Tell us what’s happening:
I was thinking that my code should be passing the tests, so I went to JS Bin (see the test here), tested it and it’s working. It doesn’t pass the challenge’s tests, and in the browser’s console I’m getting this:
TypeError: unknown: Cannot read property '0' of undefined
at Function.e.get (commons-b48a099b457b77b5ddc8.js:32)
at e.h [as unshiftContainer] (commons-b48a099b457b77b5ddc8.js:49)
at t.<anonymous> (commons-b48a099b457b77b5ddc8.js:21)
at r (commons-b48a099b457b77b5ddc8.js:49)
at e.o [as _call] (commons-b48a099b457b77b5ddc8.js:48)
at e.i [as call] (commons-b48a099b457b77b5ddc8.js:48)
at e.a [as visit] (commons-b48a099b457b77b5ddc8.js:48)
at e.visitQueue (commons-b48a099b457b77b5ddc8.js:47)
at e.visitMultiple (commons-b48a099b457b77b5ddc8.js:47)
at e.visit (commons-b48a099b457b77b5ddc8.js:47)
Your code so far (spoilers):
function sumPrimes(num) {
/*
JavaScript implementation of Sieve of Eratosthenes
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Pseudocode
*/
// object with all numbers in range 2, 3, 4, ... num
let primesObj = {};
for (let i = 2; i <= num; primesObj[i++] = true);
for (let i = 2; i < Math.sqrt(num); i++) {
// if it is prime
if (primesObj[i]) {
// for j = i^2, i^2+i, i^2+2i, i^2+3i, ..., not exceeding num
for (let j = 0; j < num; j++) {
primesObj[Math.pow(i, 2) + j * i] = false;
}
}
}
let sum = 0;
// iterate thru the object's properties
for (let n in primesObj) {
if (primesObj[n]) {
sum += +n;
}
}
return sum;
}
sumPrimes(10);
Your browser information:
Chrome:
“Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36”
Firefox:
“Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0”
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes/