-
Notifications
You must be signed in to change notification settings - Fork 0
/
t9.js
68 lines (58 loc) · 1.87 KB
/
t9.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const t9 = function (dictionary) {
// Create a mapping of keypad digits to the letters they represent
const digitMap = {
2: 'abc',
3: 'def',
4: 'ghi',
5: 'jkl',
6: 'mno',
7: 'pqrs',
8: 'tuv',
9: 'wxyz',
};
// Return an object with a getWords method that predicts words based on user input
return {
getWords: function (input) {
// Remove any non-neumerical characters from the input as well as 1 and 0
input = input.replace(/[^2-9]/g, '');
// Return an empty array if the input is empty or not a string of digits
if (!input) {
return [];
}
// Convert the input string to an array of digits
const digits = input.split('');
// Generate a list of possible T9 keys for the input digits
const t9Keys = digits.reduce((keys, digit) => {
// If this is the first digit, return the letters that represent it
if (keys.length === 0) {
return digitMap[digit].split('');
}
// Otherwise, return a list of possible T9 keys
const newKeys = [];
keys.forEach((key) => {
digitMap[digit].split('').forEach((letter) => {
newKeys.push(key + letter);
});
});
return newKeys;
}, []);
// Do a fuzzy search on the T9 dictionary to find words that match the possible T9 keys
const words = fuzzySearch(t9Keys, dictionary);
return words;
},
};
};
// Returns an array of target strings that match any part of the possible queries
function fuzzySearch(possibleQueries, targetStrings) {
// Create a list of words that match the possible queries
const words = [];
possibleQueries.forEach((query) => {
targetStrings.forEach((word) => {
if (word.toLowerCase().includes(query.toLowerCase())) {
words.push(word);
}
});
});
return words;
}
module.exports = t9;