All files / src/serdes struct.ts

100% Statements 20/20
100% Branches 4/4
100% Functions 11/11
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 3214x   14x 18x   14x 3x 9x 3x 3x   9x 9x 9x   9x       9x         9x 9x       14x 1x  
import { define, StructFactory, TupleFactory } from "..";
 
const nameOf = (key: string) =>
  /*@__PURE__*/ isNaN(+key) ? /*@__PURE__*/ JSON.stringify(key) : key;
 
export const struct: StructFactory = (definition) => {
  const keys = /*@__PURE__*/ Object.keys(definition);
  const indexes = /*@__PURE__*/ Object.keys(keys).map((i) => +i);
  const values = /*@__PURE__*/ Object.values(definition);
  return /*@__PURE__*/ new Function(
    "d",
    `[${indexes.map((i) => "k" + i).join()}]`,
    `[${indexes.map((i) => "s" + i).join()}]`,
    `[${indexes.map((i) => "d" + i).join()}]`,
    `return d((c,d)=>{${indexes
      .map((i) => `s${i}(c,d[${nameOf(keys[i])}])`)
      .join(";")}},(c)=>{const d=${
      definition instanceof Array ? "[]" : "{}"
    };${indexes
      .map((i) => `d[${nameOf(keys[i])}]=d${i}(c)`)
      .join(";")};return d})`
  )(
    define,
    keys,
    /*@__PURE__*/ values.map(({ ser }) => ser),
    /*@__PURE__*/ values.map(({ des }) => des)
  );
};
 
export const tuple: TupleFactory = (...definition) =>
  struct(definition);