-
Notifications
You must be signed in to change notification settings - Fork 0
/
word_finder.js
35 lines (27 loc) · 992 Bytes
/
word_finder.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/*
In this kata you have to extend the dictionary with a method, that returns a list of words matching a pattern.
This pattern may contain letters (lowercase) and placeholders ("?"). A placeholder stands for exactly one arbitrary letter.
*/
function Dictionary(words) {
this.words = words;
}
Dictionary.prototype.getMatchingWords = function(pattern) {
var rx = /\?/g, matches = [], pattern_orig = pattern;
for (let w = 0; w < this.words.length; w++) {
while (rx.exec(pattern)) {
pattern = pattern.replace(/\?/, this.words[w][rx.lastIndex-1]);
}
if (pattern === this.words[w]) { matches.push(pattern); }
pattern = pattern_orig;
}
return matches;
}
var fruits = new Dictionary(['banana', 'apple', 'papaya', 'cherry']);
fruits.getMatchingWords('lemon');
// []
fruits.getMatchingWords('cherr??');
// []
fruits.getMatchingWords('?a?a?a');
// ['banana', 'papaya']
fruits.getMatchingWords('??????');
// ['banana', 'papaya', 'cherry']