js-pathfinder
Version:
Path utility for objects
3 lines (2 loc) • 1.85 kB
JavaScript
var p=e=>/^[/.]/.test(e)?e.slice(1):e,O=e=>p(e).split(/[/.]/),v=e=>Object.getPrototypeOf(e||0).constructor===Object,d=(e,r)=>e&&Array.isArray(r)&&!!r.find(t=>t.constructor&&t.constructor===Object),b="no value (undefined)",P="None. Object instance not suitable",c=(e="n/a",r=(!1)[y],t=b)=>({searchPath:e,exists:r[y],value:t}),h=e=>!Array.isArray(e)&&Object.keys(e).length,{pathTo:F,fromPath:V,yn:y}=S();function S(){return Symbol.to=Symbol.for("pathTo"),Symbol.from=Symbol.for("pathFrom"),Symbol.yn=Symbol.for("yn"),Object.defineProperties(Boolean.prototype,{[Symbol.yn]:{value:t,enumerable:!1}}),Object.defineProperties(Object.prototype,{[Symbol.to]:{value:function(s){return e(this,s)},enumerable:!1},[Symbol.from]:{value:function(s){return r(this,s)},enumerable:!1}}),{pathTo:Symbol.to,fromPath:Symbol.from,yn:Symbol.yn};function e(s,n){return h(s)&&w(s,n)||{searchKey:n,pathFound:P,value:"n/a"}}function r(s,n){return h(s)&&i(s,n)||c(n,!1,"n/a")}function t(){return this.valueOf()?"YES":"NO"}}function i(e,r,t=!1,s=!1){let n=O(r),u=l=>{let o=n.shift();if(d(t,l[o])){let a=l[o].find(f=>i(f,n.join("/"),1).exists);return a?s?c(r,!0,a):i(a,n.join("/"),1):c(r,!1)}return Object.hasOwn(l,o)&&n.length?u(l[o]):{...c(r,o in l,l[o]),setValue:a=>l[o]=a}};return d(t,e)&&(e={root:e}),u(e)}function w(e,r){let t={searchKey:r,pathFound:(!1)[y]};function s(n,u,l=""){for(let o of Object.keys(n))if(o!==u&&v(n[o])&&s(n[o],u,`${l}.${o}`),o===u){t.pathFound=`${l}.${u}`.replace(/^\./,""),t.value=n[o]===void 0&&b||n[o],t.cloneWithNewValue=a=>{let f=window.structuredClone?window.structuredClone(e):JSON.parse(JSON.stringify(e)),m=i(f,t.pathFound);return Object.hasOwn(m,"setValue")&&m.setValue(a),f};break}return Object.hasOwn(t,"value")||(t.value=`No path for key '${u}'`),t}return s(e,r)}export{V as fromPath,F as pathTo};
//# sourceMappingURL=Pathfinder.min.js.map