Skip to content

Instantly share code, notes, and snippets.

@littledian
Last active January 14, 2019 08:20
Show Gist options
  • Save littledian/6a1f381fa23c2db7c6c2f5d52869d1cb to your computer and use it in GitHub Desktop.
Save littledian/6a1f381fa23c2db7c6c2f5d52869d1cb to your computer and use it in GitHub Desktop.

Revisions

  1. littledian revised this gist Jan 14, 2019. 1 changed file with 2 additions and 3 deletions.
    5 changes: 2 additions & 3 deletions destructing.js
    Original file line number Diff line number Diff line change
    @@ -1,10 +1,10 @@
    const values = [1, [2, 3, [4], 5], 6]
    const keys = '[a, [b, c, [d], e], f]'

    function parse (s, target) {
    function parse (keys, values) {
    const isArrayReg = /^\[(.+)]$/
    const keyMatchReg = /(.*?)([\[|,\]])(.*)/
    const arrayMatch = s.match(isArrayReg)
    const arrayMatch = keys.match(isArrayReg)
    if (!arrayMatch) return {}

    let depth = 0
    @@ -14,7 +14,6 @@ function parse (s, target) {

    const result = {}
    let content = arrayMatch[1]
    let values = target
    deepIndexMap.set(depth, index)
    deepValueMap.set(depth, values)

  2. littledian created this gist Jan 14, 2019.
    58 changes: 58 additions & 0 deletions destructing.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,58 @@
    const values = [1, [2, 3, [4], 5], 6]
    const keys = '[a, [b, c, [d], e], f]'

    function parse (s, target) {
    const isArrayReg = /^\[(.+)]$/
    const keyMatchReg = /(.*?)([\[|,\]])(.*)/
    const arrayMatch = s.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]
    let values = target
    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)