LoginSignup
5
0

More than 3 years have passed since last update.

【社内LT用資料転載】純粋関数

Last updated at Posted at 2019-09-13
1 / 10

はじめに

社内LTシリーズ第三弾です。
LTは2019年9月13日に行い資料はその時点での情報となります。
今回は純粋関数(pure function)についてです。
5分くらいの軽い発表になります。

第一弾: PHP7移行概要
第二弾: そうだゴルフをしよう⛳


純粋関数とは

以下の条件を満たすものを純粋関数という。
- 参照透過性
- 副作用がない


参照透過性

同じ引数に対して常に同じ値を返す。


参照透過でない例


let PI = 3.14;
const calculateArea = radius => radius * radius * PI;

calculateArea(10); // returns 314.0

参照透過である例

let PI = 3.14;
const calculateArea = (radius, pi) => radius * radius * pi;

calculateArea(10, PI); // returns 314.0

副作用がない

関数外部の変数を書き換えない


副作用がある例

let counter = 1;

function increaseCounter(value) {
 counter = value + 1;
}

increaseCounter(counter);
console.log(counter); // 2

副作用がない例

let counter = 1;

const increaseCounter = value => value + 1;

increaseCounter(counter); // 2
console.log(counter); // 1

メリット

  • テストが容易
  • ソースを読みやすくなる
5
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0