-
Notifications
You must be signed in to change notification settings - Fork 0
/
383. Ransom Note.js
32 lines (26 loc) · 954 Bytes
/
383. Ransom Note.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
class Test {
canConstruct(ransomNote, magazine) {
const groupedMagazine = this.groupByChar(magazine);
const groupedRansomNote = this.groupByChar(ransomNote);
return Object.keys(groupedRansomNote).reduce((res, c) =>
res && groupedRansomNote[c] <= groupedMagazine[c]
, true);
}
groupByChar(str) {
return str.split('').reduce((res, c) => {
res[c] = res[c] ? ++res[c] : 1;
return res;
}, {});
}
}
const testExecutor = new Test();
const testCase = [
{ransom: 'aabb', magazine: 'aaaabbbb', result: true},
{ransom: 'aabb', magazine: 'ab', result: false},
{ransom: 'aabb', magazine: 'aabb', result: true},
{ransom: 'abc', magazine: 'abd', result: false},
];
testCase.forEach(testCase => {
console.log('Executing test', testCase);
console.assert(testExecutor.canConstruct(testCase.ransom, testCase.magazine) === testCase.result)
})