map-transform
Version:
Map and transform objects with mapping definitions
47 lines • 1.75 kB
JavaScript
import mapAny from 'map-any';
import { pathGetter } from '../operations/getSet.js';
import { isObject, isString, isNonEmptyArray } from '../utils/is.js';
import { ensureArray } from '../utils/array.js';
const projectProps = (rawProps, doInclude) => {
const props = rawProps.filter(isString);
const filterFn = doInclude
? ([key]) => props.includes(key)
: ([key]) => !props.includes(key);
return (obj) => Object.fromEntries(Object.entries(obj).filter(filterFn));
};
const projectPropsFromPath = (path, rawProps, doInclude) => {
const getFn = pathGetter(path);
return (obj, state) => {
let props = getFn(obj, state);
if (props === undefined) {
props = rawProps;
}
if (!props) {
return obj;
}
return projectProps(ensureArray(props), doInclude)(obj);
};
};
function prepareProjectFn(include, includePath, exclude, excludePath) {
if (typeof includePath === 'string') {
return projectPropsFromPath(includePath, include, true);
}
else if (typeof excludePath === 'string') {
return projectPropsFromPath(excludePath, exclude, false);
}
else if (isNonEmptyArray(include)) {
return projectProps(include, true);
}
else if (isNonEmptyArray(exclude)) {
return projectProps(exclude, false);
}
else {
return (obj) => obj;
}
}
const transformer = function bucket({ include, includePath, exclude, excludePath, }) {
const projectFn = prepareProjectFn(include, includePath, exclude, excludePath);
return () => (data, state) => mapAny((data) => (isObject(data) ? projectFn(data, state) : undefined), data);
};
export default transformer;
//# sourceMappingURL=project.js.map