Skip to content

Instantly share code, notes, and snippets.

@pixelpicosean
Last active April 19, 2018 04:36
Show Gist options
  • Save pixelpicosean/4788a1063650be856964fbf5bf1f2843 to your computer and use it in GitHub Desktop.
Save pixelpicosean/4788a1063650be856964fbf5bf1f2843 to your computer and use it in GitHub Desktop.
var CreateReactiveNumber = function(initValue, min, max, callback) {
var _value = initValue;
var value = function(newVal) {
if (arguments.length > 0) {
var oldVal = _value;
_value = newVal;
if ((oldVal > min && oldVal < max) !== (newVal > min && newVal < max)) {
callback((newVal > min && newVal < max) ? 'enter' : 'leave', _value);
}
return _value;
} else {
return _value;
}
}
return value;
};
var something = CreateReactiveNumber(0, 10, 20, function(action, value) {
console.log('number "' + action + '" range(10, 20)');
});
// change value in your game
console.log('start value is ' + something());
something(12); // 'enter'
something(18); // no log
something(24); // 'leave'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment