flatted
Version:
A super light and fast circular JSON parser.
2 lines (1 loc) • 1.37 kB
JavaScript
self.Flatted=function(t){"use strict";const{parse:e,stringify:r}=JSON,{keys:n}=Object,o=String,s="string",l={},c="object",f=(t,e)=>e,i=t=>{if(typeof t===c&&t)for(let e=n(t),{length:r}=e,l=0;l<r;l++){const r=e[l];typeof t[r]===s&&(t[r]=new o(t[r]))}return t},a=(t,e,r)=>{const n=o(e.push(r)-1);return t.set(r,n),n},u=(t,r)=>{const s=e(t).map(i),a=r||f;let u=s[0];if(typeof u===c&&u){const t=[],e=((t,e,r,s)=>f=>{for(let i=n(f),{length:a}=i,u=0;u<a;u++){const n=i[u],a=f[n];if(a instanceof o){const o=t[+a];typeof o===c&&o&&!r.has(o)?(r.add(o),f[n]=l,e.push({o:f,k:n,r:o})):f[n]=s.call(f,n,o)}else f[n]!==l&&(f[n]=s.call(f,n,a))}return f})(s,t,new Set,a);u=e(u);let r=0;for(;r<t.length;)e(t[r++].r);for(;r--;){const{o:e,k:n,r:o}=t[r];e[n]=a.call(e,n,o)}}return a.call({"":u},"",u)},p=(t,e,n)=>{const l=Array.isArray(e)?[]:null;if(l)for(let t=0;t<e.length;t++){const r=e[t];typeof r!==s&&"number"!=typeof r||l.push(o(r))}const i={"":t},u=l?function(t,e){return this===i||Array.isArray(this)||-1<l.indexOf(t)?e:void 0}:e||f,p=new Map,y=[],h=[];let g=+a(p,y,u.call(i,"",t)),d=!g;for(;g<y.length;)d=!0,h[g]=r(y[g++],O,n);return"["+h.join(",")+"]";function O(t,e){if(d)return d=!d,e;const r=u.call(this,t,e);switch(typeof r){case c:if(null===r)return r;case s:return p.get(r)||a(p,y,r)}return r}};return t.fromJSON=t=>u(r(t)),t.parse=u,t.stringify=p,t.toJSON=t=>e(p(t)),t}({});