-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathutils.js
72 lines (61 loc) · 1.67 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
'use strict';
const util = require('util');
const is = require('is-type-of');
const URL = require('url').URL;
module.exports = {
convertObject,
safeParseURL,
};
function convertObject(obj, ignore) {
if (!is.array(ignore)) ignore = [ ignore ];
for (const key of Object.keys(obj)) {
obj[key] = convertValue(key, obj[key], ignore);
}
return obj;
}
function convertValue(key, value, ignore) {
if (is.nullOrUndefined(value)) return value;
let hit;
for (const matchKey of ignore) {
if (is.string(matchKey) && matchKey === key) {
hit = true;
} else if (is.regExp(matchKey) && matchKey.test(key)) {
hit = true;
}
}
if (!hit) {
if (is.symbol(value) || is.regExp(value)) return value.toString();
if (is.primitive(value)) return value;
if (is.array(value)) return value;
}
// only convert recursively when it's a plain object,
// o = {}
if (Object.getPrototypeOf(value) === Object.prototype) {
return convertObject(value, ignore);
}
// support class
const name = value.name || 'anonymous';
if (is.class(value)) {
return `<Class ${name}>`;
}
// support generator function
if (is.function(value)) {
if (is.generatorFunction(value)) return `<GeneratorFunction ${name}>`;
if (is.asyncFunction(value)) return `<AsyncFunction ${name}>`;
return `<Function ${name}>`;
}
const typeName = value.constructor.name;
if (typeName) {
if (is.buffer(value) || is.string(value)) return `<${typeName} len: ${value.length}>`;
return `<${typeName}>`;
}
/* istanbul ignore next */
return util.format(value);
}
function safeParseURL(url) {
try {
return new URL(url);
} catch (err) {
return null;
}
}