UNPKG

js-upsert

Version:

`js-upsert` is a lightweight JavaScript library designed to simplify updating deeply nested properties within objects. It provides an intuitive and efficient way to manage complex object structures, ensuring non-destructive updates. This makes `js-upsert`

3 lines (2 loc) 2.6 kB
(function(y,p){typeof exports=="object"&&typeof module<"u"?p(exports):typeof define=="function"&&define.amd?define(["exports"],p):(y=typeof globalThis<"u"?globalThis:y||self,p(y["js-upsert"]={}))})(this,function(y){"use strict";function p(e){return e.replace(/[\[\]'"]/g,"").split(".")}const c=(e,t)=>{let r=Math.floor(Math.random()*1e6),o=typeof t=="string"?p(t):t;return{["$$@@@@__upsert_hook_"+r]:{value:e,index:o??null,isFunction:typeof e=="function"}}};c.at=(...e)=>{const t=e,r=t.pop();return c(r,t)};function h(e,t,r,o=!1,n,l=[]){const f=t;if(t.length<=1){if(t.length>0)try{return e[t[0]]=o?r(e[t[0]??t]):r,e}catch(s){throw console.error(s),`Setting Failed at index ${t[0]} of [${l.join(" => ")}] due to the type ${typeof e}, Only array or object is assignable`}if(e===null||typeof e!="object")throw Error("Initial value is not a object, ERROR: INITITAL_VALUE_PARSE_FAILED");let u=o?r(e):r;if(n.returnType=="array")return e.push(u),e;if(typeof u!="object")throw`Object or array can be setted only as a default value. Type of value is ${typeof u}.`;for(const s of Object.keys(u))e[s]=u[s];return e}let i=(e??[])[t[0]]??!1;if(!i){let u=a(t,r,o);try{e[t[0]]=u}catch{throw`Setting Failed at index ${t[0]} of [${l.join(" => ")}] due to the type ${typeof e}, Only array or object is assignable`}return e}return t.shift(),h(i,t,r,o,n,[...l,f[0]])}function a(e,t,r=!1){let o=[...e],n;return o.length==1?n=r?t(null):t:(n={},o.shift(),n[o[0]]=a(o,t,r)),n}function b({obj:e},t,r=[],o=!1){let n=[];for(let l in e){let f=e[l];if(l.includes(t)&&(f??!1))n.push({index:[...r,...f.index??[]],value:f.value,isFunction:f.isFunction});else if(typeof f=="object"){const i=b({obj:f},t,[...r,l],!0);n=n.concat(i.obj)}}return o?{obj:n}:{result:n}}function _(e,t,r={returnType:"object"}){let{result:o}=b({obj:t},"$$@@@@__upsert_hook");for(let n=0;n<o.length;n++){let l=o[n];h(e,l.index,l.value,l.isFunction,r)}}function g(e,...t){let r={returnType:"object"};const o=Array.isArray(e);o&&(r.returnType="array");for(let n of t)_(e,n,r);try{return new Proxy(e,{get(n,l,f){return n=o?[...e]:{...e},l==="get"?()=>f:l==="at"?(...i)=>{if(i.length<=1)throw"keys.length is less than 2, need atleast 2 values to differentiate index and value";const u=i[i.length-1],s=i;return s.pop(),h(e,s,u,typeof u=="function",r),f}:Reflect.get(n,l,f)}})}catch{throw Error(`Cannot return value as returnType '${r.returnType}'. Please try '${r.returnType=="array"?"OBJECT":"ARRAY"}' returnType, ERROR: RETURN_ERROR.`)}}y.set=c,y.upsert=g,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})}); //# sourceMappingURL=js-upsert.umd.cjs.map