-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
68 lines (64 loc) · 1.61 KB
/
Copy pathindex.js
File metadata and controls
68 lines (64 loc) · 1.61 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
59
60
61
62
63
64
65
66
67
68
function isPrimitive(payload) {
return !payload || (payload.constructor !== Array && payload.constructor !== Object);
}
class KeySet {
constructor() {
this._map = {};
this._size = 0;
}
add(item) {
if (item in this._map) {
return this._map[item];
}
this._map[item] = this._size;
this._size++;
return this._size - 1;
}
toArray() {
return Object.entries(this._map).reduce((result, [key, value]) => {
result[value] = key;
return result;
}, []);
}
}
function compress(data) {
const keys = new KeySet();
function inner(data) {
if (isPrimitive(data)) {
return data;
}
let newData;
if (data.constructor === Array) {
newData = data.map(x => {
return inner(x);
});
} else {
newData = Object.entries(data).reduce((accum, [key, value]) => {
const keyIndex = keys.add(key);
accum[keyIndex] = inner(value);
return accum;
}, {});
}
return newData;
}
return {
data: inner(data),
keys: keys.toArray(),
};
}
function decompress(data, keys) {
if (isPrimitive(data)) {
return data;
}
if(data.constructor === Array){
return data.map(x=>{
return decompress(x, keys);
});
}
Object.keys(data).forEach(key => {
data[keys[key]] = decompress(data[key], keys);
delete data[key];
});
return data;
}
module.exports = {compress, decompress};