All files / src/utils createStructSerDes.ts

100% Statements 18/18
100% Branches 8/8
100% Functions 10/10
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 4619x                 19x 16x   19x                 4x 4x 4x 8x 4x 4x   8x 8x 8x   8x       8x         8x 8x      
import { define } from "../define";
import {
  AsyncStructDefinition,
  Struct,
  StructDefinition,
  AsyncSerDes,
  SerDes
} from "../types";
 
const nameOf = (key: string) =>
  /*@__PURE__*/ isNaN(+key) ? /*@__PURE__*/ JSON.stringify(key) : key;
 
export function createStructSerDes<
  T extends Struct,
  Async extends boolean
>(
  definition: Async extends true
    ? AsyncStructDefinition<T>
    : StructDefinition<T>,
  async: Async
): Async extends true ? AsyncSerDes<T> : SerDes<T> {
  const as = async ? "async " : "";
  const aw = async ? "await " : "";
  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(${as}(c,d)=>{${indexes
      .map((i) => `${aw}s${i}(c,d[${nameOf(keys[i])}])`)
      .join(";")}},${as}(c)=>{const d=${
      definition instanceof Array ? "[]" : "{}"
    };${indexes
      .map((i) => `d[${nameOf(keys[i])}]=${aw}d${i}(c)`)
      .join(";")};return d})`
  )(
    define,
    keys,
    /*@__PURE__*/ values.map(({ ser }) => ser),
    /*@__PURE__*/ values.map(({ des }) => des)
  );
}