Skip to content

Instantly share code, notes, and snippets.

@alvivi
Created May 27, 2013 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alvivi/5656395 to your computer and use it in GitHub Desktop.
Save alvivi/5656395 to your computer and use it in GitHub Desktop.
export interface IChecker {
check: (word: string) => boolean;
};
export interface ClumsyEntry {
valid: boolean;
children: ClumsyEntries;
}
export interface ClumsyEntries {
[letter: string]: ClumsyEntry;
}
export interface ClumsyStats {
letters: number;
nodes: number;
words: number;
}
export class ClumsyChecker implements IChecker {
tree: ClumsyEntry = {valid: false, children: {}};
stats: ClumsyStats = {letters: 0, nodes: 1, words: 0};
add (word: string): void {
var node = this.tree;
for (var i = 0; i < word.length; i++) {
var letter = word[i].toLowerCase();
if (!node.children[letter]) {
node.children[letter] = {valid: false, children: {}};
this.stats.nodes += 1;
}
node = node.children[letter];
node.valid = (i == word.length - 1) || node.valid;
this.stats.letters += 1;
}
this.stats.words += 1;
}
check (word: string): boolean {
var node = this.traverse(word);
if (node === null) {
return false;
} else {
return node.valid;
}
}
private traverse (word: string): ClumsyEntry {
var node = this.tree;
for (var i = 0; i < word.length; i++) {
var letter = word[i].toLowerCase();
if (!node.children[letter]) {
return null;
} else {
node = node.children[letter];
}
}
return node;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment