Skip to content

Instantly share code, notes, and snippets.

@komplexb
Last active November 10, 2016 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komplexb/c4ad683659f40c1181a4266961d93a6a to your computer and use it in GitHub Desktop.
Save komplexb/c4ad683659f40c1181a4266961d93a6a to your computer and use it in GitHub Desktop.
2. functional js: hiding state in a closure via https://youtu.be/kA4-b7hvWhg
// run: https://repl.it/EU15/3
function writeComment(count, author, text) {
if(count > 3) {
throw new Error(author + 'executed too many actions!!');
}
console.log(author, text); // saveComment(author, text);
return count + 1;
}
// add a function with two closures
// one risk, can't easily cache, i don't know what that means... yet
function makeWriteCommentFunction(author) {
var counter = 0;
return function(text) {
counter = writeComment(counter, author, text);
}
}
var currentUserWritesComment = makeWriteCommentFunction('byron');
currentUserWritesComment('Check out my stuff');
currentUserWritesComment('Check out my stuff');
currentUserWritesComment('Check out my stuff');
currentUserWritesComment('Check out my stuff');
currentUserWritesComment('Check out my stuff');
function writeComment(count, author, text) {
if(count > 3) {
throw new Error(author + 'executed too many actions!!');
}
console.log(author, text); // saveComment(author, text);
return count + 1;
}
var counter = 0;
counter = writeComment(counter, 'bbuckley', 'Check this out');
counter = writeComment(counter, 'bbuckley', 'Check this out');
counter = writeComment(counter, 'bbuckley', 'Check this out');
counter = writeComment(counter, 'bbuckley', 'Check this out');
counter = writeComment(counter, 'bbuckley', 'Check this out');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment