-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path5-kyu-where-my-anagrams-at.js
50 lines (40 loc) · 1.38 KB
/
5-kyu-where-my-anagrams-at.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
// 5 kyu | Where my anagrams at?
// https://www.codewars.com/kata/where-my-anagrams-at
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// const anagrams = (word, words) => {
// const letterCounts = w => {
// const cnts = new Array(26).fill(0);
// for (let c of [...w]) cnts[c.charCodeAt(0) - 97]++;
// return cnts.join('');
// };
// const wordCnt = letterCounts(word);
// const res = [];
// for (let wordsWord of words) {
// const wordsWordCnts = letterCounts(wordsWord);
// if (wordCnt === wordsWordCnts) res.push(wordsWord);
// }
// return res;
// };
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
const letterCounts = w =>
[...w]
.reduce((acc, curr) => {
acc[curr.charCodeAt(0) - 97]++;
return acc;
}, new Array(26).fill(0))
.join('');
const anagrams = (word, words) => {
const wordCnts = letterCounts(word);
return words.filter(w => wordCnts === letterCounts(w));
};
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
import { deepStrictEqual } from 'assert';
deepStrictEqual(anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']), [
'aabb',
'bbaa',
]);
deepStrictEqual(
anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']),
['carer', 'racer'],
);
deepStrictEqual(anagrams('laser', ['lazing', 'lazy', 'lacer']), []);