const harmlessRansomeNote = (noteText, magazineText) => { //split both string parameters into arrays let noteArr = noteText.split(' '); let magArr = magazineText.split(' ');
//create an object to use as a hash table it also avoids exponential time complexity of nested loops let magObj = {};
//forEach to check if word is an word is an object on our property magArr.forEach(word => { //if not we add it to our object //increment the value if (!magObj[word]) { magObj[word] = 1; } else { //otherwise, if it is there //we just increment the value magObj[word]++; } }); // { this: 1, is: 2, my: 1, note: 1 }
//Boolean variable to be return from function let noteIsPossible = true;
//use forEach to iterate through each word noteArr.forEach(word => { //if word is found on the object decrement it if (magObj[word]) { magObj[word]--; //if word value < 0 we can't make our word so note is NOT possible. if (magObj[word] < 0) { noteIsPossible = false; } //if word is not found then the note is NOT possible. } else { noteIsPossible = false; } });
return noteIsPossible; };
console.log(harmlessRansomeNote('this is my note', 'this is is my note')); // true