Solved: Issues checking if Map contains key

Question:

I am trying to implement a function that returns the prime factors of integers as a Map in JavaScript. My code is as follows:

function getPrimeFactorsBelow(n) {
var factors = new Map();

for (let i = 2; i < n / 2 + 1; i++) { if (!factors.has(i)) { for (let j = i * 2; j < n; j += i) { if (!factors.has(j)) { factors[j] = [i]; } else { factors[j].push(i); } } } } return factors; } console.log(getPrimeFactorsBelow(10));[/code]


However, the else part never executes, as though .has() doesn’t detect that the map contains the keys. What am I missing?

Best Answer:

To add an element to a Map use the set method. To get an element use the get method. Is this what you want to achieve ?

function getPrimeFactorsBelow(n) {
var factors = new Map();

for (let i = 2; i < n / 2 + 1; i++) { if (!factors.has(i)) { for (let j = i * 2; j < n; j += i) { if (!factors.has(j)) { factors.set(j, []); } factors.get(j).push(i); } } } return factors; [/code]

If you have better answer, please add a comment about this, thank you!

Source: Stackoverflow.com