UNPKG

@bemedev/decompose

Version:
1 lines 2.88 kB
{"version":3,"file":"assign.cjs","names":["splitKey","nextDefault","isArrayIndex","parseIndex"],"sources":["../../src/contexts/assign.ts"],"sourcesContent":["import {\n isArrayIndex,\n nextDefault,\n parseIndex,\n splitKey,\n} from '../helpers';\nimport type { Decompose, Ru } from '../types.types';\nimport type { DEFAULT_OPTIONS } from './constants';\n\n// #region type AssignByBey_F\nexport type AssignByBey_F = <\n T extends Ru,\n D extends Decompose<T, typeof DEFAULT_OPTIONS>,\n K extends Extract<keyof D, string>,\n R extends D[K],\n>(\n obj: T,\n key: K,\n value: R,\n) => T;\n// #endregion\n\nexport interface AssignByKey {\n (obj: any, key: string, value: any): any;\n low: (obj: any, key: string, value: any) => any;\n typed: AssignByBey_F;\n}\n\nconst _assignByKey: AssignByKey['low'] = (obj, key, value) => {\n const segments = splitKey(key);\n\n const [first, ...rest] = segments;\n const out: any = obj ?? nextDefault(first);\n\n if (rest.length === 0) {\n if (isArrayIndex(first)) {\n let idx = parseIndex(first);\n if (idx > out.length) idx = out.length;\n out[idx] = value;\n } else {\n out[first] = value;\n }\n return out;\n }\n\n const nextKey = rest.join('.');\n const next = rest[0];\n const _nextDefault = nextDefault(next);\n\n if (isArrayIndex(first)) {\n let idx = parseIndex(first);\n if (idx > out.length) idx = out.length;\n out[idx] = _assignByKey(out[idx] ?? _nextDefault, nextKey, value);\n } else {\n out[first] = _assignByKey(out[first] ?? _nextDefault, nextKey, value);\n }\n\n return out;\n};\n\n/**\n * Assigns a value to a path in an object.\n * @param obj The object to assign the value to\n * @param path The key to assign the value to, can be a nested key (e.g. 'a.b.c')\n * @param value The value to assign to the key\n * @returns The modified object with the value assigned to the specified key\n *\n * @see {@linkcode Decompose} for more details on object decomposition.\n */\nexport const assignByKey: AssignByKey = (obj, path, value) => {\n return _assignByKey(obj, path, value);\n};\n\nassignByKey.low = assignByKey;\nassignByKey.typed = assignByKey;\n"],"mappings":";;;AA4BA,MAAM,gBAAoC,KAAK,KAAK,UAAU;CAG5D,MAAM,CAAC,OAAO,GAAG,QAFAA,gBAAAA,SAAS,IAAI;CAG9B,MAAM,MAAW,OAAOC,gBAAAA,YAAY,MAAM;AAE1C,KAAI,KAAK,WAAW,GAAG;AACrB,MAAIC,gBAAAA,aAAa,MAAM,EAAE;GACvB,IAAI,MAAMC,gBAAAA,WAAW,MAAM;AAC3B,OAAI,MAAM,IAAI,OAAQ,OAAM,IAAI;AAChC,OAAI,OAAO;QAEX,KAAI,SAAS;AAEf,SAAO;;CAGT,MAAM,UAAU,KAAK,KAAK,IAAI;CAC9B,MAAM,OAAO,KAAK;CAClB,MAAM,eAAeF,gBAAAA,YAAY,KAAK;AAEtC,KAAIC,gBAAAA,aAAa,MAAM,EAAE;EACvB,IAAI,MAAMC,gBAAAA,WAAW,MAAM;AAC3B,MAAI,MAAM,IAAI,OAAQ,OAAM,IAAI;AAChC,MAAI,OAAO,aAAa,IAAI,QAAQ,cAAc,SAAS,MAAM;OAEjE,KAAI,SAAS,aAAa,IAAI,UAAU,cAAc,SAAS,MAAM;AAGvE,QAAO;;;;;;;;;;;AAYT,MAAa,eAA4B,KAAK,MAAM,UAAU;AAC5D,QAAO,aAAa,KAAK,MAAM,MAAM;;AAGvC,YAAY,MAAM;AAClB,YAAY,QAAQ"}