JavaScript / Lucky Numbers
Task number 2:
My solution:
export function luckyNumber(value) {
for (let i = 0; i < value.length / 2; i++) {
if (value[i] !== value[value.length - 1 - i])
return false;
}
return true;
}
I don’t understand why it doesn’t work. (It’s return only true)
IsaacG
March 24, 2025, 4:47pm
2
Could you share the output from the failing test? What inputs is the function being called with?
Of course
Code Run
expect(luckyNumber(15651)).toBe(true);
expect(luckyNumber(48911984)).toBe(true);
Everything is fine here
Code Run
expect(luckyNumber(156512)).toBe(false);
expect(luckyNumber(48921984)).toBe(false);
Test Failure
Error: expect(received).toBe(expected) // Object.is equality Expected: false Received: true
Code Run
expect(luckyNumber(0)).toBe(true);
expect(luckyNumber(33)).toBe(true);
expect(luckyNumber(12)).toBe(false);
Test Failure
Error: expect(received).toBe(expected) // Object.is equality Expected: false Received: true
IsaacG
March 24, 2025, 4:58pm
4
Consider number 156512
. Can you explain the steps that your code would go through to return false?
It should compare the number 1 (From the beginning) and the number 2 (From the end), and since they are not equal immediately, return false without repeating the loop.
glennj
March 24, 2025, 5:24pm
6
What should happen here in javascript: 5678[1]
? What about 5678.length
?
I solved it using this method, but I still miss the error of the previous code.
export function luckyNumber(value) {
let strValue = String(value).split(‘’);
let strValueReverse = strValue.slice().reverse();
for (let i = 0; i < strValue.length / 2; i++) {
if (strValue[i] !== strValueReverse[i])
return false;
}
return true;
}
atk
March 25, 2025, 7:50am
8
You attempt to use a number as a string, which obviously does not work. (2).length
is always undefined, so your for-loop will never run.
You can mathematically reverse the number:
export function luckyNumber(value) {
let n = value, rev = 0;
while (n) {
rev = rev * 10 + (n % 10);
n = Math.floor(n / 10);
}
return value = rev;
}
Alternatively, you can use array methods to reverse the number:
export function luckyNumber(value) {
const numStr = value.toString();
return numStr === [...numStr].reverse().join('');
}
Which is more concise, but less performant.
glennj
March 25, 2025, 11:24am
9
Please try to avoid handing out the answer.