UNPKG

1.73 kBJavaScriptView Raw
1/* eslint no-nested-ternary:0 */
2'use strict';
3const tinydate = require('tinydate');
4
5const $ = exports
6
7// @see http://stackoverflow.com/a/16608074
8$.isObject = val => Boolean(val) && (val.constructor === Object);
9
10$.isEmptyObj = val => $.isObject(val) && !Object.keys(val).length;
11
12$.toArray = val => (val === null || val === undefined) ? [] : Array.isArray(val) ? val : [val];
13
14/**
15 * Format a task's duration.
16 * @param {Array} arr Output from `process.hrtime`
17 * @return {String}
18 */
19$.formatTime = arr => {
20 let unit = 'ms';
21 let num = Math.round(arr[1] / 1000000);
22 if (arr[0] > 0) {
23 unit = 's';
24 num = (arr[0] + num / 1000).toFixed(2);
25 }
26 return `${num}${unit}`;
27}
28
29/**
30 * Get the current time!
31 * @return {String} Formatted as `[HH:mm:ss]`.
32 */
33$.getTime = tinydate('[{HH}:{mm}:{ss}]');
34
35/**
36 * Check if value is unique within the group. Modify if is not.
37 * @param {String} val The value to check.
38 * @param {Array} arr The array of values to check against.
39 * @return {String} The unique value possibly incremented.
40 */
41$.valUniq = (val, arr) => {
42 let n = 0;
43 let v = val;
44 while (arr.indexOf(v) !== -1) {
45 n++;
46 v = val.concat(n);
47 }
48 return v;
49}
50
51/**
52 * Get a unique Set of Array values
53 * @param {Array} arr The values to check
54 * @return {Set} The unique values
55 */
56$.getUniques = arr => {
57 const len = arr.length;
58 const res = [];
59 let i = 0;
60
61 for (; i < len; i++) {
62 const curr = arr[i];
63 if (res.indexOf(curr) === -1) {
64 res.push(curr);
65 }
66 }
67
68 return res;
69}
70
71function flat(arr, res) {
72 let i = 0;
73 const len = arr.length;
74 for (; i < len; i++) {
75 const cur = arr[i];
76 Array.isArray(cur) ? flat(cur, res) : res.push(cur);
77 }
78 return res;
79}
80
81$.flatten = arr => flat(arr, []);