UNPKG

@wordpress/global-styles-ui

Version:
1 lines • 1.86 kB
{"version":3,"file":"set-immutably.mjs","names":[],"sources":["../../../src/font-library/utils/set-immutably.ts"],"sourcesContent":["/**\n * Immutably sets a value inside an object. Like `lodash#set`, but returning a\n * new object. Treats nullish initial values as empty objects. Clones any\n * nested objects. Supports arrays, too.\n * Duplicated from `packages/global-styles-engine/src/utils/object.ts`\n *\n * @param object Object to set a value in.\n * @param path Path in the object to modify.\n * @param value New value to set.\n * @return Cloned object with the new value set.\n */\nexport function setImmutably(\n\tobject: Object,\n\tpath: string | number | ( string | number )[],\n\tvalue: any\n) {\n\t// Normalize path\n\tpath = Array.isArray( path ) ? [ ...path ] : [ path ];\n\n\t// Shallowly clone the base of the object\n\tobject = Array.isArray( object ) ? [ ...object ] : { ...object };\n\n\tconst leaf = path.pop();\n\n\t// Traverse object from root to leaf, shallowly cloning at each level\n\tlet prev = object;\n\tfor ( const key of path ) {\n\t\t// @ts-expect-error `prev` is typed as `Object`, which has no index signature.\n\t\tconst lvl = prev[ key ];\n\t\t// @ts-expect-error `prev` is typed as `Object`, which has no index signature.\n\t\tprev = prev[ key ] = Array.isArray( lvl ) ? [ ...lvl ] : { ...lvl };\n\t}\n\t// @ts-expect-error `leaf` is possibly `undefined`, which cannot be an index type.\n\tprev[ leaf ] = value;\n\n\treturn object;\n}\n"],"mappings":";;;;;;;;;;;;AAWA,SAAgB,aACf,QACA,MACA,OACC;CAED,OAAO,MAAM,QAAS,IAAK,IAAI,CAAE,GAAG,IAAK,IAAI,CAAE,IAAK;CAGpD,SAAS,MAAM,QAAS,MAAO,IAAI,CAAE,GAAG,MAAO,IAAI,EAAE,GAAG,OAAO;CAE/D,MAAM,OAAO,KAAK,IAAI;CAGtB,IAAI,OAAO;CACX,KAAM,MAAM,OAAO,MAAO;EAEzB,MAAM,MAAM,KAAM;EAElB,OAAO,KAAM,OAAQ,MAAM,QAAS,GAAI,IAAI,CAAE,GAAG,GAAI,IAAI,EAAE,GAAG,IAAI;CACnE;CAEA,KAAM,QAAS;CAEf,OAAO;AACR"}