@rimbu/deep
Version:
Tools to use handle plain JS objects as immutable objects
40 lines • 1.46 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.select = void 0;
var internal_cjs_1 = require("./internal.cjs");
/**
* Returns the result of applying the given `selector` shape to the given `source` value.
* @typeparam T - the patch value type
* @typeparam SL - the selector shape type
* @param source - the source value to select from
* @param selector - a shape indicating the selection from the source values
* @example
* ```ts
* const item = { a: { b: 1, c: 'a' } };
* Deep.select(item, { q: 'a.c', y: ['a.b', 'a.c'], z: (v) => v.a.b + 1 });
* // => { q: 'a', y: [1, 'a'], z: 2 }
* ```
*/
function select(source, selector) {
if (typeof selector === 'function') {
// selector is function, resolve selector function
return selector(source);
}
else if (typeof selector === 'string') {
// selector is string path, get the value at the given path
return internal_cjs_1.Deep.getAt(source, selector);
}
else if (Array.isArray(selector)) {
// selector is tuple, get each tuple item value
return selector.map(function (s) { return select(source, s); });
}
// selector is object
var result = {};
for (var key in selector) {
// set each selected object key to the selector value
result[key] = select(source, selector[key]);
}
return result;
}
exports.select = select;
//# sourceMappingURL=selector.cjs.map
;