UNPKG

object-fill-missing-keys

Version:

Add missing keys into plain objects, according to a reference object

12 lines (10 loc) 2.76 kB
/** * @name object-fill-missing-keys * @fileoverview Add missing keys into plain objects, according to a reference object * @version 11.0.22 * @author Roy Revelt, Codsen Ltd * @license MIT * {@link https://codsen.com/os/object-fill-missing-keys/} */ import y from"rfdc";import{mergeAdvanced as b}from"object-merge-advanced";import{arrayiffy as g}from"arrayiffy-if-string";import{allEq as u}from"object-all-values-equal-to";import{isStr as j,isPlainObject as o,existy as d}from"codsen-utils";var h="11.0.22";var f=y(),F=h,O={placeholder:!1,doNotFillThesePathsIfTheyContainPlaceholders:[],useNullAsExplicitFalse:!0};function a(n){return o(n)?"plain object":Array.isArray(n)?"array":typeof n}function p(n,s,l,i=""){let e=f(n);if(d(e)||!(i.length&&l.doNotFillThesePathsIfTheyContainPlaceholders.includes(i)&&u(e,l.placeholder)))if(o(s)&&o(e))Object.keys(s).forEach(t=>{let r=`${i?`${i}.`:""}${t}`;l.doNotFillThesePathsIfTheyContainPlaceholders.includes(r)&&(d(e[t])?u(e[t],l.placeholder)&&(e[t]=l.placeholder):e[t]=l.placeholder),(!d(e[t])||!(l.doNotFillThesePathsIfTheyContainPlaceholders.includes(r)&&u(e[t],l.placeholder)))&&(e[t]=p(e[t],s[t],l,r))});else if(Array.isArray(s)&&Array.isArray(e)){if(e.length===0)return s;if(s.length)for(let t=e.length;t--;){let r=`${i?`${i}.`:""}0`;(o(s[0])||Array.isArray(s[0]))&&(e[t]=p(e[t],s[0],l,r))}}else return b(s,e,{useNullAsExplicitFalse:l.useNullAsExplicitFalse,cb:(t,r,c)=>a(t)===a(r)?r:c});return e}function D(n,s,l){if(arguments.length===0)throw new Error("object-fill-missing-keys: [THROW_ID_01] All arguments are missing!");if(!o(n))throw new Error(`object-fill-missing-keys: [THROW_ID_02] First argument, input object must be a plain object. Currently it's type is "${a(n)}" and it's equal to: ${JSON.stringify(n,null,4)}`);if(!o(s))throw new Error(`object-fill-missing-keys: [THROW_ID_03] Second argument, schema object, must be a plain object. Currently it's type is "${a(s)}" and it's equal to: ${JSON.stringify(s,null,4)}`);if(l&&!o(l))throw new Error(`object-fill-missing-keys: [THROW_ID_04] Third argument, schema object, must be a plain object. Currently it's type is "${a(l)}" and it's equal to: ${JSON.stringify(l,null,4)}`);let i={...O,...l};i.doNotFillThesePathsIfTheyContainPlaceholders=g(i.doNotFillThesePathsIfTheyContainPlaceholders);let e=null,t=null;if(i.doNotFillThesePathsIfTheyContainPlaceholders.length&&!i.doNotFillThesePathsIfTheyContainPlaceholders.every((r,c)=>j(r)?!0:(e=r,t=c,!1)))throw new Error(`object-fill-missing-keys: [THROW_ID_06] resolvedOpts.doNotFillThesePathsIfTheyContainPlaceholders element with an index number "${t}" is not a string! It's ${a(e)}, equal to: ${JSON.stringify(e,null,4)}`);return p(f(n),f(s),i)}export{O as defaults,D as fillMissing,F as version};