Concatenate map values whose keys are the divisors of a given integer



i have to write the body of a javascript function fizzBuzz (number, map)

Indeed , number is an integer and map is an object.

The fizzBuzz function returns a character string.

This character string is the concatenation of the map values corresponding to the keys which are divisors of the integer number passed as a parameter (in ascending order of the divisors).

If there are no keys that can divide number, the function must return the string representation of number

We have : 1 <= number <= 100

The function to be implemented is:

/**
*Concatenates values of map associated with divisors of number.
*@returns {String}
*/

function fizzBuzz(number,map){
    //Your code goes here
   return number.toString();
   
   }
   
   
var map={3: "FIZZ", 4: "BUZZ"};
console.log(fizzBuzz(5,map));  //"5"
console.log(fizzBuzz(3,map));   //"FIZZ"
console.log(fizzBuzz(4,map));   //"BUZZ"
console.log(fizzBuzz(12,map));  //"FIZZBUZZ"

So i come up with this solution below:

function fizzBuzz(number,map){
    if(number%map[key]===0) {
    return Object.keys(map).find(key => number%map[key] === 0);
    }else{
        return number.toString()
    }

}


var map={3: "FIZZ", 4: "BUZZ"};
console.log(fizzBuzz(5,map));  //"5"
console.log(fizzBuzz(3,map));   //"FIZZ"
console.log(fizzBuzz(4,map));   //"BUZZ"
console.log(fizzBuzz(12,map));  //"FIZZBUZZ"

But i have an error :ReferenceError: key is not definedand i don’t know how to fix it also i don’t know how to get the values corresponding to the keys which are divisors of number Can you give me a hand please?

Answer

key is confined to the scope of the find callback. You are trying to reference it outside:

if(number%map[key]===0) { //<-- key is not defined
    return Object.keys(map).find(key => number%map[key] === 0);
}else{
    return number.toString()
}

You are also checking whether number is divisible not by the key, but by the property value of the key:

Object.keys(map).find(key => number % map[key] === 0);
//                                       ^^^^^

Instead, replace the condition with number % map === 0.

To get the value of the properties, we can map through the keys after filtering and get the value, then join the resulting array:

function fizzBuzz(number, map) {
  const arr =  Object.keys(map).filter(key => number % key == 0).map(e => map[e]).join('');
  return arr.length == 0 ? number.toString() : arr;
}


var map = {
  3: "FIZZ",
  4: "BUZZ"
};
console.log(fizzBuzz(5, map)); //"5"
console.log(fizzBuzz(3, map)); //"FIZZ"
console.log(fizzBuzz(4, map)); //"BUZZ"
console.log(fizzBuzz(12, map)); //"FIZZBUZZ"

A ternary operator is used to check whether no keys were divisible by number, and if so, return number.



Source: stackoverflow