javascript函数式编程基础
函数调用 引用 做返回值
function sayHello ( ) {
return "hello world" ;
}
let result= sayHello ( ) ;
let fn= sayHello;
console. log ( fn ( ) ) ;
function ee ( ) {
return function ( ) {
return "hello world" ;
}
}
console. log ( ee ( ) ( ) ) ;
高阶函数,传入参数为函数
let nnjfd= [ 1 , 2 , 3 ] ;
nnjfd= nnjfd. map ( number => number* 2 ) ;
console. log ( nnjfd) ;
箭头函数与函数功能流水线化
input= "JS" ;
trim = str => str. trim ( ) ;
wrapInDiv = str => ` <div> ${ str} </div> ` ;
toLowerCase = str => str. toLowerCase ( ) ;
result= wrapInDiv ( toLowerCase ( trim ( input) ) ) ;
console. log ( result) ;
let fp= require ( "lodash/fp" ) ;
transform= fp. compose ( wrapInDiv, toLowerCase, trim) ;
console. log ( transform ( input) ) ;
transform= fp. pipe ( trim, toLowerCase, wrapInDiv) ;
console. log ( transform ( input) ) ;
柯里化
trim = str => str. trim ( ) ;
wrapInDiv = type => str => ` < ${ type} > ${ str} < ${ type} > ` ;
toLowerCase = str => str. toLowerCase ( ) ;
transform= fp. pipe ( trim, toLowerCase, wrapInDiv ( "div" ) ) ;
console. log ( transform ( input) ) ;
纯函数
function isEligible ( age ) {
return age> minAge;
}
function isEligi ( age, minAge ) {
return age> minAge;
}
更新对象、浅拷贝问题
const person= { name: 'John' , adress: { city: 'san francisco' } } ;
person. name= 'Mary' ;
tempObject= Object. assign ( { } , person, { name: 'Bob' , age: 11 } ) ;
console. log ( tempObject) ;
tempObject= { ... person, a: 'a' , b: 'b' } ;
console. log ( tempObject) ;
tempObject. adress. city= 'ppp' ;
console. log ( person) ;
tempObject= { ... person, adress: { ... person. adress, city: 'p' } } ;
tempObject. adress. city= 'ccc' ;
console. log ( tempObject) ;
console. log ( person) ;
更新数组
numbers= [ 1 , 2 , 3 ] ;
index= numbers. indexOf ( 2 ) ;
added= [
... numbers. slice ( 0 , index) ,
4 ,
... numbers. slice ( index)
] ;
console. log ( added) ;
numbers= numbers. filter ( n => {
return n!== 4 ;
} ) ;
console. log ( numbers) ;
updated= numbers. map ( v => { return v=== 2 ? 20 : v} ) ;
console. log ( updated) ;
不可变对象 immutable与immer库
const { Map } = require ( 'immutable' ) ;
let book= Map ( { title: "Harry Potter" } ) ;
function publish ( book ) {
return book. set ( "isPublished" , true ) ;
}
booked= publish ( book) ;
console. log ( book. toJS ( ) ) ;
console. log ( booked. toJS ( ) ) ;
book= { title: "Harry Potter" } ;
const { produce} = require ( "immer" ) ;
function publish1 ( book ) {
return produce ( book, draftBook => {
draftBook. isPublished= true ;
} ) ;
}
temp= publish1 ( book) ;
console. log ( book) ;
console. log ( temp) ;
temp. title= 'OOPOP' ;
console. log ( book) ;
console. log ( temp) ;