UNPKG

@playbooks/utils

Version:

A collection of utilities used for Playbooks.

108 lines (107 loc) 2.75 kB
import bytes from "bytes"; import pluralize from "pluralize"; import uniqid from "uniqid"; const env = process.env.NEXT_PUBLIC_NODE_ENV || process.env.NODE_ENV; const sleep = (ms) => { return new Promise((resolve) => setTimeout(resolve, ms)); }; const getSeconds = () => { return Math.floor(Date.now() / 1e3); }; const getRandomInt = (max = 1e6) => { return Math.floor(Math.random() * max); }; const getUUID = (v = 36) => { return uniqid(); }; const getPlural = (value) => { return pluralize.plural(value); }; const getSingular = (value) => { return pluralize.singular(value); }; const formatUUID = (url, index = 2) => { const paths = url.split("?")[0].split("#")[0].split("/"); const name = paths[index]; return name?.toLowerCase(); }; const mapChildren = (data, key) => { const formattedData = []; data.map((record) => { const value = record[key]; if (isArray(value)) { const childData = mapChildren(value, key); childData.map((v) => formattedData.push(v)); } return formattedData.push(record); }); return formattedData; }; const buildArray = (count = 1) => { return Array.from(Array(count).keys()); }; const chunkArray = (array, chunkSize) => { let index = 0; const chunks = []; while (index < array.length) { const chunk = array.slice(index, index + chunkSize); index += chunkSize; chunks.push(chunk); } return chunks; }; const shuffleArray = (array) => { let randomIndex; let currentIndex = array.length; while (currentIndex !== 0) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex--; [array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]]; } return array; }; const computeBytes = (data, unit = "kb") => { return bytes.format(data, { unit }); }; const isArray = (data) => { return Array.isArray(data); }; const isDate = (data) => { return isObject(data) && typeof data.getMonth === "function"; }; const isFunction = (data) => { return data ? typeof data === "function" : false; }; const isObject = (data) => { return data !== null && data && typeof data === "object"; }; const isString = (data) => { return typeof data === "string"; }; const isEmpty = (data) => { if (data === null || data === void 0 || data === "undefined") return true; if (isArray(data)) return data.length === 0 ? true : false; if (isObject(data)) return Object.keys(data).length === 0 ? true : false; return data.length === 0 ? true : false; }; export { buildArray, chunkArray, computeBytes, env, formatUUID, getPlural, getRandomInt, getSeconds, getSingular, getUUID, isArray, isDate, isEmpty, isFunction, isObject, isString, mapChildren, shuffleArray, sleep };