diff --git a/deep-map/index.d.ts b/deep-map/index.d.ts index 469b522a..6214339c 100644 --- a/deep-map/index.d.ts +++ b/deep-map/index.d.ts @@ -1,7 +1,7 @@ import type { WritableAtom } from '../atom/index.js' import type { AllPaths, BaseDeepMap, FromPath } from './path.js' -export { AllPaths, BaseDeepMap, FromPath, getPath, setPath } from './path.js' +export { AllPaths, BaseDeepMap, FromPath, getPath, setByKey, setPath } from './path.js' export type DeepMapStore = { /** diff --git a/deep-map/index.js b/deep-map/index.js index 44d1081a..024e3958 100644 --- a/deep-map/index.js +++ b/deep-map/index.js @@ -1,7 +1,7 @@ import { atom } from '../atom/index.js' import { getPath, setPath } from './path.js' -export { getPath, setPath } from './path.js' +export { getPath, setByKey, setPath } from './path.js' export function deepMap(initial = {}) { let $deepMap = atom(initial) diff --git a/deep-map/path.d.ts b/deep-map/path.d.ts index 99464f5a..57042954 100644 --- a/deep-map/path.d.ts +++ b/deep-map/path.d.ts @@ -122,3 +122,25 @@ export function setPath>( path: K, value: FromPath ): T + +/** + * Set a deep value by path. Initialized arrays with `undefined` + * if you set arbitrary length. + * + * ``` + * import { setByKey } from 'nanostores' + * + * setByKey({ a: { b: { c: [] } } }, ['a', 'b', 'c', 1], 'hey') + * // Returns `{ a: { b: { c: [undefined, 'hey'] } } }` + * ``` + * + * @param obj Any object. + * @param splittedKeys An array of keys representing the path to the value. + * @param value New value. + * @retunts The new object. + */ +export function setByKey( + obj: T, + splittedKeys: PropertyKey[], + value: unknown +): T; diff --git a/deep-map/path.js b/deep-map/path.js index c5d5c320..179d7180 100644 --- a/deep-map/path.js +++ b/deep-map/path.js @@ -14,7 +14,7 @@ export function setPath(obj, path, value) { return setByKey(obj != null ? obj : {}, getAllKeysFromPath(path), value) } -function setByKey(obj, splittedKeys, value) { +export function setByKey(obj, splittedKeys, value) { let key = splittedKeys[0] ensureKey(obj, key, splittedKeys[1]) let copy = Array.isArray(obj) ? [...obj] : { ...obj } diff --git a/index.d.ts b/index.d.ts index 3c9e16eb..23674387 100644 --- a/index.d.ts +++ b/index.d.ts @@ -8,6 +8,7 @@ export { DeepMapStore, FromPath, getPath, + setByKey, setPath } from './deep-map/index.js' export { keepMount } from './keep-mount/index.js' diff --git a/index.js b/index.js index b08a0e7c..ae436664 100644 --- a/index.js +++ b/index.js @@ -1,7 +1,7 @@ export { atom } from './atom/index.js' export { clean, cleanStores } from './clean-stores/index.js' export { batched, computed } from './computed/index.js' -export { deepMap, getPath, setPath } from './deep-map/index.js' +export { deepMap, getPath, setByKey, setPath } from './deep-map/index.js' export { keepMount } from './keep-mount/index.js' export { onMount,