Last active
August 9, 2016 13:43
-
-
Save bas080/08b37137fbe498166afa to your computer and use it in GitHub Desktop.
This file contains 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
// The only function is like once but with a predicate. It remembers the return | |
// value and keeps returning that value every time the inner function is called | |
// except when the predicate returns true. In that case the new value to be | |
// stored is returned from the fn. | |
// | |
// For convenience the only function runs the fn the first time the inner | |
// function is called regardless of the return value of the predicate. | |
// | |
// The function that inspired this one: http://ramdajs.com/0.19.0/docs/#once | |
function onlyWhen(pred, fn){ | |
var once = false; | |
var old; | |
return function(current){ | |
// set the return value first time when function is called (convenience) | |
if (!once){ | |
once = true | |
old = fn.apply(this, arguments); | |
return old; | |
} | |
// check if predicate is true and if so reset the value the only function | |
// will return | |
if (pred.call(this, current, old)){ | |
old = fn.apply(this, arguments); | |
} | |
return old; | |
}; | |
} | |
// Usage | |
function newer(current, old){ | |
return (current.timestamp > old.timestamp) | |
} | |
function identity(v){ | |
return v; | |
} | |
var onlyWhenNewer = onlyWhen(newer, identity); | |
var first = { | |
timestamp: 0 | |
}; | |
var second = { | |
timestamp: 1 | |
}; | |
var third = { | |
timestamp: -1 | |
}; | |
console.log( | |
onlyWhenNewer(first), // => {timestamp: 0}; | |
onlyWhenNewer(second), // => {timestamp: 1}; | |
onlyWhenNewer(third) // => {timestamp: 1}; | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment