簡體   English   中英

部分函數與bind

[英]Partial functions with bind

所以最近我發現你可以使用bind做js的部分函數/ currying。 例如:

const foo = (a, b, c) => (a + (b / c))
foo.bind(null, 1, 2) //gives me (c) => (1 + (2 / c))

但是,這僅適用於您要咖喱的部分。 如果我想使用bind實現以下內容怎么辦?

(b) => (1 + (b / 2))

嘗試過各種解決方案,例如:

foo.bind(null, 1, null, 2)

有任何想法嗎? 用香草es6可以實現這個目標嗎?

您可以使用包裝器來重新排序參數。

 const foo = (a, b, c) => a + b / c, acb = (a, c, b) => foo(a, b, c); console.log(acb.bind(null, 1, 2)(5)); 

目前我想到了兩種實現方法(除了來自@NinaSholz的包裝器,這非常好):

1.使用合並兩個參數數組的curry函數:

 const foo = (a, b, c) => a + b / c; function curry(fn, ...args) { return function(...newArgs) { const finalArgs = args.map(arg => arg || newArgs.pop()); return fn(...finalArgs); }; } const curriedFoo = curry(foo, 1, null, 2); console.log(curriedFoo(4)) // Should print 1 + 4 / 2 = 3 

這里我們只是在我們想跳過的參數的位置發送nullundefined ,在第二次調用中我們按順序發送這些參數

2.使用對象作為命名參數

 const foo = ({a, b, c}) => a + b / c; function curry(fn, args) { return (newArgs) => fn({ ...args, ...newArgs }); } const curriedFoo = curry(foo, { a: 1, c: 2 }); console.log(curriedFoo({ b: 4 })); 

在這里,我們利用funcion簽名中的... (spread)運算符和對象語法來合並兩個參數對象;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM