JavaScript Count Backward by Evens: Two Approaches Quiz
Two seeded approaches to enumerate even numbers descending from n (filter-on-step-1 vs step-2 loop), plus two companions on Array.from and an odd-start edge case.
1,121 views
36
Implement countBackward(n) that returns an array of even numbers descending from n down to (but excluding) 0. Solve it with a step-1 loop and an internal filter.
Examples
Example 1:
Input: 12
Output: [12, 10, 8, 6, 4, 2]
Explanation: Every even number from 12 down to 2 inclusive.Example 2:
Input: 7
Output: [6, 4, 2]
Explanation: 7 is odd, so the loop skips it and starts collecting at 6.function countBackward(n) {
// your solution comes here, with a step-1 loop and a filter check
}Solve the same problem more efficiently with a step-2 loop, handling the case where n is odd by snapping the start down. Why is this version exactly twice as fast?
Examples
Example 1:
Input: 10
Output: [10, 8, 6, 4, 2]
Explanation: The loop visits only the evens; no parity check is needed.Example 2:
Input: 11
Output: [10, 8, 6, 4, 2]
Explanation: 11 is odd, so the start snaps down to 10 with `n - (n % 2)`.function countBackward(n) {
// your solution comes here, with `i -= 2`
}Re-express the same problem declaratively with Array.from and a computed length, then reverse. When is this version a better fit than a hand-rolled loop?
Examples
Example 1:
Input: 8
Output: [8, 6, 4, 2]
Explanation: Length is 4 (i.e. 8/2), and the mapping produces 2, 4, 6, 8; reversing yields the descending list.function countBackward(n) {
// your solution comes here, with Array.from and reverse
}Edge cases: what should countBackward(0), countBackward(1), and countBackward(-4) return? Justify each choice.
Examples
Example 1:
Input: 0
Output: []
Explanation: The loop guard `i > 0` is false on entry, so nothing is pushed.Example 2:
Input: -4
Output: []
Explanation: For a negative n the descending semantics are undefined; returning an empty array is the safest default.function countBackward(n) {
if (typeof n !== 'number' || !Number.isInteger(n) || n <= 1) return [];
const result = [];
for (let i = n - (n % 2); i > 0; i -= 2) result.push(i);
return result;
};