使用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
我尝试使用箭头功能和部分功能,但无法使其正常工作
答案 0 :(得分:0)
第二个选项不起作用,因为_.get(foo2, 'bar')
会立即评估foo2.bar
并将partialRight
作为参数undefined
放入multiply
,因为稍后会分配4个get
因此4 * undefined
计算的NaN
为multiply
。
改进可能是:
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)