- Hands-On Functional Programming with TypeScript
- Remo H. Jansen
- 338字
- 2021-07-02 14:03:09
Pure functions
FP introduces a number of concepts and principles that will help us to improve the predictability of our code. In this section, we are going to learn about one of these core concepts—pure functions.
A function can be considered pure when it returns a value that is computed using only the arguments passed to it. Also, a pure function avoids mutating its arguments or any other external variables. As a result, a pure function always returns the same value given the same arguments, independently of when it is invoked.
The isIndexPage function declared in the preceding section is not a pure function because it accesses the pathname variable, which has not been passed as an argument to the function. We can transform the preceding function into a pure function by rewriting it as follows:
function isIndexPage(pathname: string) {
return pathname === "/";
}
Even though this is a basic example, we can easily perceive that the newer version is much easier to predict. Pure functions help us to make our code easier to understand, maintain, and test.
Imagine that we wanted to write a unit test for the impure version of the isIndexPage function. We would encounter some problems when trying to write a test because the function uses the window.location object. We could overcome this issue by using a mocking framework, but it would add a lot of complexity to our unit tests just because we didn't use a pure function.
On the other hand, testing the pure version of the isIndexPage function would be straightforward, as follows:
function shouldReturnTrueWhenPathIsIndex(){
let expected = true;
let result = isIndexPage("/");
if (expected !== result) {
throw new Error('Expected ${expected} to equals ${result}');
}
}
function shouldReturnFalseWhenPathIsNotIndex() {
let expected = false;
let result = isIndexPage("/someotherpage");
if (expected !== result) {
throw new Error('Expected ${expected} to equals ${result}');
}
}
Now that we understand how functional programming helps us to write better code by avoiding state mutations, we can learn about side-effects and referential transparency.
- Redis Applied Design Patterns
- Mastering phpMyAdmin 3.4 for Effective MySQL Management
- 青少年軟件編程基礎與實戰(圖形化編程三級)
- 軟件測試工程師面試秘籍
- Vue.js 3.0源碼解析(微課視頻版)
- Python Geospatial Development(Second Edition)
- Learning Laravel's Eloquent
- MySQL入門很輕松(微課超值版)
- Python Interviews
- 機器學習微積分一本通(Python版)
- Instant jQuery Boilerplate for Plugins
- Struts 2.x權威指南
- Visual Basic程序設計全程指南
- MySQL 8從零開始學(視頻教學版)
- Redmine Cookbook