diff --git a/src/_DataStructures_/Trees/Trie/all-words-in-trie/all-words-in-trie.test.js b/src/_DataStructures_/Trees/Trie/all-words-in-trie/all-words-in-trie.test.js new file mode 100644 index 00000000..ae9b2e99 --- /dev/null +++ b/src/_DataStructures_/Trees/Trie/all-words-in-trie/all-words-in-trie.test.js @@ -0,0 +1,61 @@ +const allWordsInTrie = require('./index'); +const Trie = require('../index'); + +describe('Data Structure : Trie : All Words In Tree', () => { + it('Should return all words sorted alphabetically', () => { + const words = ['bed', 'ball', 'apple', 'java', 'javascript', 'bed']; + const trie = new Trie(); + + words.forEach(word => trie.insert(word)); + + const result = allWordsInTrie(trie.root); + + const expected = ['apple', 'ball', 'bed', 'bed', 'java', 'javascript']; + expect(expected).toEqual(result); + }); + + it('Should retain duplicates', () => { + const words = ['bed', 'bed', 'bed']; + const trie = new Trie(); + + words.forEach(word => trie.insert(word)); + + const result = allWordsInTrie(trie.root); + expect(result.length).toBe(3); + }); + + it('passing an empty array of words returns an empty array', () => { + const words = []; + const trie = new Trie(); + + words.forEach(word => trie.insert(word)); + + const result = allWordsInTrie(trie.root); + expect(result).toEqual([]); + }); + + it('passing an empty Trie will throw an error ', () => { + const trie = new Trie(); + expect(() => { + allWordsInTrie(trie); + }).toThrow('Invalid argument: Root of Trie is required'); + }); + + it('passing an empty array will throw an error ', () => { + expect(() => { + allWordsInTrie([]); + }).toThrow('Invalid argument: Root of Trie is required'); + }); + + it('passing null will throw an error ', () => { + expect(() => { + allWordsInTrie([]); + }).toThrow('Invalid argument: Root of Trie is required'); + }); + + it('passing an array not in a Trie will throw an error ', () => { + expect(() => { + allWordsInTrie(['bed', 'ball', 'apple']); + }).toThrow('Invalid argument: Root of Trie is required'); + }); +}); diff --git a/src/_DataStructures_/Trees/Trie/all-words-in-trie/index.js b/src/_DataStructures_/Trees/Trie/all-words-in-trie/index.js index bc814859..d46a66ec 100644 --- a/src/_DataStructures_/Trees/Trie/all-words-in-trie/index.js +++ b/src/_DataStructures_/Trees/Trie/all-words-in-trie/index.js @@ -1,5 +1,6 @@ // eslint-disable-next-line no-unused-vars const Trie = require('../index'); +const TrieNode = require('../Node'); function getAllWords(root, level, word) { let result = []; @@ -30,6 +31,10 @@ function getAllWords(root, level, word) { } function allWordsFromTrie(root) { + if (!(root instanceof TrieNode)) { + throw new Error('Invalid argument: Root of Trie is required'); + } + const word = []; // char arr to store a word for (let i = 0; i < 26; i += 1) { word[i] = null;