Skip to content

Instantly share code, notes, and snippets.

@jafow
Created April 24, 2016 20:14
Show Gist options
  • Save jafow/51d44fec061658622e44fe2b968ad483 to your computer and use it in GitHub Desktop.
Save jafow/51d44fec061658622e44fe2b968ad483 to your computer and use it in GitHub Desktop.
Example once implementation
/** Once takes a function as an argument and returns a function or undefined, depending on whether the fn passed as an argument
* has been called. If that function hasn't been invoked, Once will return the value of that function applied to any arguments.
* otherwise it will return undefined.
*/
// implementation #1
function once (fn) {
var run = false
return function () {
if (run) return void 0
else {
run = true
return fn.apply(this, arguments)
}
}
}
// Example
var withdrawCash = once(function () {
console.log('you withdrew some cash!');
})
withdrawCash() // => 'you withdrew some cash!'
withdrawCash() // => undefined
// implementation #2
const once2 = (fn) => {
let run = false
return function () {
return run
? void 0
: ((run = true), fn.apply(this, arguments))
}
}
// Example
const sayBye = (name) => `bye bye ${name}`
const sayByeOnce = once2(sayBye)
sayByeOnce('Jeremy') // => 'bye bye Jeremy'
sayByeOnce('Jeremy') // => undefined
sayByeOnce('Alice') // => undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment