Skip to content

Instantly share code, notes, and snippets.

@chris-martin
Last active July 5, 2016 23:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chris-martin/750d885b3171fd7cc1b8428c4e2d656f to your computer and use it in GitHub Desktop.
Save chris-martin/750d885b3171fd7cc1b8428c4e2d656f to your computer and use it in GitHub Desktop.
'use strict';
const x = (() => {
// This is always >= 0
let nonNegative = 0;
return {
// Return the value
get: () => nonNegative,
// Add some number to the value, and call the callback with the new value.
add: (offset, callback) => {
// The value is not allowed to go below 0!
if (nonNegative + offset < 0) throw 'Too low!';
// Let the listener know what the new value is
if (callback) callback(nonNegative + offset);
// Make the change
nonNegative += offset;
}
};
})();
x.add(1, console.log); // 1
x.add(-1, () => x.add(-1))
console.log(x.get()); // -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment