UNPKG

2.98 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const path_1 = require("path");
4let objUid = 0;
5let objUidMap = new WeakMap();
6/** @internal */
7function getType(key) {
8 const t = Object.prototype.toString.call(key);
9 return t.slice(8, -1).toLowerCase();
10}
11exports.getType = getType;
12/** @internal */
13function hashAny(key) {
14 switch (getType(key)) {
15 case 'undefined':
16 case 'null':
17 case 'boolean':
18 case 'number':
19 case 'regexp':
20 return key + '';
21 case 'date':
22 return '📅' + key.getTime();
23 case 'string':
24 return '📝' + key;
25 case 'array':
26 return '🔗' + key.map(k => hashAny(k)).join('⁞');
27 case 'object':
28 return key.constructor.name + JSON.stringify(key, (k, v) => {
29 if (!k)
30 return v;
31 return hashAny(v);
32 });
33 default:
34 let uid = objUidMap.get(key);
35 if (!uid) {
36 uid = ++objUid;
37 objUidMap.set(key, uid);
38 }
39 return '⭕️' + uid;
40 }
41}
42exports.hashAny = hashAny;
43exports.sleep = (ms) => {
44 return new Promise(res => setTimeout(res, ms));
45};
46function throttle(cb, ms) {
47 let timer;
48 let newCb = (...args) => {
49 timer && clearTimeout(timer);
50 timer = setTimeout(cb, ms, ...args);
51 };
52 return newCb;
53}
54exports.throttle = throttle;
55exports.Is = {
56 defed(v) {
57 return typeof v !== 'undefined' && v !== null;
58 },
59 str(v) {
60 return typeof v === 'string';
61 },
62 bool(v) {
63 return typeof v === 'boolean';
64 },
65 fn(v) {
66 return typeof v === 'function';
67 },
68 obj(v) {
69 return v && typeof v === 'object';
70 },
71 num(v) {
72 return typeof v === 'number';
73 }
74};
75function defaults(...args) {
76 let [val, ...defaultVals] = args;
77 if (exports.Is.defed(val))
78 return val;
79 if (defaultVals.length === 0) {
80 return val;
81 }
82 return defaults(...defaultVals);
83}
84exports.defaults = defaults;
85/**
86 * Generate unique task names with namespaces via object tree.
87 * @param obj
88 * @param ns Namespace
89 * @param sep Separator for namespaces
90 * @example
91 * ```ts
92 * /** N.aa.bb => 'aa:bb' *\/
93 * const N = namespacify({
94 * aa: { bb: { cc: '' } },
95 * cc: '',
96 * ff: ''
97 * })
98 *
99 * /* =>
100 * { aa: { bb: { cc: 'aa:bb:cc' } },
101 * cc: 'cc',
102 * ff: 'ff' } *\/
103 * ```
104 */
105function namespacify(obj, ns = '', sep = ':') {
106 for (const key in obj) {
107 const val = obj[key] || key;
108 if (exports.Is.str(val)) {
109 obj[key] = `${ns}${ns && sep}${val}`;
110 }
111 else if (exports.Is.obj(val)) {
112 namespacify(val, `${ns}${ns && sep}${key}`, sep);
113 }
114 }
115 return obj;
116}
117exports.namespacify = namespacify;
118exports.DefaultLogFile = path_1.join(process.cwd(), 'foy.log');
119//# sourceMappingURL=utils.js.map
\No newline at end of file