简体   繁体   中英

JavaScript algorithm - Comparing two strings parameters

I am doing this algorithm exercise and I understand everything except the purpose of this conditional:

if (magazineObj[word] < 0) noteIsPossible = false

I can't find any scenario where this results -1

What is the purpose of this conditional?

This algorithm simply returns if the second parameter has all the words in the first parameter. This code I'm showing is the instructor's solution.

console.log(solution('aa abc dd', 'aa abc dd aa'))

function solution(noteText, magazineText) {
  var noteArr = noteText.split(' ')
  var magazineArr = magazineText.split(' ')
  var magazineObj = {}


  magazineArr.forEach(word => {
    if (!magazineObj[word]) magazineObj[word] = 0
    magazineObj[word]++
  })


  var noteIsPossible = true
  noteArr.forEach(word => {
    if (magazineObj[word]) {
      magazineObj[word]--
      if (magazineObj[word] < 0) noteIsPossible = false
    }
    else noteIsPossible = false
  })

  return noteIsPossible      
}

For example:

console.log(solution('aa abc dd', 'aa abc dd aa'))

In this case above it returns true. The parameter2 contains all words in parameter1.

 console.log(solution('aa abc dd ee', 'aa abc dd aa'))

In this case above it returns false. The parameter2 doesn't contain all words in parameter1. There is missing 'ee'

console.log(solution('aa abc abc dd', 'aa abc dd'))

In this case above it returns false. The parameter2 doesn't contain all words in parameter1. There is missing the another 'abc'. it must contain 2 'abc' in the parameter2 to return true

This function counts the number of time each "word" appears in the 1st string, and the result is an object like this { aa: 1, abc: 1, dd: 1 } .

The code then iterate the 2nd string, and if a word exists in the object it removes 1 from the number. If the counter is below 0, then it means that there are more instances of the word in the 2nd string than in the 1st string.

Example: 'aa abc dd aa' should produce - { aa: -1, abc: 0, dd: 0 } , and the overall result would be false .

However, this doesn't actually works because of this condition if (magazineObj[word]) . When magazineObj[word] is 0 or undefined this will be evaluated as false , and it will never reach -1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM