1.函數式編程是什么 為什么要函數式編程
2.什么是函數組合
3.柯里化實現
嚴格意義上的柯里化是將多參函數變?yōu)閱螀⒑瘮?,每個函數可以看成處理數據的管道,函數組合就是將各個管道串聯(lián)起來,因為函數的返回值只有一個,所以如果想串聯(lián)函數,就需要被串聯(lián)的函數是單參的,這就需要柯里化。函數組合后返回一個函數,這時候傳遞最后的數據,執(zhí)行函數就得到最后想要的結果。簡明 JavaScript 函數式編程——入門篇 說的比較清楚
怎樣去debug組合的函數
var dasherize = compose(join('-'), toLower, trace("after split"), split(' '), replace(/\s{2,}/ig, ' '));
// after split [ 'The', 'world', 'is', 'a', 'vampire' ]
需要個trace函數,本以為復雜,其實很簡單,采自函數式編程指北
var trace = curry(function(tag, x){
console.log(tag, x);
return x;
});
看到trace,自然會聯(lián)想到console.trace,做出改進
const trace = curry(function(tag, x) {
console.log(tag, x);
console.trace("trace");
return x;
});
F12打開控制臺就看到函數的調用棧了
一個例子
- 獲取所有年齡小于 18 歲的對象,并返回他們的名稱和年齡。
還是上篇文章中的例子:
具體的代碼在functional demo使用jest測試
import * as R from "ramda";
/*
* ex1
*/
// :: String -> Number -> Object -> Boolean
const propLt = R.curry((p, c) =>
R.pipe(
R.prop(p),
R.lt(R.__, c)
)
);
// :: Object -> Boolean
const ageUnder18 = propLt("age", 18);
// :: [a] -> b
const getAgeUnder18 = R.pipe(
R.filter(ageUnder18),
R.map(R.pickAll(["name", "age"]))
);
describe("Test", function() {
it("1. 獲取所有年齡小于18歲的對象,并返回他們的名稱和年齡", function() {
const result = getAgeUnder18(data);
expect(result).toEqual(ageLt18);
});
});
pipe更compose執(zhí)行順序相反,pipe從左到右執(zhí)行,R.filter R.map跟數組的filter map類似,都需要傳遞函數,R.prop,R.lt,R.pickAll源碼都很簡單
ramda@0.27.0
- R.prop
/**
* Returns a function that when supplied an object returns the indicated
* property of that object, if it exists.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Object
* @typedefn Idx = String | Int
* @sig Idx -> {s: a} -> a | Undefined
* @param {String|Number} p The property name or array index 對象的名字或者數組的下標
* @param {Object} obj The object to query 對象或者數組
* @return {*} The value at `obj.p`. 返回對象的值或者數組的值
* @see R.path, R.props, R.pluck, R.project, R.nth
* @example
*
* R.prop('x', {x: 100}); //=> 100
* R.prop('x', {}); //=> undefined
* R.prop(0, [100]); //=> 100
* R.compose(R.inc, R.prop('x'))({ x: 3 }) //=> 4
*/
var prop = _curry2(function prop(p, obj) {
if (obj == null) {
return;
}
return _isInteger(p) ? nth(p, obj) : obj[p];
});
export default prop;
- R.lt
import _curry2 from './internal/_curry2';
/**
* Returns `true` if the first argument is less than the second; `false`
* otherwise.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Relation
* @sig Ord a => a -> a -> Boolean
* @param {*} a
* @param {*} b
* @return {Boolean}
* @see R.gt
* @example
*
* R.lt(2, 1); //=> false
* R.lt(2, 2); //=> false
* R.lt(2, 3); //=> true
* R.lt('a', 'z'); //=> true
* R.lt('z', 'a'); //=> false
*/
var lt = _curry2(function lt(a, b) { return a < b; });
export default lt;
- R.pickAll 攫取對象中指定keys的子對象
import _curry2 from './internal/_curry2';
/**
* Similar to `pick` except that this one includes a `key: undefined` pair for
* properties that don't exist.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Object
* @sig [k] -> {k: v} -> {k: v}
* @param {Array} names an array of String property names to copy onto a new object
* @param {Object} obj The object to copy from
* @return {Object} A new object with only properties from `names` on it.
* @see R.pick
* @example
*
* R.pickAll(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4}
* R.pickAll(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, e: undefined, f: undefined}
*/
var pickAll = _curry2(function pickAll(names, obj) {
var result = {};
var idx = 0;
var len = names.length;
while (idx < len) {
var name = names[idx];
result[name] = obj[name];
idx += 1;
}
return result;
});
export default pickAll;
源碼在寫的時候并沒有使用單參函數,都是用了curry函數進行柯里化,但是所有的函數都有一個規(guī)律,第二個參數是管道中流動的數據,第一個參數是一開始傳遞進去的。所以流動的數據應該放在需要被柯里化的函數參數的最后面。這樣我們可以自我實現R.filter R.map
const filter = R.curry((func, arr) => arr.filter(func));
const map = R.curry((func, arr) => arr.map(func));
哇 好簡單。但是這么寫是不是有點復雜,最原始直接的辦法:
arr.filter((x) => x.age < 18).map((x) => ({ name: x.name, age: x.age }));
對于數組的操作感覺這么寫直觀,簡單。從復用的角度說ageUnder18函數并不簡單,R.pickAll相對簡單點,返回了函數。
4. lodash/fp 模塊
在 ES6 大行其道的今天,還有必要使用 lodash 之類的庫嗎?討論指出:
- lodash/fp 下面的所有方法,都是 Immutable 的。
- lodash/fp 下面的所有方法,都是 Auto-curried Iteratee-first Data-last 處理過的。
- 通過 flow 創(chuàng)建的函數是 lazy evaluation 的。
在我們安裝lodash的時候已經安裝了lodash/fp模塊,可以隨性的使用。函數式風格跟lodash 鏈式調用也有爭議,其中提到flow 已經自帶做了這種性能優(yōu)化,而原生的鏈式調用是不會有這種性能優(yōu)化的。看了《JavaScript函數式編程指南》導讀與總結發(fā)現lodash@4.17.15鏈式調用也做了惰性求值。