Last active
December 12, 2017 07:54
-
-
Save alpenfritz/ec93528c031bf7e315922e9e74e5907b to your computer and use it in GitHub Desktop.
JS BinUnderstand _.once function// source https://jsbin.com/mumoxip
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
// var chores = function () { | |
// var tasks = ['laundry', 'dishes', 'vaccuum', 'dust']; | |
// return { | |
// doChores: function () { | |
// console.log(tasks.pop()); | |
// }, | |
// addChores: function (task) { | |
// tasks.push(task); | |
// return task; | |
// } | |
// } | |
// } | |
// var house1 = chores(); | |
// house1.doChores(); | |
// house1.doChores(); | |
// house1.doChores(); | |
// house1.addChores('water plants'); | |
// house1.doChores(); | |
// var house2 = chores(); | |
// house2.doChores(); | |
var greeting = function () { | |
return 'hello world!'; | |
} | |
var greeting2 = function () { | |
return 'konnichiwa'; | |
} | |
var _ = {}; | |
_.once = function (fn) { | |
// keep track of when the function has been called | |
var called = false; | |
// keep track of the result | |
var result; | |
return function () { | |
// and use the result if the function has already been called | |
if (!called) { | |
called = true; | |
console.log('called!'); | |
result = fn(); | |
} | |
return result; | |
} | |
}; | |
var foo = _.once(greeting); | |
console.log(foo()); | |
console.log(foo()); | |
// var foo2 = _.once(greeting2); | |
// foo2(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment