How to determine if an anagram of a smaller string is found in a larger word

Here is one way to determine whether an anagram of a smaller string is found in a larger word.

subAnagramTry in REPL
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
function subAnagram(anagram, string) {
const m = anagram.length;
const n = string.length;
if (m > n) return false;
const target = anagram.split('').reduce((accum, char) => {
if (!accum[char]) {
accum[char] = 1;
} else {
accum[char] = accum[char]++;
}
return accum;
},{});
anagram.split('').forEach((char, i) => {
const c = string[i];
if (target[c]) target[c]--;
});
let discrepancy = Object.keys(target).reduce((accum, char) => accum + Math.abs(target[char]), 0);
for ( let i = m; i < n; i++ ) {
if (discrepancy === 0) {
return true;
} else {
let c = string[i-m];
if (target[c] !== undefined) {
target[c]++;
(target[c] > 0 && discrepancy++) || (discrepancy--);
}
c = string[i];
if (target[c] !== undefined) {
target[c]--;
(target[c] < 0 && discrepancy++) || (discrepancy--);
}
}
}
return discrepancy === 0;
}