typestar

util and structured clone in JavaScript

promisify for callback APIs, and a deep copy that handles cycles.

import { inspect, promisify } from "node:util";

function legacy(value, callback) {
  if (value < 0) return callback(new Error("negative"));
  return callback(null, value * 2);
}

const modern = promisify(legacy);
console.log(await modern(21));
console.log(await modern(-1).catch((error) => error.message));

const original = { when: new Date(0), tags: new Set(["a"]) };
original.self = original;
const copy = structuredClone(original);
console.log(copy.self === copy, copy.tags.has("a"), copy.when.getTime());

console.log(inspect({ nested: { deep: [1, 2] } }, { depth: 0 }));

How it works

  1. promisify converts an error-first callback function.
  2. structuredClone copies Maps, Sets, Dates and cycles.
  3. util.inspect is what console.log uses underneath.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
573
Tokens
179
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 102 seconds.

Type this snippet

Step 2 of 3 in The process, step 8 of 18 in Node.js.

← Previous Next →