Created
November 8, 2016 11:14
-
-
Save gregberge/16400b6207c3948e05e7075ab6a31574 to your computer and use it in GitHub Desktop.
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
| 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