Last active
July 5, 2016 23:34
-
-
Save chris-martin/750d885b3171fd7cc1b8428c4e2d656f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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