Skip to content

Commit

Permalink
add Trie
Browse files Browse the repository at this point in the history
  • Loading branch information
gkucmierz committed Jun 11, 2024
1 parent 4c58318 commit a323002
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
36 changes: 36 additions & 0 deletions spec/Trie.spec.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@

import {
Trie,
} from '../src/Trie.mjs';

describe('Trie', () => {
it('check empty', () => {
const trie = Trie();
expect(trie.has('')).toBe(false);
expect(trie.has('abc')).toBe(false);
});

it('init data', () => {
const trie = Trie(['abc', '']);
expect(trie.has('')).toBe(true);
expect(trie.has('abc')).toBe(true);
});

it('add/readd data', () => {
const trie = Trie();
expect(trie.has('')).toBe(false);
expect(trie.add('')).toBe(true);
expect(trie.has('')).toBe(true);
expect(trie.add('')).toBe(false);
});

it('list data', () => {
const trie = Trie(['abc', '', 'abcdef', 'xyz']);
const abc = ['abc', 'abcdef'];
expect(trie.get('a')).toEqual(abc);
expect(trie.get('ab')).toEqual(abc);
expect(trie.get('abc')).toEqual(abc);
expect(trie.get('aa')).toEqual([]);
expect(trie.get('')).toEqual(['', 'abc', 'abcdef', 'xyz']);
});
});
45 changes: 45 additions & 0 deletions src/Trie.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@

export const Trie = (words = []) => {
const HAS = 0;
const MAP = 1;
const data = [false, new Map()];
const add = word => {
let node = data;
for (let i = 0; i < word.length; ++i) {
const char = word[i];
if (!node[MAP]) node[MAP] = new Map();
const child = node[MAP].get(char) ?? [false];
node[MAP].set(char, child);
node = child;
}
if (node[HAS]) return false;
node[HAS] = true;
return true;
};
const findNode = word => {
let node = data;
for (let i = 0; i < word.length; ++i) {
const char = word[i];
if (!node[MAP]?.has(char)) return [false];
node = node[MAP].get(char);
}
return node;
};
const has = word => findNode(word)[HAS];
const get = begin => {
const res = [];
const loop = (node, str = '') => {
if (!node) return;
if (node[HAS]) res.push(begin + str);
const map = node[MAP] || new Map();
[...map].map(([char, node]) => loop(node, str + char));
};
loop(findNode(begin));
return res;
};
words.map(word => add(word));
return {
add, has, get,
getData: () => data,
};
};

0 comments on commit a323002

Please sign in to comment.