UNPKG

@rimbu/deep

Version:

Tools to use handle plain JS objects as immutable objects

36 lines 1.3 kB
import { Deep } from './internal.mjs'; /** * 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 } * ``` */ export 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 Deep.getAt(source, selector); } else if (Array.isArray(selector)) { // selector is tuple, get each tuple item value return selector.map((s) => select(source, s)); } // selector is object const result = {}; for (const key in selector) { // set each selected object key to the selector value result[key] = select(source, selector[key]); } return result; } //# sourceMappingURL=selector.mjs.map