UNPKG

@cookbook/dot-notation

Version:

Object readings and complex transformations using dot notation syntax.

3 lines (2 loc) 2.51 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).dot={})}(this,(function(e){"use strict";const t=e=>t.regexpNaNIndex.exec(e)||t.regexpIntIndex.exec(e);t.regexpIntIndex=/\[(-*\d*)]/g,t.regexpNaNIndex=/\[([^\]]*)]/;const n=e=>{const[t,...r]=e.split(n.regexp).filter(Boolean);return[t,r.length?r.join("."):void 0]};n.regexp=/\.|(\[[^\]]*])|(\[-*\d*])/;const r=e=>({}.toString.call(e).match(/\s([A-Za-z]+)/)[1].toLowerCase()),o={nullish:e=>null==e,string:e=>"string"===r(e),number:e=>"number"===r(e),object:e=>"object"===r(e),array:e=>Array.isArray(e)},i=e=>{let t;return t=o.array(e)?[...e]:o.object(e)?Object.assign({},e):"date"===r(e)?new Date(e):e,t},a=(e,r)=>{if(o.nullish(r)||!r.toString().trim())throw new SyntaxError(`A dot notation path was expected, but instead got "${r}"`);const s=i(e);let[c,l]=n(r);const u=t(c.toString());if(u){const{1:e}=u;if(!e)throw new SyntaxError(`An array index was expected but nothing was found at "${r}"`);if(Number.isNaN(+e))throw new TypeError(`Array index must a positive integer "${e}"`);if(+e<0)throw new RangeError(`Array index must be equal or greater than 0, but instead got "${e}"`);c=+e}return!l||o.nullish(s[c])?s[c]:a(s[c],l)},s=(e,r)=>{const[o,a]=n(e),c=t(o),l=a?s(a,r):i(r);return c?[l]:{[o]:l}},c=(e,t)=>{if(!o.object(e)&&!o.object(t))return t;const n=i(e),r=i(t),a=Object.keys(n),s=i(t);for(let e=0;e<a.length;e+=1){const t=a[e],l=i(n[t]),u=i(r[t]);o.array(l)&&o.array(u)?s[t]=u:o.object(l)&&o.object(u)?s[t]=c(l,u):s[t]=u||l}return s},l=e=>e.split(n.regexp).filter(Boolean).map((e=>"[]"===e?"[0]":e)),u=(e,n,r)=>{const a=i(e);if(!o.array(a))return c(a,s(n.join("."),r));const{1:l,index:d}=t(n.join("."));if(+l>a.length)throw new RangeError(`Expected array index for path "${n.join(".")}" to be "${a.length}" but found instead "${l}"`);if(o.nullish(a[+l]))a.push(...s(n.splice(d).join("."),r));else{const e=n.length>1?u(a[+l],n.slice(1),r):r;o.object(e)?a[+l]=Object.assign({},e):o.array(e)?a[+l]=[...e]:a[+l]=e}return a};e.parse=e=>{const n=i(e),r=Object.keys(n);let d=t(l(r[0])[0])?[]:{};for(let e=0;e<r.length;e+=1){const f=r[e],g=t(f),p=i(n[f]);let x=s(f,p);if(g){const e=f.substring(0,g.index),t=l(f.replace(e,"")),n=e?a(d,e)||[]:d;x=u(n,t,p),e&&(x=s(e,x))}o.array(x)&&(d=x),d=c(d,x)}return d},e.parseKey=s,e.pick=a,Object.defineProperty(e,"__esModule",{value:!0})})); //# sourceMappingURL=dot.min.js.map