-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.common.js
More file actions
51 lines (48 loc) · 1.39 KB
/
string.common.js
File metadata and controls
51 lines (48 loc) · 1.39 KB
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
/*
* @title: Find Common Characters
* @description: Find Common Characters
* @author: Thorsten Kober
* @email: [email protected]
*/
function commonChars(str) {
let result = str[0].split('');
for (let i = 1; i < str.length; i++) {
const current = str[i].split('');
result = result.filter((char) => {
const index = current.indexOf(char);
// return index > -1 ? current[index] = true : false;
// if character found in current string, replace value with something
// else so that it doesn't get discovered again;
if (index > -1) {
current[index] = 'found';
return true;
}
return false;
});
}
return result;
}
function commonChars2(str) {
const start = str[0].split('');
for (let i = 1; i < str.length; i++) {
const current = str[i].split('');
const length = start.length; // eslint-disable-line
for (let j = length - 1; j >= 0; j--) {
const char = start[j];
const index = current.indexOf(char);
if (index === -1) {
start.splice(j, 1);
} else {
current.splice(index, 1);
}
}
}
return start;
}
// npx jest algorithms/string/string.common.js
test('commonChars()', () => {
expect(commonChars(['bella', 'label', 'roller'])).toEqual(['e', 'l', 'l']);
});
test('commonChars2()', () => {
expect(commonChars2(['bella', 'label', 'roller'])).toEqual(['e', 'l', 'l']);
});