LearnFrenzy
Sign in Take a free test

Closures · Closures Coding Problems · Question 6

A resettable number sequence in JavaScript Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links