/
util.ts
53 lines (46 loc) · 1.42 KB
/
util.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
41
42
43
44
45
46
47
48
49
50
51
52
53
export const get = (obj: any, path: string, defaultValue: any = undefined) => {
const travel = (regexp: RegExp) =>
String.prototype.split
.call(path, regexp)
.filter(Boolean)
.reduce((res: any, key: any) => (res !== null && res !== undefined ? res[key] : res), obj);
const result = travel(/[,[\]]+?/) || travel(/[,[\].]+?/);
return result === undefined || result === obj ? defaultValue : result;
};
export function throttle(func: any, timeFrame: number) {
var lastTime: number = 0;
return function () {
var now: number = Number(new Date());
if (now - lastTime >= timeFrame) {
func();
lastTime = now;
}
};
}
export function deepCopy(obj: any): any {
var copy;
// Handle the 3 simple types, and null or undefined
if (null == obj || "object" != typeof obj) return obj;
// Handle Array
if (obj instanceof Array) {
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = deepCopy(obj[i]);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
const copy: any = {};
for (const attr in obj) {
const key: string = attr
if (obj.hasOwnProperty(key))
copy[key] = deepCopy(obj[key]);
}
return copy;
}
throw new Error("Unable to copy obj! Its type isn't supported.");
}
export function isPlainObject (obj: any) {
return Object.prototype.toString.call(obj) === '[object Object]';
}