@sagold/json-pointer
Version:
json pointer - failsafe data retrieval from js and json objects
1 lines • 2.36 kB
JavaScript
function e(e){return e===`#`||e===``||Array.isArray(e)&&e.length===0||!1}const t=/~1/g,n=/~0/g,r=/(^#?\/?)/g;function i(e){return e.replace(t,`/`).replace(n,`~`)}function a(e){return i(decodeURIComponent(e))}function o(t){if(t==null||typeof t!=`string`||e(t))return Array.isArray(t)?t.slice():[];let n=t.indexOf(`#`)>=0?a:i;t=t.replace(r,``);let o=t.split(`/`);for(let e=0,t=o.length;e<t;e+=1)o[e]=n(o[e]);return o}function s(t,n,r=void 0){if(n==null||t==null)return r;if(e(n))return t;let i=c(t,o(n));return i===void 0?r:i}function c(e,t){let n=t.shift();if(e!==void 0)return n===void 0?e:e==null?void 0:c(e[n],t)}const l=/^\[.*\]$/,u=/^[[{](.+)[\]}]$/;function d(e,t){return e===`__proto__`||e==`constructor`&&t.length>0&&t[0]==`prototype`}function f(e,t,n){if(t==null)return e;let r=o(t);if(r.length===0)return e;e??=l.test(r[0])?[]:{};let i,a,s=e;for(;r.length>1;)i=r.shift(),a=l.test(r[0])||`${parseInt(r[0])}`===r[0],!d(i,r)&&(s=m(s,i,a));return i=r.pop(),p(s,i,n),e}function p(e,t,n){let r=t.match(u)?.pop()??t;t===`[]`&&Array.isArray(e)?e.push(n):d(r,e)||(e[r]=n)}function m(e,t,n){let r=t.match(u)?.pop()??t;if(e[r]!=null)return e[r];let i=n?[]:{};return p(e,t,i),i}function h(e){let t=0,n=0;for(;t+n<e.length;)e[t+n]===void 0&&(n+=1),e[t]=e[t+n],t+=1;return e.length-=n,e}function g(e,t,n){let r=o(t),i=r.pop(),a=s(e,r);return a&&delete a[i],Array.isArray(a)&&n!==!0&&h(a),e}const _=/~/g,v=/\//g;function y(e,t){if(e.length===0)return t?`#`:``;for(let n=0,r=e.length;n<r;n+=1)e[n]=e[n].replace(_,`~0`).replace(v,`~1`),t&&(e[n]=encodeURIComponent(e[n]));return(t?`#/`:`/`)+e.join(`/`)}function b(e,...t){let n=[];if(Array.isArray(e))return y(e,arguments[1]===!0);let r=arguments[arguments.length-1],i=typeof r==`boolean`?r:e&&e[0]===`#`;for(let e=0,t=arguments.length;e<t;e+=1)n.push.apply(n,o(arguments[e]));let a=[];for(let e=0,t=n.length;e<t;e+=1)if(n[e]===`..`){if(a.length===0)return i?`#`:``;a.pop()}else a.push(n[e]);return y(a,i)}function x(e){let t=o(e);if(t.length===0)return typeof e==`string`&&e[0]===`#`?[`#`,t[0]]:[``,void 0];if(t.length===1)return e[0]===`#`?[`#`,t[0]]:[``,t[0]];let n=t.pop();return[b(t,e[0]===`#`),n]}var S={get:s,set:f,remove:g,join:b,split:o,splitLast:x,isRoot:e,removeUndefinedItems:h};export{S as default,s as get,e as isRoot,b as join,g as remove,h as removeUndefinedItems,f as set,o as split,x as splitLast};