-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathJSONfn.ts
More file actions
58 lines (51 loc) · 1.46 KB
/
JSONfn.ts
File metadata and controls
58 lines (51 loc) · 1.46 KB
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
// https://dev.to/localazy/how-to-pass-function-to-web-workers-4ee1
// https://github.com/vkiryukhin/jsonfn
export const JSONfn = {
stringify(obj: any) {
return JSON.stringify(obj, function (key, value) {
var fnBody;
if (value instanceof Function || typeof value == 'function') {
fnBody = value.toString();
if (fnBody.length < 8 || fnBody.substring(0, 8) !== 'function') {
//this is ES6 Arrow Function
return '_NuFrRa_' + fnBody;
}
return fnBody;
}
if (value instanceof RegExp) {
return '_PxEgEr_' + value;
}
return value;
});
},
parse(str: any, date2obj?: any) {
var iso8061 = date2obj ? /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/ : false;
return JSON.parse(str, function (key, value) {
var prefix;
if (typeof value != 'string') {
return value;
}
if (value.length < 8) {
return value;
}
prefix = value.substring(0, 8);
// @ts-ignore
if (iso8061 && value.match(iso8061)) {
return new Date(value);
}
if (prefix === 'function') {
return eval('(' + value + ')');
}
if (prefix === '_PxEgEr_') {
return eval(value.slice(8));
}
if (prefix === '_NuFrRa_') {
return eval(value.slice(8));
}
return value;
});
},
clone(obj: any, date2obj?: any) {
return JSONfn.parse(JSONfn.stringify(obj), date2obj);
},
};