嵌套的约简函数/递归/函数式编程/树遍历

时间:2018-10-14 22:06:57

标签: javascript recursion functional-programming reduce traversal

我一直遇到这样的情况,最终我嵌套了许多reduce函数来深入研究一个对象。很难弄清楚逻辑,因为在底部,我需要访问沿途遍历的各种键。本质上,我正在寻找一种更好的方法来实现以下目标:

import { curry } from 'lodash/fp'
import { fromJS } from 'immutable'

const reduce = curry((fn, acc, it) => it.reduce(fn, acc))

describe('reduceNested', () => {
  const input = fromJS({
    a1: {
      b1: {
        c1: {
          d1: {
            e1: 'one',
            e2: 'two',
            e3: 'three'
          },
          d2: {
            e1: 'one',
            e2: 'two',
            e3: 'three'
          }
        },
        c2: {
          d1: {
            e1: 'one',
            e2: 'two'
          }
        }
      }
    },
    a2: {
      b1: {
        c1: {
          d1: {
            e1: 'one'
          },
          d2: {
            e1: 'one'
          }
        }
      },
      b2: {
        c1: {
          d1: {
            e1: 'one'
          },
          d2: {
            e1: 'one'
          }
        }
      }
    },
    a3: {
      b1: {
        c1: {}
      }
    }
  })

  const expected = fromJS({
    one: [
      'a1.b1.c1.d1.e1',
      'a1.b1.c1.d2.e1',
      'a1.b1.c2.d1.e1',
      'a2.b1.c1.d1.e1',
      'a2.b1.c1.d2.e1',
      'a2.b2.c1.d1.e1',
      'a2.b2.c1.d2.e1'
    ],
    two: ['a1.b1.c1.d1.e2', 'a1.b1.c1.d2.e2', 'a1.b1.c2.d1.e2'],
    three: ['a1.b1.c1.d1.e3', 'a1.b1.c1.d2.e3']
  })

  const init = fromJS({ one: [], two: [], three: [] })

  test('madness', () => {
    const result = reduce(
      (acc2, val, key) =>
        reduce(
          (acc3, val2, key2) =>
            reduce(
              (acc4, val3, key3) =>
                reduce(
                  (acc5, val4, key4) =>
                    reduce(
                      (acc6, val5, key5) =>
                        acc6.update(val5, i =>
                          i.push(`${key}.${key2}.${key3}.${key4}.${key5}`)
                        ),
                      acc5,
                      val4
                    ),
                  acc4,
                  val3
                ),
              acc3,
              val2
            ),
          acc2,
          val
        ),
      init,
      input
    )

    expect(result).toEqual(expected)
  })

  test('better', () => {
    const result = reduceNested(
      (acc, curr, a, b, c, d, e) =>
        acc.update(curr, i => i.push(`${a}.${b}.${c}.${d}.${e}`)),
      init,
      input
    )

    expect(result).toEqual(expected)
  })
})

我想编写一个功能reduceNested,该功能实现相同的结果,但没有所有嵌套的reduce函数。我没有在lodash/fp中看到任何东西或类似于地址的内容,所以我的想法是创建一个新函数reduceNested并为树中每个键的回调添加变量。我已经尝试实现实际的逻辑,但不幸的是暂时无法解决。我知道reduceNested将需要使用fn.length来确定要钻探的源代码的深度,但除此之外,我只是被卡住了。

const reduceNested = curry((fn, acc, iter) => {
  // TODO --> use (fn.length - 2)
})

4 个答案:

答案 0 :(得分:2)

您可以使用对于这种遍历非常理想的递归,如下所示:

function traverse(input, acc, path = []) {                       // path will be used internally so you don't need to pass it to get from the outside, thus it has a default value
    Object.keys(input).forEach(key => {                          // for each key in the input
        let newPath = [...path, key];                            // the new path is the old one + the current key
        if(input[key] && typeof input[key] === "object") {       // if the current value (at this path) is an object
            traverse(input[key], acc, newPath);                  // traverse it using the current object as input, the same accumulator and the new path
        } else {                                                 // otherwise (it's not an object)
            if(acc.hasOwnProperty(input[key])) {                 // then check if our accumulator expects this value to be accumulated
                acc[input[key]].push(newPath.join('.'));         // if so, add its path to the according array
            }
        }
    });
}

let input = {"a1":{"b1":{"c1":{"d1":{"e1":"one","e2":"two","e3":"three"},"d2":{"e1":"one","e2":"two","e3":"three"}},"c2":{"d1":{"e1":"one","e2":"two"}}}},"a2":{"b1":{"c1":{"d1":{"e1":"one"},"d2":{"e1":"one"}}},"b2":{"c1":{"d1":{"e1":"one"},"d2":{"e1":"one"}}}},"a3":{"b1":{"c1":{}}}};
let acc = { one: [], two: [], three: [] };

traverse(input, acc);

console.log(acc);

答案 1 :(得分:2)

功能样式

您的答案正确无误,但是根据用户提供的过程的长度重复进行是错误的。相反,应将可变长度路径作为一个可变长度值(一个数组)传递

const reduceTree = (proc, state, tree, path = []) =>
  reduce                        // call reduce with:
    ( (acc, [ key, value ]) =>  // reducer
        isObject (value)               // value is an object (another tree):
          ? reduceTree                 //   recur with:
              ( proc                   //     the proc
              , acc                    //     the acc
              , value                  //     this value (the tree)
              , append (path, key)     //     add this key to the path
              )                        // value is NOT an object (non-tree):
          : proc                       //   call the proc with:
              ( acc                    //     the acc
              , value                  //     this value (non-tree, plain value)
              , append (path, key)     //     add this key to the path
              )
    , state                     // initial input state 
    , Object.entries (tree)     // [ key, value ] pairs of input tree
    )

上面的自由值定义为使用前缀表示法,这在功能样式上更为常见–

const isObject = x =>
  Object (x) === x

const reduce = (proc, state, arr) =>
  arr .reduce (proc, state)

const append = (xs, x) =>
  xs .concat ([ x ])

现在我们有了通用的reduceTree函数–

const result =
  reduceTree
    ( (acc, value, path) =>           // reducer
        [ ...acc, { path, value } ] 
    , []                              // initial state
    , input                           // input tree
    )

console.log (result)
// [ { path: [ 'a1', 'b1', 'c1', 'd1', 'e1' ], value: 'one' }
// , { path: [ 'a1', 'b1', 'c1', 'd1', 'e2' ], value: 'two' }
// , { path: [ 'a1', 'b1', 'c1', 'd1', 'e3' ], value: 'three' }
// , { path: [ 'a1', 'b1', 'c1', 'd2', 'e1' ], value: 'one' }
// , { path: [ 'a1', 'b1', 'c1', 'd2', 'e2' ], value: 'two' }
// , { path: [ 'a1', 'b1', 'c1', 'd2', 'e3' ], value: 'three' }
// , { path: [ 'a1', 'b1', 'c2', 'd1', 'e1' ], value: 'one' }
// , { path: [ 'a1', 'b1', 'c2', 'd1', 'e2' ], value: 'two' }
// , { path: [ 'a2', 'b1', 'c1', 'd1', 'e1' ], value: 'one' }
// , { path: [ 'a2', 'b1', 'c1', 'd2', 'e1' ], value: 'one' }
// , { path: [ 'a2', 'b2', 'c1', 'd1', 'e1' ], value: 'one' }
// , { path: [ 'a2', 'b2', 'c1', 'd2', 'e1' ], value: 'one' } 
// ]

我们可以根据需要调整结果的输出–

const result =
  reduceTree
    ( (acc, value, path) =>                        // reducer
        ({ ...acc, [ path .join ('.') ]: value })
    , {}                                           // initial state
    , input                                        // input tree
    )

console.log (result)
// { 'a1.b1.c1.d1.e1': 'one'
// , 'a1.b1.c1.d1.e2': 'two'
// , 'a1.b1.c1.d1.e3': 'three'
// , 'a1.b1.c1.d2.e1': 'one'
// , 'a1.b1.c1.d2.e2': 'two'
// , 'a1.b1.c1.d2.e3': 'three'
// , 'a1.b1.c2.d1.e1': 'one'
// , 'a1.b1.c2.d1.e2': 'two'
// , 'a2.b1.c1.d1.e1': 'one'
// , 'a2.b1.c1.d2.e1': 'one'
// , 'a2.b2.c1.d1.e1': 'one'
// , 'a2.b2.c1.d2.e1': 'one'
// }

我们的测试input应该证明reduceTree适用于各种嵌套级别–

test ('better', () => {
  const input =
    { a: { b: { c: 1, d: 2 } }, e: 3 }

  const expected =
    { 'a.b.c': 1, 'a.b.d': 2, e: 3 }

  const result =
    reduceTree
      ( (acc, value, path) =>
          ({ ...acc, [ path .join ('.') ]: value })
      , {}
      , input 
      )

  expect(result).toEqual(expected)
})

最后,在下面的浏览器中验证程序是否正常工作

const isObject = x =>
  Object (x) === x

const reduce = (proc, state, arr) =>
  arr .reduce (proc, state)

const append = (xs, x) =>
  xs .concat ([ x ])

const reduceTree = (proc, state, tree, path = []) =>
  reduce
    ( (acc, [ key, value ]) =>
        isObject (value)
          ? reduceTree
              ( proc
              , acc
              , value
              , append (path, key)
              )
          : proc
              ( acc
              , value
              , append (path, key)
              )
    , state
    , Object.entries (tree)
    )

const input =
  { a: { b: { c: 1, d: 2 } }, e: 3 }

const result =
  reduceTree
    ( (acc, value, path) =>
        [ ...acc, { path, value } ]
    , []
    , input
    )

console.log (result)
// { 'a.b.c': 1, 'a.b.d': 2, e: 3 }


…在一些朋友的帮助下

即时型生成器可以轻松完成此类任务,同时提供直观的语言来描述预期的过程。下面我们添加traverse,它为嵌套的[ path, value ](对象)生成tree对–

const traverse = function* (tree = {}, path = [])
{ for (const [ key, value ] of Object.entries (tree))
    if (isObject (value))
      yield* traverse (value, append (path, key))
    else
      yield [ append (path, key), value ]
}

使用Array.from,我们可以将生成器直接插入我们现有的功能reduce中; reduceTree现在只是一个专业领域-

const reduceTree = (proc, state, tree) =>
  reduce
    ( (acc, [ path, value ]) =>
        proc (acc, value, path)
    , state
    , Array.from (traverse (tree))
    )

呼叫站点相同–

const input =
  { a: { b: { c: 1, d: 2 } }, e: 3 }

const result =
  reduceTree
    ( (acc, value, path) =>
        ({ ...acc, [ path .join ('.') ]: value })
    , {}
    , input
    )

console.log (result)
// { 'a.b.c': 1, 'a.b.d': 2, e: 3 }

在下面的浏览器中验证结果–

const isObject = x =>
  Object (x) === x

const reduce = (proc, state, arr) =>
  arr .reduce (proc, state)

const append = (xs, x) =>
  xs .concat ([ x ])

const traverse = function* (tree = {}, path = [])
{ for (const [ key, value ] of Object.entries (tree))
    if (isObject (value))
      yield* traverse (value, append (path, key))
    else
      yield [ append (path, key), value ]
}

const reduceTree = (proc, state, tree) =>
  reduce
    ( (acc, [ path, value ]) =>
        proc (acc, value, path)
    , state
    , Array.from (traverse (tree))
    )

const input =
  { a: { b: { c: 1, d: 2 } }, e: 3 }

const result =
  reduceTree
    ( (acc, value, path) =>
        ({ ...acc, [ path .join ('.') ]: value })
    , {}
    , input
    )

console.log (result)
// { 'a.b.c': 1, 'a.b.d': 2, e: 3 }

答案 2 :(得分:1)

我将使用递归generator function

解决此问题

在此示例中,我创建了一个单独的函数childPathsAndValues。在这里,我们已经实现了关注点的分离:该函数不需要知道您要将每个路径都附加到数组。它只是遍历对象并返回路径/值组合。

function* childPathsAndValues(o) {
   for(let k in o) {
     if(typeof(o[k]) === 'object') {
	  for(let [childPath, value] of childPathsAndValues(o[k])) {
  	      yield [`${k}.${childPath}`, value];
          }
     } else {
        yield [k, o[k]];
     }
  }
}

const input = {"a1":{"b1":{"c1":{"d1":{"e1":"one","e2":"two","e3":"three"},"d2":{"e1":"one","e2":"two","e3":"three"}},"c2":{"d1":{"e1":"one","e2":"two"}}}},"a2":{"b1":{"c1":{"d1":{"e1":"one"},"d2":{"e1":"one"}}},"b2":{"c1":{"d1":{"e1":"one"},"d2":{"e1":"one"}}}},"a3":{"b1":{"c1":{}}}};
  
const acc = {};
for(let [path, value] of childPathsAndValues(input)) {
   console.log(`${path} = ${value}`);
   acc[value] = acc[value] || [];
   acc[value].push(path);
}

console.log('*** Final Result ***');
console.log(acc);

答案 3 :(得分:0)

其他答案表明,递归是关键;但是,与其编写和重写会使您的数据发生变化并且需要针对每种情况进行手工处理的过程代码,不如在需要的地方使用和重用此功能。

Vanilla Javascript:

import { curry, __ } from 'lodash/fp'
const reduce = require('lodash/fp').reduce.convert({ cap: false })
reduce.placeholder = __


const reduceNested = curry((fn, acc, iter, paths) =>
  reduce(
    (acc2, curr, key) =>
      paths.length === fn.length - 3
        ? fn(acc2, curr, ...paths, key)
        : reduceNested(fn, acc2, curr, [...paths, key]),
    acc,
    iter
  )
)

export default reduceNested

用法:

test('better', () => {
  const result = reduceNested(
    (acc, curr, a, b, c, d, e) => ({
      ...acc,
      [curr]: [...acc[curr], `${a}.${b}.${c}.${d}.${e}`]
    }),
    init,
    input,
    []
  )

  expect(result).toEqual(expected)
})

使用Immutable.js:

import { curry } from 'lodash/fp'

const reduce = curry((fn, acc, it) => it.reduce(fn, acc))

const reduceNested = curry((fn, acc, iter, paths) =>
  reduce(
    (acc2, curr, key) =>
      paths.size === fn.length - 3
        ? fn(acc2, curr, ...paths, key)
        : reduceNested(fn, acc2, curr, paths.push(key)),
    acc,
    iter
  )
)

export default reduceNested

用法:

test('better', () => {
  const result = reduceNested(
    (acc, curr, a, b, c, d, e) =>
      acc.update(curr, i => i.push(`${a}.${b}.${c}.${d}.${e}`)),
    init,
    input,
    List()
  )

  expect(result).toEqual(expected)
})