@crpt/react-utils
Version:
A useful kit for daily using
66 lines (44 loc) • 2.27 kB
JavaScript
import { get, has, isEmpty, isObjectLike, isPlainObject, reduce } from 'lodash';
import { getKeyFromPath } from '../objectUtils';
import { accumulateWith } from './accumulatorUtils';
import getPropWith from './getPropWith';
import mergeProps from './mergeProps';
/**
* @param {Object} target
* @param {Function|Object} accessorOrOptions
* @param {*} ...args
*/
var pickPropsWith = function pickPropsWith(target, accessorOrOptions) {
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
var currArgs = isEmpty(args) ? [target] : args;
var ownProps = currArgs[0],
extraProps = currArgs.slice(1);
var accessor = has(accessorOrOptions, 'accessor') ? get(accessorOrOptions, 'accessor') : accessorOrOptions;
var accumulator = has(accessorOrOptions, 'accumulator') ? get(accessorOrOptions, 'accumulator') : mergeProps;
var props = void 0;
if (isObjectLike(accessor)) {
props = reduce(accessor, function (prevProps, currAccessor, keyOrIdx) {
var _ref;
var idx = typeof keyOrIdx === 'number' && keyOrIdx.toString();
var key = typeof keyOrIdx === 'string' && keyOrIdx;
var passProps = accumulateWith([ownProps, prevProps], accumulator);
var passOptions = {
accessor: currAccessor,
accumulator: accumulator
};
var computedProps = [isObjectLike(currAccessor) && pickPropsWith.apply(undefined, [target, passOptions, passProps].concat(extraProps)), currAccessor === true && getPropWith.apply(undefined, [target, key, passProps].concat(extraProps)), getPropWith.apply(undefined, [target, currAccessor, passProps].concat(extraProps))].find(Boolean);
var currProps = [idx && isPlainObject(computedProps) && computedProps, key && (_ref = {}, _ref[key] = computedProps, _ref)].find(Boolean);
return accumulateWith([prevProps, currProps], accumulator);
}, {});
}
if (typeof accessor === 'string') {
var _props;
var propName = getKeyFromPath(accessor);
var computedProps = getPropWith.apply(undefined, [target, accessor].concat(currArgs));
props = (_props = {}, _props[propName] = computedProps, _props);
}
return props;
};
export default pickPropsWith;