All files / json-random/src RandomJson.ts

86.95% Statements 80/92
81.81% Branches 36/44
88.23% Functions 15/17
90.41% Lines 66/73

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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 3351x                                               1x                               1x 9626x     1x                                                                                                                                                                                                   1x 1180x                   1x   4x 4x       9x         48x             48x 48x       1084x 1180x 9599x 1084x 1057x                   1x               1x                               6x           6x 6x 6x 6x 6x 6x 6x 6x 6x 6x               6x 1x 1x   5x               5x               108x 6x             108x 108x 108x 108x 108x 64x 64x   44x 44x               108x   5x   8x   47x   39x       5x   4x         40x 40x         108x 108x 103x 95x 48x 9x 9x 4x                               108x      
import {randomString, type Token} from './string';
 
type JsonValue = unknown;
 
/** @ignore */
export type NodeType = 'null' | 'boolean' | 'number' | 'string' | 'binary' | 'array' | 'object';
 
export interface NodeOdds {
  null: number;
  boolean: number;
  number: number;
  string: number;
  binary: number;
  array: number;
  object: number;
}
 
export interface RandomJsonOptions {
  rootNode: 'object' | 'array' | 'string' | undefined;
  nodeCount: number;
  odds: NodeOdds;
  strings?: Token;
}
 
const defaultOpts: RandomJsonOptions = {
  rootNode: 'object',
  nodeCount: 32,
  odds: {
    null: 1,
    boolean: 2,
    number: 10,
    string: 8,
    binary: 0,
    array: 2,
    object: 2,
  },
};
 
type ContainerNode = unknown[] | object;
 
const ascii = (): string => {
  return String.fromCharCode(Math.floor(32 + Math.random() * (126 - 32)));
};
 
const alphabet = [
  'a',
  'b',
  'c',
  'd',
  'e',
  'f',
  'g',
  'h',
  'i',
  'j',
  'k',
  'l',
  'm',
  'n',
  'o',
  'p',
  'q',
  'r',
  's',
  't',
  'u',
  'v',
  'w',
  'x',
  'y',
  'z',
  'A',
  'B',
  'C',
  'D',
  'E',
  'F',
  'G',
  'H',
  'I',
  'J',
  'K',
  'L',
  'M',
  'N',
  'O',
  'P',
  'Q',
  'R',
  'S',
  'T',
  'U',
  'V',
  'W',
  'X',
  'Y',
  'Z',
  '0',
  '1',
  '2',
  '3',
  '4',
  '5',
  '6',
  '7',
  '8',
  '9',
  '-',
  '_',
  '.',
  ',',
  ';',
  '!',
  '@',
  '#',
  '$',
  '%',
  '^',
  '&',
  '*',
  '\\',
  '/',
  '(',
  ')',
  '+',
  '=',
  '\n',
  '👍',
  '🏻',
  '😛',
  'ä',
  'ö',
  'ü',
  'ß',
  'а',
  'б',
  'в',
  'г',
  '诶',
  '必',
  '西',
];
const utf16 = (): string => {
  return alphabet[Math.floor(Math.random() * alphabet.length)];
};
 
/**
 * Create a random JSON value.
 *
 * ```ts
 * RandomJson.generate()
 * ```
 */
export class RandomJson {
  public static generate(opts?: Partial<RandomJsonOptions>): JsonValue {
    const rnd = new RandomJson(opts);
    return rnd.create();
  }
 
  public static genBoolean(): boolean {
    return Math.random() > 0.5;
  }
 
  public static genNumber(): number {
    const num =
      Math.random() > 0.2
        ? Math.random() * 1e9
        : Math.random() < 0.2
          ? Math.round(0xff * (2 * Math.random() - 1))
          : Math.random() < 0.2
            ? Math.round(0xffff * (2 * Math.random() - 1))
            : Math.round(Number.MAX_SAFE_INTEGER * (2 * Math.random() - 1));
    Iif (num === 0) return 0;
    return num;
  }
 
  public static genString(length = Math.ceil(Math.random() * 16)): string {
    let str: string = '';
    if (Math.random() < 0.1) for (let i = 0; i < length; i++) str += utf16();
    else for (let i = 0; i < length; i++) str += ascii();
    if (str.length !== length) return ascii().repeat(length);
    return str;
  }
 
  public static genBinary(length = Math.ceil(Math.random() * 16)): Uint8Array {
    const buf = new Uint8Array(length);
    for (let i = 0; i < length; i++) buf[i] = Math.floor(Math.random() * 256);
    return buf;
  }
 
  public static genArray(options: Partial<Omit<RandomJsonOptions, 'rootNode'>> = {odds: defaultOpts.odds}): unknown[] {
    return RandomJson.generate({
      nodeCount: 6,
      ...options,
      rootNode: 'array',
    }) as unknown[];
  }
 
  public static genObject(options: Partial<Omit<RandomJsonOptions, 'rootNode'>> = {odds: defaultOpts.odds}): object {
    return RandomJson.generate({
      nodeCount: 6,
      ...options,
      rootNode: 'object',
    }) as object;
  }
 
  /** @ignore */
  public opts: RandomJsonOptions;
  /** @ignore */
  private totalOdds: number;
  /** @ignore */
  private oddTotals: NodeOdds;
  /** @ignore */
  public root: JsonValue;
  /** @ignore */
  private containers: ContainerNode[] = [];
 
  /**
   * @ignore
   */
  public constructor(opts: Partial<RandomJsonOptions> = {}) {
    this.opts = {...defaultOpts, ...opts};
    this.oddTotals = {} as any;
    this.oddTotals.null = this.opts.odds.null;
    this.oddTotals.boolean = this.oddTotals.null + this.opts.odds.boolean;
    this.oddTotals.number = this.oddTotals.boolean + this.opts.odds.number;
    this.oddTotals.string = this.oddTotals.number + this.opts.odds.string;
    this.oddTotals.binary = this.oddTotals.string + this.opts.odds.binary;
    this.oddTotals.array = this.oddTotals.string + this.opts.odds.array;
    this.oddTotals.object = this.oddTotals.array + this.opts.odds.object;
    this.totalOdds =
      this.opts.odds.null +
      this.opts.odds.boolean +
      this.opts.odds.number +
      this.opts.odds.string +
      this.opts.odds.binary +
      this.opts.odds.array +
      this.opts.odds.object;
    if (this.opts.rootNode === 'string') {
      this.root = this.generateString();
      this.opts.nodeCount = 0;
    } else {
      this.root =
        this.opts.rootNode === 'object'
          ? {}
          : this.opts.rootNode === 'array'
            ? []
            : this.pickContainerType() === 'object'
              ? {}
              : [];
      this.containers.push(this.root as ContainerNode);
    }
  }
 
  /**
   * @ignore
   */
  public create(): JsonValue {
    for (let i = 0; i < this.opts.nodeCount; i++) this.addNode();
    return this.root;
  }
 
  /**
   * @ignore
   */
  public addNode(): void {
    const container = this.pickContainer();
    const newNodeType = this.pickNodeType();
    const node = this.generate(newNodeType);
    if (node && typeof node === 'object') this.containers.push(node as any);
    if (Array.isArray(container)) {
      const index = Math.floor(Math.random() * (container.length + 1));
      container.splice(index, 0, node);
    } else {
      const key = RandomJson.genString();
      (container as any)[key] = node;
    }
  }
 
  /**
   * @ignore
   */
  protected generate(type: NodeType): unknown {
    switch (type) {
      case 'null':
        return null;
      case 'boolean':
        return RandomJson.genBoolean();
      case 'number':
        return RandomJson.genNumber();
      case 'string':
        return this.generateString();
      case 'binary':
        return RandomJson.genBinary();
      case 'array':
        return [];
      case 'object':
        return {};
    }
  }
 
  protected generateString(): string {
    const strings = this.opts.strings;
    return strings ? randomString(strings) : RandomJson.genString();
  }
 
  /** @ignore */
  public pickNodeType(): NodeType {
    const odd = Math.random() * this.totalOdds;
    if (odd <= this.oddTotals.null) return 'null';
    if (odd <= this.oddTotals.boolean) return 'boolean';
    if (odd <= this.oddTotals.number) return 'number';
    if (odd <= this.oddTotals.string) return 'string';
    Iif (odd <= this.oddTotals.binary) return 'binary';
    if (odd <= this.oddTotals.array) return 'array';
    return 'object';
  }
 
  /**
   * @ignore
   */
  protected pickContainerType(): 'array' | 'object' {
    const sum = this.opts.odds.array + this.opts.odds.object;
    Iif (Math.random() < this.opts.odds.array / sum) return 'array';
    return 'object';
  }
 
  /**
   * @ignore
   */
  protected pickContainer(): ContainerNode {
    return this.containers[Math.floor(Math.random() * this.containers.length)];
  }
}