JavaScript函数参数翻转——连接多个数组——zip、zipwith
作者:互联网
1.
let f = {}; f.flip = (fn)=>(...args)=>fn(...args.reverse()); var divide = (a,b)=>a / b; var flip = f.flip(divide); flip(10, 5) // 0.5 flip(1, 10) // 10 var three = (a,b,c)=>[a, b, c]; var flip = f.flip(three); flip(1, 2, 3); // => [2, 1, 3]
2.
let f = {}; f.concat = (...xs) => xs.reduce((a, b) => a.concat(b)); f.concatMap = (g, ...xs) => f.concat(xs.map(g)); f.concat([5], [27], [3]) // [5, 27, 3] f.concatMap(x => 'hi ' + x, 1, [[2]], 3) // ['hi 1', 'hi 2', 'hi 3']
3.
let f = {}; f.zip = (...xs)=>{ let r = []; let nple = []; let length = Math.min.apply(null, xs.map(x=>x.length)); for (var i = 0; i < length; i++) { xs.forEach(x=>nple.push(x[i])); r.push(nple); nple = []; } return r; } ; f.zipWith = (op,...xs)=>f.zip.apply(null, xs).map((x)=>x.reduce(op)); let a = [0, 1, ]; let b = [3, 4, 6]; let c = [6, 7, 8]; console.log('--') console.log(f.zip(a, b)) // [[0, 3], [1, 4], [2, 5]] console.log(f.zipWith((a,b)=>a + b, a, b, c))
标签:...,zip,zipwith,flip,函数参数,let,var,xs 来源: https://www.cnblogs.com/sunupo/p/15539309.html