Ramda(或其他 FP 库)用于选择空键的用法

Ramda (or other FP lib) usage for selecting maybe null keys

假设我的数据结构如下:

let slots = {
  7 : [ 'a', 'b', 'c' ],
  8 : [ 'd', 'e', 'f' ]
}
let names = {
  a : { name : 'Joe' },
  b : { name : 'Doe' },
  c : { name : 'Cecilia' },
  d : { name : 'Hugh' }
}

... 其中 slots[x][y]names' 键相关。

鉴于 x 和 y 是可以从 0 到 10 的输入,为了获取名称和解释错误情况,可以写:

let nameKey = (slots[x] || [])[y] //string or undefined
let name = (names[nameKey] || {}).name || ''

所以我在这里使用了 || []|| {} 之类的东西,以避免某些输入和空键可能​​出现的错误。我听说通过使用 FP 套件,我还可以以更简洁的方式实现这一点。为了实现这一点,我应该使用 Ramda(或任何其他 FP 工具包)的哪些功能?

Ramda 有 pathOr:

let slots = {
  7 : [ 'a', 'b', 'c' ],
  8 : [ 'd', 'e', 'f' ]
}
let names = {
  a : { name : 'Joe' },
  b : { name : 'Doe' },
  c : { name : 'Cecilia' },
  d : { name : 'Hugh' }
}

你会这样做:

let nameKey = R.pathOr(undefined, [x, y], slots);
//it'd be probably better to normalize it to always a string instead of undefined (but that's what you wrote)
let name = R.pathOr('', [nameKey, 'name'], names);