-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrim.ts
40 lines (36 loc) · 1.39 KB
/
trim.ts
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
import { isArrayLike, isDictLike } from "https://lib.deno.dev/x/is_like@latest/index.js";
import { ensureArray } from "./ensureType.ts";
/**
* Trims the leading and tailing spaces of a string, the string properties of
* an object, or the string and object elements in an array.
*/
export default function trim<T extends any>(target: T, deep = false): T extends string ? string : T {
if (typeof target === "string") {
return target.trim() as any;
} else if (isArrayLike(target, true)) {
return ensureArray(target).map(item => trim(item, deep)) as any;
} else if (isDictLike(target)) {
const keys = [
...Object.getOwnPropertyNames(target),
...Object.getOwnPropertySymbols(target)
];
return keys.reduce((result, key) => {
let value = target[key];
if (typeof value === "string") {
value = value.trim();
} else if (deep) {
if (isArrayLike(value, true)) {
value = ensureArray(value).map(item => {
return isDictLike(item) ? trim(item, deep) : item;
});
} else if (isDictLike(value)) {
value = trim(value, deep);
}
}
result[key] = value;
return result;
}, {} as any);
} else {
return target as any;
}
}