Skip to content

Instantly share code, notes, and snippets.

@gregberge
Created November 8, 2016 11:14
Show Gist options
  • Select an option

  • Save gregberge/16400b6207c3948e05e7075ab6a31574 to your computer and use it in GitHub Desktop.

Select an option

Save gregberge/16400b6207c3948e05e7075ab6a31574 to your computer and use it in GitHub Desktop.
import { Component } from 'react'
import createEagerFactory from './createEagerFactory'
import createHelper from './createHelper'
const mapValues = (obj, func) => {
const result = []
let i = 0
/* eslint-disable no-restricted-syntax */
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
i += 1
result[key] = func(obj[key], key, i)
}
}
/* eslint-enable no-restricted-syntax */
return result
}
const withHandlers = handlers => BaseComponent => {
const factory = createEagerFactory(BaseComponent)
let cachedHandlers
let handlers
return props => {
cachedHandlers = {}
handlers = handlers || mapValues(
handlers,
(createHandler, handlerName) => (...args) => {
const cachedHandler = cachedHandlers[handlerName]
if (cachedHandler) {
return cachedHandler(...args)
}
const handler = createHandler(props)
cachedHandlers[handlerName] = handler
if (
process.env.NODE_ENV !== 'production' &&
typeof handler !== 'function'
) {
console.error(
'withHandlers(): Expected a map of higher-order functions. ' +
'Refer to the docs for more info.'
)
}
return handler(...args)
}
)
return factory({
...props,
...handlers
})
}
}
export default createHelper(withHandlers, 'withHandlers')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment