From 8d04fec5ecf863a1c2233bc68c09fe249b8b3547 Mon Sep 17 00:00:00 2001 From: Rathes Sachchithananthan Date: Fri, 23 Oct 2026 12:55:33 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=20Build=20each=20transliteration=20ta?= =?UTF-8?q?ble=20once=20instead=20of=20on=20every=20call?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every call rebuilt the lookup table by spreading an object per letter, about 1.8 ms per call since the Grantha rows were added. The tables are now built once per notation and Grantha setting: about 1 µs per call. --- src/index.spec.ts | 7 +++++++ src/index.ts | 23 +++++++++++++++++------ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/index.spec.ts b/src/index.spec.ts index cb8a344..67a2370 100644 --- a/src/index.spec.ts +++ b/src/index.spec.ts @@ -45,6 +45,13 @@ describe('script tests', () => { expect(getRomanization('+அம்!மாஜ்--!', { grantha: false })).toEqual('+am!maaஜ்--!'); }); + it('keeps the grantha option apart between calls', () => { + expect(getIso15919('ஜன்னல்')).toEqual('jaṉṉal'); + expect(getIso15919('ஜன்னல்', { grantha: false })).toEqual('ஜṉṉal'); + expect(getIso15919('ஜன்னல்')).toEqual('jaṉṉal'); + expect(getIPA('ஜன்னல்', { grantha: false })).toEqual('ஜnnal'); + }); + it('transliterates grantha letters with a vowel', () => { expect(getIso15919('ஜன்னல்')).toEqual('jaṉṉal'); expect(getIPA('ஜன்னல்')).toEqual('d͡ʑannal'); diff --git a/src/index.ts b/src/index.ts index e8363a8..8d2bd06 100644 --- a/src/index.ts +++ b/src/index.ts @@ -17,13 +17,24 @@ export type Options = { export const script = data as Script[][]; export const granthaScript = grantha as Script[][]; -const transliterate = (phrase: string, notation: 'romanization' | 'iso15919' | 'ipa', options?: Options) => { - const notationMap = [...script, ...(options?.grantha === false ? [] : grantha)] - .flat() - .reduce( - (scripts, newScript) => ({ ...scripts, [newScript.script]: newScript[notation] }), - {} as Record, +type Notation = 'romanization' | 'iso15919' | 'ipa'; + +const notationMaps = new Map>(); + +const getNotationMap = (notation: Notation, withGrantha: boolean) => { + const key = `${notation}:${withGrantha}`; + let notationMap = notationMaps.get(key); + if (!notationMap) { + notationMap = Object.fromEntries( + [...script, ...(withGrantha ? grantha : [])].flat().map((letter) => [letter.script, letter[notation]]), ); + notationMaps.set(key, notationMap); + } + return notationMap; +}; + +const transliterate = (phrase: string, notation: Notation, options?: Options) => { + const notationMap = getNotationMap(notation, options?.grantha !== false); return phrase .split(' ')