UNPKG

@bjoerge/mutiny

Version:

Tiny toolkit for working with Sanity mutations in JavaScript & TypeScript

1 lines 2.34 kB
{"version":3,"file":"getAtPath.cjs","sources":["../../src/path/get/getAtPath.ts"],"sourcesContent":["import {type AnyArray} from '../../utils/typeUtils'\nimport {type KeyedPathElement, type Path, type PathElement} from '../types'\nimport {isArrayElement, isKeyedElement} from '../utils/predicates'\nimport {type FindInArray} from './types'\n\nexport type {AnyArray} from '../../utils/typeUtils'\n\nexport type Get<\n P extends number | KeyedPathElement | Readonly<KeyedPathElement> | string,\n T,\n> = T extends AnyArray\n ? P extends KeyedPathElement | Readonly<KeyedPathElement> | number\n ? FindInArray<P, T>\n : undefined\n : P extends keyof T\n ? T[P]\n : never\n\nexport type GetAtPath<P extends readonly PathElement[], T> = P extends []\n ? T\n : P extends [infer Head, ...infer Tail]\n ? Head extends PathElement\n ? Tail extends PathElement[]\n ? GetAtPath<Tail, Get<Head, T>>\n : undefined\n : undefined\n : undefined\n\nexport function getAtPath<const Head extends PathElement, const T>(\n path: [head: Head],\n value: T,\n): Get<Head, T>\nexport function getAtPath<\n const Head extends PathElement,\n const Tail extends PathElement[],\n T,\n>(path: [head: Head, ...tail: Tail], value: T): GetAtPath<[Head, ...Tail], T>\nexport function getAtPath<T>(path: [], value: T): T\nexport function getAtPath(path: Path, value: unknown): unknown\nexport function getAtPath(path: Path, value: unknown): unknown {\n if (path.length === 0) {\n return value\n }\n\n let current = value\n for (const head of path) {\n if (isArrayElement(head)) {\n if (!Array.isArray(current)) {\n return undefined\n }\n\n if (isKeyedElement(head)) {\n current = current.find(item => item._key === head._key)\n continue\n }\n current = current[head]\n continue\n }\n current = (current as any)[head]\n }\n return current\n}\n"],"names":["isArrayElement","isKeyedElement"],"mappings":";;AAuCgB,SAAA,UAAU,MAAY,OAAyB;AAC7D,MAAI,KAAK,WAAW;AACX,WAAA;AAGT,MAAI,UAAU;AACd,aAAW,QAAQ,MAAM;AACnB,QAAAA,UAAAA,eAAe,IAAI,GAAG;AACpB,UAAA,CAAC,MAAM,QAAQ,OAAO;AACxB;AAGE,UAAAC,UAAAA,eAAe,IAAI,GAAG;AACxB,kBAAU,QAAQ,KAAK,CAAA,SAAQ,KAAK,SAAS,KAAK,IAAI;AACtD;AAAA,MACF;AACA,gBAAU,QAAQ,IAAI;AACtB;AAAA,IACF;AACA,cAAW,QAAgB,IAAI;AAAA,EACjC;AACO,SAAA;AACT;;"}