lyndseybrowning / trie-prefix-tree

Create and modify trie prefix structures and extract word lists including prefixes, anagrams and sub-anagrams
48 stars 14 forks source link

Convert Dictionary to Map for stable data input order #12

Open shanghungshih opened 2 years ago

shanghungshih commented 2 years ago

In this use case, given a sorted array of words, and invoke getPrefix(x, false) with disable sort. For Alphabetical characters, it works like a charm, but for Arabic characters, it gets non-stable results. So I implemented a version of Map instead of Dictionary for stable data input order.

I publish a temporary npm module called trie-prefix-tree-v1.7. Try the example below!

const words = ['ad', 'ab', 'ac', 'aa']; const input = trie(words); const inputWithMap = trieWithMap(words);

console.log(getPrefix of 'a' from input with sort: ${JSON.stringify(input.getPrefix('a'))}); console.log(getPrefix of 'a' from input: ${JSON.stringify(input.getPrefix('a', false))}); console.log(getPrefix of 'a' from inputWithMap with sort: ${JSON.stringify(inputWithMap.getPrefix('a'))}); console.log(getPrefix of 'a' from inputWithMap: ${JSON.stringify(inputWithMap.getPrefix('a', false))}); / getPrefix of 'a' from input with sort: ["aa","ab","ac","ad"] getPrefix of 'a' from input: ["ad","ab","ac","aa"] getPrefix of 'a' from inputWithMap with sort: ["aa","ab","ac","ad"] getPrefix of 'a' from inputWithMap: ["ad","ab","ac","aa"] /


- `Arabic characters`
```js
const trie = require('trie-prefix-tree');
const trieWithMap = require('trie-prefix-tree-v1.7');

const words = ['a4', 'a2', 'a3', 'a1'];
const input = trie(words);
const inputWithMap = trieWithMap(words);

console.log(`getPrefix of 'a' from input with sort: ${JSON.stringify(input.getPrefix('a'))}`);
console.log(`getPrefix of 'a' from input: ${JSON.stringify(input.getPrefix('a', false))}`);
console.log(`getPrefix of 'a' from inputWithMap with sort: ${JSON.stringify(inputWithMap.getPrefix('a'))}`);
console.log(`getPrefix of 'a' from inputWithMap: ${JSON.stringify(inputWithMap.getPrefix('a', false))}`);
/*
getPrefix of 'a' from input with sort: ["a1","a2","a3","a4"]
getPrefix of 'a' from input: ["a1","a2","a3","a4"]
getPrefix of 'a' from inputWithMap with sort: ["a1","a2","a3","a4"]
getPrefix of 'a' from inputWithMap: ["a4","a2","a3","a1"]
*/