Functional Programming in JavaScript

Why we need to use functional programming.
Write your code with Less bugs in less time.
Your code will have less bugs because your code will be easier to reason about and you will be able to write it in less time because you will be able to reuse more of your code.

  • Purity & Immutability
    • When Functional Programmers talk of Purity, they are referring to Pure Functions.
    • Pure Functions will always produce the same output given the same inputs.
    • All useful Pure Functions must return something.
    • Pure functions have no side effects.

Higher-order Function

  • Function are values.
    Create an anonymous function and assign it to a variable. Just like any other value.
function triple(x){
  return x * 3
}
const triple = function(x){
  return x * 3
}

A function is a value , so it can be passed to another function (higher-order function).
what are higher-order function good for

  • Composition
    Composition the fact that we can take on function and put it into another function, allows us to compose a lot of small function into bigger functions.
const animals = [
  { name: 'Fluffykins',  species: 'rabbit'},
  { name: 'Caro',  species: 'dog'},
  { name: 'Hamilton',  species: 'dog'},
  { name: 'Harold',  species: 'fish'},
  { name: 'Ursual',  species: 'cat'},
  { name: 'Jimmy',  species: 'fish'},
]

const dogs = []
for (let i = 0; i < animals.length; i++){
  if(animals[i].species === 'dog'){
    dogs.push(animals[i]) 
  }
}

const dogs2 = animals.filter(animal=> animal.species === 'dog') 

// notice here the eample that uses filter is alot less code than the for loop
// less code means less bug and means less time.

const isDog = animal => animal.species === 'dog'
const dogs3 = animals.filter(isDog) 

const isCat = animal => animal.species === 'cat'
const cats = animals.filter(isCat) 


// we want to get an array of all the names of the animals
const animals = [
  { name: 'Fluffykins',  species: 'rabbit'},
  { name: 'Caro',  species: 'dog'},
  { name: 'Hamilton',  species: 'dog'},
  { name: 'Harold',  species: 'fish'},
  { name: 'Ursual',  species: 'cat'},
  { name: 'Jimmy',  species: 'fish'},
]

const names = []
for (let i = 0; i< animals.length; i++){
  names.push(animals[i].name)
}

const names2 = animals.map(animal => animal.name)

//- Reuce
// There are lots of arary transofrmations on the arrary object.  But what to do if you can  't find one that fits. That is where reduce comes in.
// summarize all the amounts
const orders = [
  {amount: 250},
  {amount: 400},
  {amount: 100},
  {amount: 325}
]

let totalAmount = 0
for (var i = 0; i< orders.length; i++){
  totalAmount += orders[i].amount
}

console.log(totalAmount)

const totalAmount2 = orders.reduce((sum, order)=>sum + order.amount,0)
console.log(totalAmount2)

// parser the unstructured data
const doc = `
mark johansson  waffle iron  80  2
mark johansson  blender  200  1
mark johansson  knife  10  4
Nikita Smith  waffle iron  80  1
Nikita Smith  knife  10  2
Nikita Smith  pot  20  3
`

// const output = {
//   'mark johansson': [
//     {name: 'waffle iron', price: '80', quantity: '2'},
//     {name: 'blender', price: '200', quantity: '1'},
//     {name: 'knife', price: '10', quantity: '4'},
//   ],
//   'Nikita Smith': [
//     {name: 'waffle iron', price: '80', quantity: '1'},
//     {name: 'blender', price: '200', quantity: '2'},
//     {name: 'pot', price: '20', quantity: '3'},
//   ] 
// }

const output = doc
.trim()
.split('\n')
.map(item=>item.split('  '))
.reduce((pre, cur)=>{
  const customerName = cur[0];
  const orderItem = {name:cur[1], price: cur[2], quantity: cur[3]}
  return {
    ...pre,
    [customerName]:pre[customerName] ? [...pre[customerName], orderItem] : [orderItem]
  }
}, {})

console.log(output)
// Good functional code is make up of small functions that do one thing and you just find them all together.

Recursion

Recursion is when a function calls itself until it doesn't.

// countDownFrom(10) 
// show count down 10 9 ... 1

const countDownFrom = (num) => {
  console.log(num--)
  num >=0 && countDownFrom(num)
}

countDownFrom(10)


const categories = [
  { id: 'animals', parent: null },
  { id: 'mammals', parent: 'animals' },
  { id: 'cats', parent: 'mammals' },
  { id: 'dogs', parent: 'mammals' },
  { id: 'chihuahua', parent: 'dogs' },
  { id: 'labrador', parent: 'dogs' },
  { id: 'persian', parent: 'cats' },
  { id: 'siamese', parent: 'cats' },
]

// const output = {
//   animals:{
//     mammals:{
//       dogs:{
//         chihuahua:null,
//         labrador: null
//       },
//       cats:{
//         persian: null,
//         siamese: null
//       }
//     }
//   }
// } 


const makeTree = (categories, parent) => {
  const node = {}
  categories
    .filter(c => c.parent === parent)
    .forEach(c => node[c.id] = makeTree(categories, c.id))
  return node
}

console.log(JSON.stringify(
  makeTree(categories, null)
  , null, 2))

Functor

Functor is the object that has map method.
For example,in javaScript array is the functor.


image.png

Monad

Monad is a more powerful functor, that also implements flatmap.
The flatMap() method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a map() followed by a flat() of depth 1, but slightly more efficient than calling those two methods separately.

const arr = [1, 2, 3, 4];
arr.flatMap(x => [x, x * 2]);
// [1, 2, 2, 4, 3, 6, 4, 8]

let arr1 = ["it's Sunny in", "", "California"];
arr1.map(x => x.split(" "));
// [["it's","Sunny","in"],[""],["California"]]

arr1.flatMap(x => x.split(" "));
// ["it's","Sunny","in", "", "California"]

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末稳衬,一起剝皮案震驚了整個(gè)濱河市该镣,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖褐奥,帶你破解...
    沈念sama閱讀 216,496評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件仰挣,死亡現(xiàn)場(chǎng)離奇詭異冒冬,居然都是意外死亡伸蚯,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門简烤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)剂邮,“玉大人,你說(shuō)我怎么就攤上這事横侦』用龋” “怎么了?”我有些...
    開封第一講書人閱讀 162,632評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵枉侧,是天一觀的道長(zhǎng)引瀑。 經(jīng)常有香客問我,道長(zhǎng)榨馁,這世上最難降的妖魔是什么憨栽? 我笑而不...
    開封第一講書人閱讀 58,180評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮翼虫,結(jié)果婚禮上屑柔,老公的妹妹穿的比我還像新娘。我一直安慰自己珍剑,他們只是感情好掸宛,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,198評(píng)論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著招拙,像睡著了一般唧瘾。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上别凤,一...
    開封第一講書人閱讀 51,165評(píng)論 1 299
  • 那天劈愚,我揣著相機(jī)與錄音,去河邊找鬼闻妓。 笑死菌羽,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的由缆。 我是一名探鬼主播注祖,決...
    沈念sama閱讀 40,052評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼均唉!你這毒婦竟也來(lái)了是晨?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,910評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤舔箭,失蹤者是張志新(化名)和其女友劉穎罩缴,沒想到半個(gè)月后蚊逢,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,324評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡箫章,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,542評(píng)論 2 332
  • 正文 我和宋清朗相戀三年烙荷,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片檬寂。...
    茶點(diǎn)故事閱讀 39,711評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡终抽,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出桶至,到底是詐尸還是另有隱情昼伴,我是刑警寧澤,帶...
    沈念sama閱讀 35,424評(píng)論 5 343
  • 正文 年R本政府宣布镣屹,位于F島的核電站圃郊,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏女蜈。R本人自食惡果不足惜描沟,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,017評(píng)論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望鞭光。 院中可真熱鬧,春花似錦泞遗、人聲如沸惰许。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)汹买。三九已至,卻和暖如春聊倔,著一層夾襖步出監(jiān)牢的瞬間晦毙,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工耙蔑, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留见妒,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,722評(píng)論 2 368
  • 正文 我出身青樓甸陌,卻偏偏與公主長(zhǎng)得像须揣,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子钱豁,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,611評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容