Write createSequence(start, step) returning next, peek and reset functions, and generate invoice numbers starting at 1001 in steps of 1 and even numbers starting at 0.
Solution
main.js
function createSequence(start = 0, step = 1) {
let current = start;
return {
next: () => { const v = current; current += step; return v; },
peek: () => current,
reset: () => { current = start; },
};
}
const invoice = createSequence(1001);
const evens = createSequence(0, 2);
console.log(invoice.next(), invoice.next(), evens.next(), evens.next(), evens.next());
console.log("next invoice will be", invoice.peek());
invoice.reset();
console.log(invoice.next());
Output Verified by running it on Node.js
1001 1002 0 2 4
next invoice will be 1003
1001
start, step and current all live in the closure; reset can restore the original start because the factory's parameters are remembered too.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!