Skip to content

Instantly share code, notes, and snippets.

@mohandere
Created May 4, 2019 11:25
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 mohandere/a679e5bea104dcedb7399830c3e5147d to your computer and use it in GitHub Desktop.
Save mohandere/a679e5bea104dcedb7399830c3e5147d to your computer and use it in GitHub Desktop.
Higher-Order Components
// Example #1
const twice = (f, v) => f(f(v))
const add3 = v => v + 3
twice(add3, 7) // 13
// Example #2
const filter = (predicate, xs) => xs.filter(predicate)
const is = type => x => Object(x) instanceof type
filter(is(Number), [0, '1', 2, null]) // [0, 2]
// Example #3
const withCounter = fn => {
let counter = 0
return (...args) => {
console.log(`Counter is ${++counter}`)
return fn(...args)
}
}
const add = (x, y) => x + y
const countedSum = withCounter(add)
console.log(countedSum(2, 3))
console.log(countedSum(2, 1))
// Output -
// Counter is 1
// 5
// Counter is 2
// 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment