schemind
Version:
Read and write to messages serialized as arrays (indexed keys) by defining a schema, enabling smaller message size when using protocols such as msgpack or JSON.
2 lines (1 loc) • 1.5 kB
JavaScript
var Schemind=(function(d){"use strict";function h(e,t){const o=t[a];let s=e;for(let c=t[a].length-1;c>=1;c--)s=s[o[c]];const i=o[0];return s[i]}function u(e,t,o){const s=t[a];let i=e;for(let n=t[a].length-1;n>=1;n--)i[s[n]]===void 0&&(i[s[n]]=[]),i=i[s[n]];const c=s[0];i[c]=o}const a=Symbol("indexesPathReversed"),m=Symbol("fieldType"),S=Symbol("isSchemaLeaf");class f extends Error{constructor(){super("Invalid schema. Make sure there are no duplicate indexes, and that nested objects are also wrapped with withIndex."),this.name="InvalidSchemaError"}}function y(e){return v(e,e,[],0),e}function v(e,t,o,s){for(const[i,c]of Object.entries(t)){const n=c;l(n)?(O(n,o,s),n.get=r=>h(r,n),n.set=(r,P)=>u(r,n,P)):v(e,n,o,s+1)}}function O(e,t,o){if(t.some(c=>c.length===e[a].length&&c.every((n,r)=>n===e[a][r])))throw new f;if(t.push(e[a]),e[a].length!==o+1)throw new f}function j(e){return t=>t?(b(t,e),t):{[a]:[e],[m]:void 0,[S]:!0}}function l(e){return Object.hasOwn(e,S)}function b(e,t){for(const[o,s]of Object.entries(e)){const i=s;l(i)?i[a].push(t):b(i,t)}}function I(e,t){const o={};for(const[s,i]of Object.entries(t)){const c=i;let n;l(c)?n=h(e,c):n=I(e,c),o[s]=n}return o}function w(e,t){const o=[];return g(o,e,t),o}function g(e,t,o){for(const[s,i]of Object.entries(o)){const c=i,n=t[s];l(c)?u(e,c,n):g(e,n,c)}}return d.InvalidSchemaError=f,d.buildSchema=y,d.get=h,d.set=u,d.toIndexedKeysMessage=w,d.toPlainObject=I,d.withIndex=j,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"}),d})({});