3分钟搞定纯函数与副作用

2/8/2022 pure functionSide Effect

# 3分钟搞定纯函数与副作用

# what is pure function

相同的输入,相同的输出

Pure function中文又称纯函数

  • 相同的输入,相同的输出
  • 没有第三方库的依赖
  • 不会执行一些和该函数不相关的操作
const customCreeting = (name)=>{
  return `Howdy,${name}`
}
1
2
3
const customCreeting = (name)=>{
  return `Howdy,${name}`
}
const names = ['Barack','Michelle','Malia','Sasha']
const nameGreetings = names.map(customCreeting)
1
2
3
4
5

# what is Side Effect

副作用就是和上面的相反

  • 直接修改外部的状态
  • 直接修改函数的参入

case One

const show ={
  titile : 'One Piece',
  episodes : 920,
  currentEpisode: 899,
  creator:'Eiichiro Oda'
};

//这个函数修改了外部的状态,他不是pure function
const watchNextEpisode=()=>{
  show.currentEpisode = show.currentEpisode + 1;
  return show
}
watchNextEpisode()
1
2
3
4
5
6
7
8
9
10
11
12
13

如何避免副作用呢,就是在当前作用域中创建一个新的状态来进行操作

const show ={
  titile : 'One Piece',
  episodes : 920,
  currentEpisode: 899,
  creator:'Eiichiro Oda'
};

//这个函数修改了外部的状态,他不是pure function
const watchNextEpisode=()=>{
 show={...show}
  show.currentEpisode+=1
  return show
}
watchNextEpisode()
1
2
3
4
5
6
7
8
9
10
11
12
13
14

case two

const comedies = ['The Office','Parks and Rec','Community'];
//改变函数的参数Argument,所以这也不是pure function
const appendShow = (shows,newShow)=>{
  shows.push(newShow);
  return shows;
}
const shows = appendShow(comedies,'30 Rock');
1
2
3
4
5
6
7

如何避免副作用呢,就是在当前作用域中创建一个新的状态来进行操作

const comedies = ['The Office','Parks and Rec','Community'];
//改变函数的参数Argument,所以这也不是pure function
const appendShow = (shows,newShow)=>{
  return [...shows,newShow];
}
const shows = appendShow(comedies,'30 Rock');
1
2
3
4
5
6
Last Updated: 2/8/2022, 8:57:10 PM