object-fill-missing-keys
Version:
Add missing keys into plain objects, according to a reference object
12 lines (10 loc) • 2.75 kB
JavaScript
/**
* @name object-fill-missing-keys
* @fileoverview Add missing keys into plain objects, according to a reference object
* @version 11.1.0
* @author Roy Revelt
* @license MIT
* {@link https://codsen.com/os/object-fill-missing-keys/}
*/
import y from"rfdc";import{mergeAdvanced as g}from"object-merge-advanced";import{arrayiffy as b}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.1.0";var p=y(),F=h,O={placeholder:!1,doNotFillThesePathsIfTheyContainPlaceholders:[],useNullAsExplicitFalse:!0};function a(n){return o(n)?"plain object":Array.isArray(n)?"array":typeof n}function f(n,i,s,l=""){let e=p(n);if(d(e)||!(l.length&&s.doNotFillThesePathsIfTheyContainPlaceholders.includes(l)&&u(e,s.placeholder)))if(o(i)&&o(e))Object.keys(i).forEach(t=>{let r=`${l?`${l}.`:""}${t}`;s.doNotFillThesePathsIfTheyContainPlaceholders.includes(r)&&(d(e[t])?u(e[t],s.placeholder)&&(e[t]=s.placeholder):e[t]=s.placeholder),(!d(e[t])||!(s.doNotFillThesePathsIfTheyContainPlaceholders.includes(r)&&u(e[t],s.placeholder)))&&(e[t]=f(e[t],i[t],s,r))});else if(Array.isArray(i)&&Array.isArray(e)){if(e.length===0)return i;if(i.length)for(let t=e.length;t--;){let r=`${l?`${l}.`:""}0`;(o(i[0])||Array.isArray(i[0]))&&(e[t]=f(e[t],i[0],s,r))}}else return g(i,e,{useNullAsExplicitFalse:s.useNullAsExplicitFalse,cb:(t,r,c)=>a(t)===a(r)?r:c});return e}function C(n,i,s){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(i))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(i)}" and it's equal to: ${JSON.stringify(i,null,4)}`);if(s&&!o(s))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(s)}" and it's equal to: ${JSON.stringify(s,null,4)}`);let l={...O,...s};l.doNotFillThesePathsIfTheyContainPlaceholders=b(l.doNotFillThesePathsIfTheyContainPlaceholders);let e=null,t=null;if(l.doNotFillThesePathsIfTheyContainPlaceholders.length&&!l.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 f(p(n),p(i),l)}export{O as defaults,C as fillMissing,F as version};