UNPKG

@techmely/utils

Version:

Collection of helpful JavaScript / TypeScript utils

35 lines (30 loc) 805 B
'use strict'; /*! * @techmely/utils * Copyright(c) 2021-2024 Techmely <techmely.creation@gmail.com> * MIT Licensed */ // src/pick.ts function pick(state, paths) { if (Array.isArray(paths)) { return paths.reduce((acc, path) => { const _paths = path.split("."); return set(acc, _paths, get(state, _paths)); }, {}); } return get(state, paths.split(".")); } function get(state, paths) { return paths.reduce((acc, path) => acc?.[path], state); } var ProtoRE = /^(__proto__)$/; function set(state, paths, val) { const last = paths.at(-1); if (last === void 0) return state; const restPaths = paths.slice(0, -1); const result = restPaths.reduce((obj, p) => ProtoRE.test(p) ? {} : obj[p] ||= {}, state); result[last] = val; return state; } exports.pick = pick;