GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

No menu could be recovered. Follow the blue links in the page.

This view

  • Original page
  • New address

GeezerVison is showing javascript.info — Set and decrease for counter

  • Tutorial
  • The JavaScript language
  • Advanced working with functions
  • Function object, NFE
back to the lesson

Set and decrease for counter

importance: 5

Modify the code of makeCounter() so that the counter can also decrease and set the number:

  • counter() should return the next number (as before).
  • counter.set(value) should set the counter to value.
  • counter.decrease() should decrease the counter by 1.

See the sandbox code for the complete usage example.

P.S. You can use either a closure or the function property to keep the current count. Or write both variants.

Open a sandbox with tests.

The solution uses count in the local variable, but addition methods are written right into the counter. They share the same outer lexical environment and also can access the current count.

function makeCounter() {
  let count = 0;

  function counter() {
    return count++;
  }

  counter.set = value => count = value;

  counter.decrease = () => count--;

  return counter;
}

Open the solution with tests in a sandbox.

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.