Skip to content

Commit 504d873

Browse files
authored
Merge pull request knaxus#148 from ChristieRobson/test/all-words-in-trie
test: add test for all-words-in-tree
2 parents 37fd3af + 3d02b9e commit 504d873

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
const allWordsInTrie = require('./index');
2+
const Trie = require('../index');
3+
4+
describe('Data Structure : Trie : All Words In Tree', () => {
5+
it('Should return all words sorted alphabetically', () => {
6+
const words = ['bed', 'ball', 'apple', 'java', 'javascript', 'bed'];
7+
const trie = new Trie();
8+
9+
words.forEach(word => trie.insert(word));
10+
11+
const result = allWordsInTrie(trie.root);
12+
13+
const expected = ['apple', 'ball', 'bed', 'bed', 'java', 'javascript'];
14+
expect(expected).toEqual(result);
15+
});
16+
17+
it('Should retain duplicates', () => {
18+
const words = ['bed', 'bed', 'bed'];
19+
const trie = new Trie();
20+
21+
words.forEach(word => trie.insert(word));
22+
23+
const result = allWordsInTrie(trie.root);
24+
expect(result.length).toBe(3);
25+
});
26+
27+
it('passing an empty array of words returns an empty array', () => {
28+
const words = [];
29+
const trie = new Trie();
30+
31+
words.forEach(word => trie.insert(word));
32+
33+
const result = allWordsInTrie(trie.root);
34+
expect(result).toEqual([]);
35+
});
36+
37+
it('passing an empty Trie will throw an error ', () => {
38+
const trie = new Trie();
39+
expect(() => {
40+
allWordsInTrie(trie);
41+
}).toThrow('Invalid argument: Root of Trie is required');
42+
});
43+
44+
it('passing an empty array will throw an error ', () => {
45+
expect(() => {
46+
allWordsInTrie([]);
47+
}).toThrow('Invalid argument: Root of Trie is required');
48+
});
49+
50+
it('passing null will throw an error ', () => {
51+
expect(() => {
52+
allWordsInTrie([]);
53+
}).toThrow('Invalid argument: Root of Trie is required');
54+
});
55+
56+
it('passing an array not in a Trie will throw an error ', () => {
57+
expect(() => {
58+
allWordsInTrie(['bed', 'ball', 'apple']);
59+
}).toThrow('Invalid argument: Root of Trie is required');
60+
});
61+
});

src/_DataStructures_/Trees/Trie/all-words-in-trie/index.js

+5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// eslint-disable-next-line no-unused-vars
22
const Trie = require('../index');
3+
const TrieNode = require('../Node');
34

45
function getAllWords(root, level, word) {
56
let result = [];
@@ -30,6 +31,10 @@ function getAllWords(root, level, word) {
3031
}
3132

3233
function allWordsFromTrie(root) {
34+
if (!(root instanceof TrieNode)) {
35+
throw new Error('Invalid argument: Root of Trie is required');
36+
}
37+
3338
const word = []; // char arr to store a word
3439
for (let i = 0; i < 26; i += 1) {
3540
word[i] = null;

0 commit comments

Comments
 (0)