Lodash部分与对象路径

时间:2016-12-08 15:57:04

标签: javascript lodash

使用lodash或箭头函数,在以下示例中重写func声明的更优雅的方法是什么?

  function multiply(a, b) {
    return a * b;
  }

  let foo = {};
  let func = function (v) { return multiply(v, _.get(foo, 'bar')) };
  foo.bar = 4;
  console.log(func(4)); //Result in 16

  let foo2 = {};
  let func2 = _.unary(_.partialRight(multiply, _.get(foo2, 'bar')));
  foo2.bar = 4;
  console.log(func2(4)); //Result in NaN

  let foo3 = {};
  let func3 = (v) => multiply(v, _.get(foo3, 'bar'));
  foo3.bar = 4;
  console.log(func3(4)); //Result in NaN

我尝试使用箭头功能和部分功能,但无法使其正常工作

1 个答案:

答案 0 :(得分:0)

Your third option is working.

第二个选项不起作用,因为_.get(foo2, 'bar')会立即评估foo2.bar并将partialRight作为参数undefined放入multiply,因为稍后会分配4个get

因此4 * undefined计算的NaNmultiply

改进可能是:

  • curry func
  • 制作 const multiply = _.curryRight(function(a, b) { return a * b; }) let foo3 = {}; foo3.bar = 4; let func3 = multiply(_.get(foo3, 'bar')); console.log(func3(4)); pure

例如:

val records = sc.textFile(filename).persist(StorageLevel.MEMORY_AND_DISK_SER) val partitionCount = records.getNumPartitions
println(s"Number of Paritions: " + partitionCount)

println(s"Number record count: " + records.count)

val idRecs = records.map(x => { MyServiceHelper.getIdRecord(x) }).persist(StorageLevel.MEMORY_AND_DISK_SER)

idRecs.take(300).foreach(println) records.unpersist(false)

val kk = idRecs.reduceByKey({(a, b) => b ::: a}, partitionCount*4)