utils.js

/**
 * @module Utils
 * @description A set of utilities
 */

/**
 * Sum the values of the array (must be numbers).
 *
 * @static
 * @method sum
 *
 * @param array {Array} array of number values
 * @return {Number} the sum of the values in the array
 */
export function sum(array) {
  return (array || []).reduce(function (memo, num) {
    if (typeof num === "number") {
      memo += num;
    }
    return memo;
  }, 0);
}

export function is(obj, type) {
  return Object.prototype.toString.call(obj) === "[object " + type + "]";
}

const interestingValues = (entry) =>
  typeof entry[1] !== "undefined" && entry[1] !== "undefined" && entry[1] !== Number.MAX_VALUE;

const formatEntry = (entry) => `${entry[0]} = ${entry[1]}`;

const formatObject = (entry) =>
  typeof entry[1] === "object"
    ? [entry[0], `{${entry[1]?.type ? entry[1].type : "object"}}`]
    : entry;

// This is displays well in Firefox, it doesn’t add much on Chrome
class Logger {
  #name = [];
  start(name, params = {}) {
    console.time(name);
    this.#name.push(name);
    const paramsString = Object.entries(params)
      .filter(interestingValues)
      .map(formatObject)
      .map(formatEntry)
      .join(", ");
    console.groupCollapsed(`${name}: ${paramsString}`);
  }
  end(obj) {
    console.groupEnd();
    console.timeEnd(this.#name.pop());
    if (typeof obj === "string") {
      console.log("%c" + obj, "color: #2289B6");
    } else {
      console.log(obj);
    }
    return obj;
  }
}
export const logger = new Logger();