1 | var staticParseInt = require('./staticParseInt')
|
2 |
|
3 | var helperGetHGSKeys = require('./helperGetHGSKeys')
|
4 |
|
5 | var hasOwnProp = require('./hasOwnProp')
|
6 |
|
7 | var sKeyRE = /(.+)?\[(\d+)\]$/
|
8 |
|
9 | function setDeepProps (obj, key, isEnd, nextKey, value) {
|
10 | if (obj[key]) {
|
11 | if (isEnd) {
|
12 | obj[key] = value
|
13 | }
|
14 | } else {
|
15 | var index
|
16 | var rest
|
17 | var currMatchs = key ? key.match(sKeyRE) : null
|
18 | if (isEnd) {
|
19 | rest = value
|
20 | } else {
|
21 | var nextMatchs = nextKey ? nextKey.match(sKeyRE) : null
|
22 | rest = nextMatchs && !nextMatchs[1] ? new Array(staticParseInt(nextMatchs[2]) + 1) : {}
|
23 | }
|
24 | if (currMatchs) {
|
25 | if (currMatchs[1]) {
|
26 |
|
27 | index = staticParseInt(currMatchs[2])
|
28 | if (obj[currMatchs[1]]) {
|
29 | obj[currMatchs[1]][index] = rest
|
30 | } else {
|
31 | obj[currMatchs[1]] = new Array(index + 1)
|
32 | obj[currMatchs[1]][index] = rest
|
33 | }
|
34 | } else {
|
35 |
|
36 | obj[currMatchs[2]] = rest
|
37 | }
|
38 | } else {
|
39 |
|
40 | obj[key] = rest
|
41 | }
|
42 | return rest
|
43 | }
|
44 | return obj[key]
|
45 | }
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 | function set (obj, property, value) {
|
54 | if (obj) {
|
55 | if ((obj[property] || hasOwnProp(obj, property)) && !isPrototypePolluted(property)) {
|
56 | obj[property] = value
|
57 | } else {
|
58 | var rest = obj
|
59 | var props = helperGetHGSKeys(property)
|
60 | var len = props.length
|
61 | for (var index = 0; index < len; index++) {
|
62 | if (isPrototypePolluted(props[index])) {
|
63 | continue
|
64 | }
|
65 | var isEnd = index === len - 1
|
66 | rest = setDeepProps(rest, props[index], isEnd, isEnd ? null : props[index + 1], value)
|
67 | }
|
68 | }
|
69 | }
|
70 | return obj
|
71 | }
|
72 |
|
73 |
|
74 |
|
75 |
|
76 |
|
77 | function isPrototypePolluted(key) {
|
78 | return key === '__proto__' || key === 'constructor' || key === 'prototype'
|
79 | }
|
80 |
|
81 | module.exports = set
|