-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
186 lines (176 loc) · 5.57 KB
/
index.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
'use strict'
const depictsWholeNumber = require('depicts-whole-number').onlySafeNumbers
const c = {
ESCAPE_CHAR: '\\',
KEY_SEPARATOR: '.',
EMPTY_STRING: '',
REGEX: {
SQUARE_BRACKETS: /[\[\]]/g,
EXPLICIT_ARRAY: /\[(0|[1-9][0-9]*)\]/,
EXPLICIT_ARRAY_GM: /\[(0|[1-9][0-9]*)\]/g
}
}
const defaultOptions = {
CustomDelimiter: c.KEY_SEPARATOR,
AutocreateArrays: true,
ExplicitArrays: false,
CircularityCheck: false,
MaxDepth: 0
}
/**
* ObjectFx static class.
* @class
*/
class ObjectFx {
/**
* Checks for valid array index
* @param {String} s
* @return {Boolean}
*/
static _isValidArrayIndex (s) {
return depictsWholeNumber(s)
}
/**
* Checks for valid array index within square brackets (named 'explicit array' here)
* @param {String} s
* @return {Boolean}
*/
static _containsValidArrayIndex (s) {
const result = s.match(c.REGEX.EXPLICIT_ARRAY)
if (!result) {
return false
}
return depictsWholeNumber(result[1])
}
/**
* Merge user options with default options
* @param {Object} userOptions
* @return {Object}
*/
static _mergeOptions (userOptions) {
if (Object.prototype.toString.call(userOptions) === '[object Object]') {
for (let key of Object.keys(userOptions)) {
if (defaultOptions.hasOwnProperty(key) === false) {
throw new Error('Unsupported option: ' + key)
}
}
return Object.assign({}, defaultOptions, userOptions)
}
return defaultOptions
}
/**
* Expands (unflattens) a flattened object
* @param {Object} objFlat - flattened object
* @param {Object} userOptions - options
* @return {Object}
*/
static unflatten (objFlat, userOptions) {
return this.expand(objFlat, userOptions)
}
static expand (objFlat, userOptions) {
if (Object.prototype.toString.call(objFlat) !== '[object Object]') {
return null
}
const options = this._mergeOptions(userOptions)
const prefix = 'root' + options.CustomDelimiter
const regexConsecutiveSeparators = new RegExp('\\' + options.CustomDelimiter.split('').join('\\') + '{2,}', 'g')
const regexSurroundingSeparators = new RegExp('^\\' + options.CustomDelimiter.split('').join('\\') + '+|\\' + options.CustomDelimiter.split('').join('\\') + '+$', 'g')
const objExp = {}
let keys = Object.keys(objFlat)
for (let i = 0, kln = keys.length; i < kln; i++) {
const origKey = keys[i]
let currKey = prefix + origKey
if (options.ExplicitArrays) {
currKey = currKey
.replace(c.REGEX.EXPLICIT_ARRAY_GM, options.CustomDelimiter + '[$1]' + options.CustomDelimiter)
.replace(regexConsecutiveSeparators, options.CustomDelimiter)
.replace(regexSurroundingSeparators, c.EMPTY_STRING)
}
const chunks = currKey.split(options.CustomDelimiter)
let obj = objExp
for (let j = 0, cln = chunks.length; j < cln; j++) {
let currChunk = chunks[j]
let nextChunk = chunks[j + 1]
if (options.ExplicitArrays) {
currChunk = currChunk.replace(c.REGEX.SQUARE_BRACKETS, c.EMPTY_STRING)
}
if (!obj[currChunk]) {
if (j > cln - 2) {
obj[currChunk] = objFlat[origKey]
} else {
if ((options.AutocreateArrays && this._isValidArrayIndex(nextChunk)) ||
(options.ExplicitArrays && this._containsValidArrayIndex(nextChunk))) {
obj[currChunk] = []
} else {
obj[currChunk] = {}
}
}
}
/* if (options.ExplicitArrays && this._containsValidArrayIndex(currChunk)) {
currChunk.replace(c.REGEX.SQUARE_BRACKETS, c.EMPTY_STRING)
} */
obj = obj[currChunk]
}
}
return objExp.root
}
/**
* Flattens an object
* @param {Object} objExp
* @param {Object} userOptions - options
* @return {Object}
*/
static flatten (objExp, userOptions) {
if (Object.prototype.toString.call(objExp) !== '[object Object]' && Object.prototype.toString.call(objExp) !== '[object Array]') {
return null
}
const options = this._mergeOptions(userOptions)
if (options.CircularityCheck) {
try {
JSON.stringify(objExp)
} catch (err) {
if (err.message.match(/circular structure/ig)) {
// throw TypeError('Unable to flatten circular structure')
return null
}
}
}
let result = {}
const recurse = (cur, prop, lev) => {
if (options.MaxDepth > 0 && lev >= options.MaxDepth) {
result[prop] = cur
return
}
lev++
if (typeof cur !== 'object') { // Object(cur) !== cur
result[prop] = cur
} else if (Array.isArray(cur)) { // https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
for (let i = 0, l = cur.length; i < l; i++) {
if (options.ExplicitArrays) {
recurse(cur[i], prop + '[' + i + ']', lev)
} else {
let prefix = prop
if (prefix) {
prefix += options.CustomDelimiter
}
recurse(cur[i], prefix + i, lev)
}
}
/* if (l === 0) {
result[prop] = []
} */
} else {
if (Object.prototype.toString.call(cur) === '[object Object]') { // cur && cur.toString() === '[object Object]'
for (let p in cur) {
recurse(cur[p], prop ? prop + options.CustomDelimiter + p : p, lev)
}
} else {
result[prop] = cur
}
}
}
recurse(objExp, c.EMPTY_STRING, 0)
return result
}
}
module.exports = ObjectFx