Last active
January 14, 2019 08:20
-
-
Save littledian/6a1f381fa23c2db7c6c2f5d52869d1cb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const values = [1, [2, 3, [4], 5], 6] | |
| const keys = '[a, [b, c, [d], e], f]' | |
| function parse (keys, values) { | |
| const isArrayReg = /^\[(.+)]$/ | |
| const keyMatchReg = /(.*?)([\[|,\]])(.*)/ | |
| const arrayMatch = keys.match(isArrayReg) | |
| if (!arrayMatch) return {} | |
| let depth = 0 | |
| let index = 0 | |
| const deepIndexMap = new Map() | |
| const deepValueMap = new Map() | |
| const result = {} | |
| let content = arrayMatch[1] | |
| deepIndexMap.set(depth, index) | |
| deepValueMap.set(depth, values) | |
| while (content) { | |
| const keyMatch = content.match(keyMatchReg) | |
| if (!keyMatch) { | |
| result[content] = values[index] | |
| content = '' | |
| continue | |
| } | |
| const key = keyMatch[1].trim() | |
| if (key !== '') { | |
| result[key] = values[index] | |
| index++ | |
| } | |
| const splitChar = keyMatch[2] | |
| if (splitChar === '[') { | |
| values = values[index] | |
| deepIndexMap.set(depth, index) | |
| depth++ | |
| index = 0 | |
| deepIndexMap.set(depth, index) | |
| deepValueMap.set(depth, values) | |
| } | |
| if (splitChar === ']') { | |
| depth-- | |
| index = deepIndexMap.get(depth) + 1 | |
| values = deepValueMap.get(depth) | |
| deepIndexMap.delete(depth) | |
| deepValueMap.delete(depth) | |
| } | |
| content = keyMatch[3].trim() | |
| } | |
| return result | |
| } | |
| const result = parse(keys, values) | |
| console.log(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment