使用Ramda查找子索引和对应的父索引

问题描述 投票:0回答:1

我有两个实现,你可以在下面看到,但我不知道如何简化它。另外,也许我在这里遗漏了一些关于函数组合的东西,我很高兴得到任何帮助。

p.s.:摆脱箭头功能也很好。

const sections = [
  {
    key: 'first',
    data: [ { key: 'a' }, { key: 'b' } ]
  },
    {
    key: 'second',
    data: [ { key: 'c' }, { key: 'd' } ]
  },
  {
    key: 'third',
    data: [ { key: 'e' }, { key: 'f' } ]
  },
]
const pathToField = (key, sections) =>
  sections
    .reduce((found, section, parentIndex) =>
      compose(
        unless(equals(-1), pair(parentIndex)),
        findIndex(propEq(key, 'key')),
        prop('data')
      )(section)
    )

pathToField('f', sections)
const findKeyIndex = useWith(findIndex, [propEq(__, 'key'), prop('data')])

const findFieldIndex = curry(
  (key, sections) => compose(
    converge(pair, [prop('index'), findKeyIndex(key)]),
    find(compose(gt(__, -1), findKeyIndex(key))),
    addIndex(map)(flip(assoc('index')))
  )(sections)
)

findFieldIndex('f', sections)
functional-programming ramda.js
1个回答
0
投票

如果我必须进一步简化,我会这样做:

const sections = [{
    key: 'first',
    data: [{
      key: 'a'
    }, {
      key: 'b'
    }]
  },
  {
    key: 'second',
    data: [{
      key: 'c'
    }, {
      key: 'd'
    }]
  },
  {
    key: 'third',
    data: [{
      key: 'e'
    }, {
      key: 'f'
    }]
  },
];

const findKeyIndex = R.useWith(R.findIndex, [R.propEq(R.__, 'key'), R.prop('data')]);
const findFieldIndex = R.curry((key, sections) =>
  R.compose(
    R.converge(R.pair, [R.prop('index'), findKeyIndex(key)]),
    R.find(R.compose(R.gt(R.__, -1), findKeyIndex(key))),
    R.addIndex(R.map)(R.flip(R.assoc('index')))
  )(sections)
);

console.log(findFieldIndex('f', sections));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.29.0/ramda.min.js"></script>

© www.soinside.com 2019 - 2024. All rights reserved.