Tell us what’s happening:
Hi, I expect smallestCommons to return the value of the variable after the return statement, lcm. However, it returns undefined. The line before it executes and says that lcm is type number and has a value. Why is the function returning undefined despite it having a return statement and following expression?
Thanks!
Your code so far
function range(a, b) {
/* return an array of the numbers between a and b, inclusive */
const low = a < b ? a : b;
const high = a > b ? a : b;
let nums = [];
for (let i = low; i <= high; i++) {
nums.push(i);
}
return nums;
}
function multiples_lt_n(x, n) {
let multiples = [];
for (let i = 1; ; i++) {
let multiple = x * i;
if (multiple > n) {
break;
}
multiples.push(multiple)
}
return multiples;
}
function smallestCommons(arr) {
const divisors = range(arr[0], arr[1]);
const comMult = divisors.reduce((acc, n) => acc * n);
const allMults = divisors.map(n => multiples_lt_n(n, comMult));
let noSubArrs = allMults.reduce((acc, n) => acc.concat(n), []);
let comMults = new Set();
for (let i in noSubArrs) {
if (allMults.every(arr => arr.includes(noSubArrs[i]))) {
comMults.add(noSubArrs[i]);
}
}
let comMultsArr = Array.from(comMults);
const lcm = comMultsArr.shift();
console.log(typeof lcm, lcm);
return lcm;
}
smallestCommons([1,5]);
Your browser information:
User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:80.0) Gecko/20100101 Firefox/80.0
.
Challenge: Smallest Common Multiple
Link to the challenge: