DAY 3
0
Software Development

yo, what's up?

## Curry 的功用?

``````const add = (x, y) => x + y;
``````

``````add(1, 1) // 2
``````

``````add(1) // NaN

``````

## Curry 是什麼呢?

``````const addC = x => y => x + y;
``````

``````// utils.js

// example.js
import { add1 } from './utils';

[1, 2, 3, 4, 5].map(add1) // [2, 3, 4, 5, 6]
``````

## 實作 Curry

``````function curry(fn, arity = fn.length) {
return (function nextCurried(prevArgs) {
return function curried(nextArgs) {
const args = [...prevArgs, nextArgs];
if(args.length >= arity){
return fn(...args);
}
return nextCurried(args)
}
})([])
}
``````

``````const add = (x, y) => x + y;

``````

`1` 被傳入時，此時 `args` 會變成 `[1]`，此時 `args.length` 還小於 `add` 傳入參數長度(2)， 所以會進行遞迴 `nextCurried([1])`

## Loose curry

``````function looseCurry(fn, arity = fn.length) {
return (function nextCurried(prevArgs){
return function curried(nextArgs){
const args = [...prevArgs, ...nextArgs];
if(args.length >= artiy){
return fn(...args);
}
return nextCurried(args)
}
})([])
}

const add = (x, y) => x + y;

``````

## So What...?

1. 對使用者居住的緯度由高到低進行排序，
2. 取出使用者的名字，
3. 在每位使用者名子後面加 "!"。

``````// sort
const sort = (fn, data) => [...data].sort(fn)

// get
const get = (key, data) => data[key]

// concat
const concat = (symbol, data) => data.concat(symbol);

// map
const map = (transformer, data) => data.map(transformer)
``````

``````fetch('https://jsonplaceholder.typicode.com/users')
.then(r => r.json())
.then(sortedData => map((data) => get('username', data), sortedData))
.then(result => console.log(result))
.catch(err => console.error(err));
``````

``````// sort
const sort = curry((fn, data) => [...data].sort(fn));
// get
const get = curry((key, data) => data[key]);
// concat
const concat = curry((symbol, data) => data.concat(symbol));
// map
const map = curry((transformer, data) => data.map(transformer));
``````
``````fetch('https://jsonplaceholder.typicode.com/users')
.then(r => r.json())
.then(xs => map(concat('!'))(xs))
.then(result => console.log(result))
.catch(err => console.error(err));
``````

``````fetch('https://jsonplaceholder.typicode.com/users')
...
...
``````

``````fetch('https://jsonplaceholder.typicode.com/users')
.then(r => r.json())
.then(map(concat('!')))
.then(console.log)
.catch(console.error)
``````

1. 易讀性增加

``````const getNameFromSortedData = sortedData =>
``````
``````fetch('https://jsonplaceholder.typicode.com/users')
...
.then(getNameFromSortedData)
...
``````

``````fetch('https://jsonplaceholder.typicode.com/users')
...
...
``````

2. Data Last

`function(fn, data)`

## 額外讀物

1. Auto-Curried: 在 TypeScript 會噴出錯誤, TypeScript and currying

## 參考資源

NEXT: Function Composition

### 2 則留言

0

iT邦新手 5 級 ‧ 2021-09-18 21:41:29

https://ithelp.ithome.com.tw/articles/10261364

0
Ken Chen
iT邦新手 5 級 ‧ 2021-09-18 23:47:09