A Pen by Danica Shen on CodePen.
Created
January 10, 2017 09:52
-
-
Save DDDDDanica/999e8d7cc6ead423b1a9eb9d15870c3d to your computer and use it in GitHub Desktop.
1.10 Pure functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Definition of pure fuctions | |
// 1. Given the same input, will always return the same output. | |
// 2. Produces no side effects. | |
// 3. Relies on no external state. | |
//pure functions | |
let array1 = [1,2,3,4,5]; | |
// pure: not mess up with original data | |
array1.slice(0,3); | |
//=> [1,2,3] | |
array1.slice(0,3); | |
//=> [1,2,3] | |
array1.slice(0,3); | |
//=> [1,2,3] | |
// not pure: change the value of original data | |
array1.splice(0,3); | |
//=> [1,2,3] | |
array1.splice(0,3); | |
//=> [4,5] | |
array1.splice(0,3); | |
//=> [] | |
// Not pure | |
let minimum = 21; | |
let checkAge = (age)=> { | |
return age >= minimum; | |
}; | |
// The result depends on system state, it adds in external variable and increases cognitive load | |
// pure | |
let checkAge2 = (age)=> { | |
let minimum = 21; //minimum is not an immutable variable | |
return age >= minimum; | |
}; | |
//reason: | |
//1. Cacheable纯函数总能够根据输入来做缓存 | |
//2. 可移植性/自文档化(Portable / Self-Documenting) | |
//纯函数是完全自给自足的,它需要的所有东西都能轻易获得 | |
//3. 可测试性(Testable) | |
//4. 合理性(Reasonable)引用透明性(referential transparency) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment