Frochu
Published in

Frochu

純粹的好,Pure Function 知道

Pure Function 介紹,以及在React、Redux開發中的角色

Eiskristalle

Pure Function 是什麼

// impure function
let intercept = 2
function math(x) {
return (3 * x) + intercept
}
const result = math(4) // 14// pure function
function math(itr) {
return function(x) {
return (3 * x) + itr
}
}
const result = math(2)(4) // 14

Pure Function 對開發有什麼益處

有利重構(Refactor)

方便測試

易與其他函數組合(Compose)

function someMath(n) {
return 6 + (5 * n)
}
function g(n) {
return n * 5
}
function f(n) {
return n + 6
}
const z = someMath(x)// 等同於
const y = g(x)
const z = f(y)
// 能利用組合率
z = f(g(x))
iex> "Hello World"
|> String.upcase
|> String.split
|> Enum.map(fn x -> x <> "oo" end)
["HELLOoo", "WORLDoo"]

並行運作

利於建快取(Cache)

function cacheMath(n){
const cache = {}
return function(){
if (n in cache) return cache[n]
const result = doSomeComplexMathMethod(n)
cache[n] = result
return result
}
}

專注於特定情境(Context)

與React、Redux 共舞

React Component

Redux Reducer

const CounterReducer = (state, action) => {
switch (action.type) {
case INCREASE:
return state + 1
case DECREASE:
return state - 1
default:
return state
}
}

setState(object) -> setState(function)

Selector

總結

--

--

Frochu — Frontend Ochu ,程式碼的黑手,親手實作的前端知識推動者

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Wendell Liu

A Frontend Developer in honestbee. Fullstack Engineer and Functional Programming enthusiast. Love the quote "Ideas are bulletproof."