0

假设我有以下代码:

const results = //some complex datastructure generated by a third party api call
const reducedList = results.map((item) => item.awesome_key)
  .map((awesomeKeyList) => awesomeKeyList
    .reduce((memo, awesomeKey) => {//stuff},{})))

这段代码就像一个魅力。现在说我决定通过 pluck 将 Ramda 用于第一张地图,如下所示:

  import R from Ramda;
  R.pluck('awesome_key', results)
    .map((awesomeKeyList) => awesomeKeyList
      .reduce((memo, awesomeKey) => {},{})))

这将失败:

Property 'reduce' does not exist on type '{}'.

Ramda.pluck 上的类型有:

pluck<T>(p: string|number, list: any[]): T[];
pluck(p: string|number): <T>(list: any[]) => T[];

这些类型会阻止我以这种方式使用 reduce 吗?

示例(简化)结构:

things: [
  {
    awesome_key: [{
      long_name: 'string',
      short_name: 'string',
      types: {
        0: 'string from set',
        1?: 'string'
      }
    }]
    other_fields not relevant here
    }
]
4

1 回答 1

0

从此开始:

const results = [
  {
    awesome_key: [{
      long_name: 'foo',
      short_name: 'bar',
      types: {
        0: 'abc',
        1: 'def',
        2: 'ghi'
      }
    }, {
      long_name: 'baz',
      short_name: 'qux',
      types: {
        0: 'pqr',
        1: 'xyz'
      }
    }],
    other_fields: 'not relevant here'
    }
]
const interestingTypes = ['pqr', 'xyz'];

据我所知,这两个都有相同的行为:

results.map((item) => item.awesome_key)
  .map((addressComponentList) => addressComponentList.reduce((memo, addressComponent) => {
     if (interestingTypes.indexOf(addressComponent.types[0]) !== -1) {
       if (!memo[addressComponent.types[0]]) {
         memo[addressComponent.types[0]] = addressComponent.long_name
       }  
     }
     return memo
   },{}));

R.pluck('awesome_key', results)
  .map((addressComponentList) => addressComponentList.reduce((memo, addressComponent) => {
     if (interestingTypes.indexOf(addressComponent.types[0]) !== -1) {
       if (!memo[addressComponent.types[0]]) {
         memo[addressComponent.types[0]] = addressComponent.long_name
       }  
     }
     return memo
   },{}));

就像这个一样,这对于 Ramda 来说更惯用:

R.pipe(
  R.pluck('awesome_key'),
  R.map(reduce((memo, addressComponent) => {
     if (interestingTypes.indexOf(addressComponent.types[0]) !== -1) {
       if (!memo[addressComponent.types[0]]) {
         memo[addressComponent.types[0]] = addressComponent.long_name
       }  
     }
     return memo
   },{}))
)(results) 

显然,这可能也可以清理一下,但我将代码基于您的另一个问题

pluck('field', xs)确实应该返回与xs.map(x => x.field).

您列出的打字稿签名不是我想的pluck那样,它被记录为:: k -> [{k: v}] -> [v],这意味着它接受一个(字符串)键和一个包含该键的对象列表,返回一个值列表

于 2017-05-23T14:53:14.703 回答