Created
October 28, 2020 19:57
-
-
Save matt-dunn/d074cad0e92f0571c02381cb96ae4f25 to your computer and use it in GitHub Desktop.
This file contains 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
/** ! | |
* Copyright (c) 2020, Matt Dunn | |
* | |
* @author Matt Dunn (https://matt-dunn.github.io/) | |
* @licence MIT | |
*/ | |
/** | |
* Optimised selector - similar to reselect | |
* | |
* @method createSelector | |
* @param {Function} [props] Function that returns props or null for no props | |
* @param {Function} [state] Function that returns state or null for no state | |
* @param {Function||Array.<Function>} selectors A function which returns immutable data (passing props, state) or another Selector (or an array of) | |
* @param {Function} computeData A function which computes state, passing the values in order of selectors | |
* @returns {Object} Final computed state | |
*/ | |
const createSelector = (props, state, selectors, computeData) => { | |
const computeSelectors = Array.isArray(selectors) ? selectors : [selectors]; | |
let prevData = [], | |
computedState; | |
return () => { | |
let hasChange = false; | |
computeSelectors.map((selector, index) => { | |
const currentData = selector(props && props(), state && state()); | |
if (currentData !== prevData[index]) { | |
hasChange = true; | |
prevData[index] = currentData; | |
} | |
}); | |
if (hasChange) { | |
computedState = computeData(...prevData); | |
} | |
return computedState; | |
}; | |
}; | |
export {createSelector}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment