-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathscramblies.js
71 lines (61 loc) · 1.92 KB
/
scramblies.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
69
70
71
// scramble('rkqodlw', 'world') ==> True
// scramble('cedewaraaossoqqyt', 'codewars') ==> True
// scramble('katas', 'steak') ==> False
function scramble(str1, str2) {
// a place to store str1 letter counts
const letterCounts = {};
// iterate over str1
for (let i = 0; i < str1.length; i++) {
// set a property on the object that is the current letter
// if the property didn't exist, set it to 1
// otherwise increment the value
const currentLetter = str1[i];
letterCounts[currentLetter] = letterCounts[currentLetter] || 0;
letterCounts[currentLetter]++;
}
console.log(letterCounts);
// iterate over str2
for (let i = 0; i < str2.length; i++) {
const currentLetter = str2[i];
// if the current letter is in the object and the count is greater than 0
if (letterCounts[currentLetter] > 0) {
// decrement the count
letterCounts[currentLetter]--;
} else {
// else break out of the loop
return false;
}
}
console.log(letterCounts);
return true;
}
function scramble(str1, str2) {
const letterCounts = str1.split('').reduce((letterCounts, currentLetter) => {
letterCounts[currentLetter] = letterCounts[currentLetter] || 0;
letterCounts[currentLetter]++;
return letterCounts;
}, {});
return str2.split('').every((currentLetter) => {
if (letterCounts[currentLetter] > 0) {
letterCounts[currentLetter]--;
return true;
} else {
return false;
}
});
}
function scramble(str1, str2) {
const letterCounts = Array.prototype.reduce.call(str1, (letterCounts, currentLetter) => {
letterCounts[currentLetter] = letterCounts[currentLetter] || 0;
letterCounts[currentLetter]++;
return letterCounts;
}, {});
return Array.prototype.every.call(str2, (currentLetter) => {
if (letterCounts[currentLetter] > 0) {
letterCounts[currentLetter]--;
return true;
} else {
return false;
}
});
}