Last active
August 16, 2018 01:24
-
-
Save wichopy/6ce609594888f5bfba1bb5ee8bb76c00 to your computer and use it in GitHub Desktop.
higher order single click function
This file contains hidden or 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
//Wrap an onclick handler | |
const once = fn => { | |
let done = false; | |
return (...args) => { | |
if (!done) { | |
done = true; | |
fn(...args); | |
} | |
} | |
} | |
//usage: | |
let onSubmitPayment = (items, prices) { | |
// ... | |
} | |
<button onClick={once(onSubmitPayment)(items, prices)}></button> | |
// test: | |
const squeak = a => console.log(a, " squeak!!"); | |
squeak("original"); // "original squeak!!" | |
squeak("original"); // "original squeak!!" | |
squeak("original"); // "original squeak!!" | |
const squeakOnce = once(squeak); | |
squeakOnce("only once"); // "only once squeak!!" | |
squeakOnce("only once"); // no output | |
squeakOnce("only once"); // no output | |
const thisManyTimes = (fn, n) => { | |
let runsLeft = n | |
return (...args) => { | |
if (n > 0) { | |
n--; | |
fn(...args); | |
} | |
} | |
} | |
thisManyTimes(fn,1) | |
const alternator = (fn1, fn2) => { | |
let first = fn1 | |
let second = fn2 | |
let flag = 0 | |
return (...args) => { | |
if (flag) { | |
flag = 0 | |
first(...args) | |
} else { | |
flag = 1 | |
second(...args) | |
} | |
} | |
} | |
let sayA = () => console.log("A"); | |
let sayB = () => console.log("B"); | |
let alt = alternator(sayA, sayB); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment