-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnote-construct.js
70 lines (54 loc) · 1.37 KB
/
note-construct.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
/*
*
* -------------------
* | NOTE CONSTRUCTION |
* -------------------
*
*
* Given an array of integers, find the sum of its elements.
*
* e.g.
*
* numArr = [1, 3, 4 ]
*
* constructNote(numArr) // returns 1 + 3 + 4
*
*
* */
/*
*
* ***** SOLUTION
*
* */
function constructNote(magazine, note) {
// init magazineMap
const magazineMap = {};
// populate magazineMap using for loop
for(let word of magazine) {
magazineMap[word] = magazineMap[word] + 1 || 1;
};
// loop over note
for(let word of note) {
if(!magazineMap[word]) {
return false;
};
!magazineMap[word] --;
};
// if a word is not found in magazineMap
// return false
return true;
};
/*
*
* ***** TESTS
*
* */
const magazine1 = ["hello", "are", "you", "there"];
const note1 = ["friend", "hello", "are", "you", "there"];
console.log("## TEST 1 ----- > ", constructNote(magazine1, note1)); // false
const magazine2 = ["hello", "are", "you", "there", "friend"];
const note2 = ["friend", "hello", "are", "you", "there"];
console.log("## TEST 1 ----- > ", constructNote(magazine2, note2)); // true
const magazine3 = ["hello", "are", "you", "there", "friend"];
const note3 = ["hello", "friend", "hello", "are", "you", "there"];
console.log("## TEST 1 ----- > ", constructNote(magazine3, note3)); // false