Collections (Arrays & Objects)

(, en)

Objects

Is it an object?

export function isObject(o: any) {
  return typeof o === "object" && !Array.isArray(o) && o !== null;
}

Source

export function isEmpty(obj: any): boolean {
  if (obj == null || typeof obj === "undefined") {
    return true;
  }
  if (typeof obj === "string") {
    return !obj.length;
  }
  if (obj instanceof Set || obj instanceof Map) {
    return !obj.size;
  }
  for (const _ in obj) {
    return false;
  }

  return true;
}

Object has key

https://stackoverflow.com/questions/455338/how-do-i-check-if-an-object-has-a-key-in-javascript

Arrays

Ranges

function* range(start, end) {
  for (let i = start; i <= end; i++) {
    yield i;
  }
}

for (i of range(1, 5)) {
  console.log(i);
}

source

Empty or not?

if (!Array.isArray(array) || !array.length) {
  // array does not exist, is not an array, or is empty
  // ⇒ do not attempt to process array
}

if (Array.isArray(array) && array.length) {
    // array exists and is not empty
}

source

Intersperse

const intersperse = (xs, s) => xs.reduce((acc, x) => (acc ? [...acc, s, x] : [x]), null);

Miscellaneous

Use millimetres in pdfmake

const MILLIMETERS_IN_INCH = 25.4;
const POINTS_IN_INCH = 72;

function mm2pt(mm) {
  const inches = mm / MILLIMETERS_IN_INCH;
  return inches * POINTS_IN_INCH;
}