gpt4 book ai didi

javascript - 在 Ramda 的二维数组中获取给定元素的位置

转载 作者:行者123 更新时间:2023-11-30 08:27:57 24 4
gpt4 key购买 nike

我有一个包含一些数据的数组,即。

const data = [[   , '+',    ],
['+', , '+'],
[ , , '+']]

我想得到每个 '+' 元素的 [x, y] 坐标:

const expected = [[1, 0], [0, 1], [2, 1], [2, 2]]

我如何在 Ramda 中做到这一点?

我敲出了一些有效的代码:

const getHorizontalPosition = R.map(R.addIndex(R.reduce)
( (xs, el, idx) => R.equals('+', el) ? R.append(idx, xs) : xs, [] ))

const combineWithVerticalPosition = R.addIndex(R.chain)
( (xs, y) => R.map( (x) => [x, y] )(xs) )

pipe(getHorizontalPosition,
combineWithVerticalPosition)(data)

但是,如您所见,它很丑陋且可读性差。我怎样才能更优雅地做到这一点?

link to the code in ramda repl

最佳答案

您可能已经注意到,Ramda 在索引处理方面做的不多。我想不出一个特别好的解决方案。

像这样的东西会起作用,但评论中提到的两个 reducer 似乎不太优雅:

pipe(addIndex(map)((xs, i) => pipe(
map(equals('+')),
addIndex(map)((x, j) => x && [i, j]),
reject(equals(false))
)(xs)), unnest)(data)

你可以在 Ramda REPL 上看到这个.

关于javascript - 在 Ramda 的二维数组中获取给定元素的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42208565/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com