- 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.
- 數據庫系統原理及MySQL應用教程(第2版)
- GraphQL學習指南
- 算法精粹:經典計算機科學問題的Python實現
- 新手學Visual C# 2008程序設計
- 基于差分進化的優化方法及應用
- 你必須知道的204個Visual C++開發問題
- ASP.NET程序開發范例寶典
- Learning YARN
- TypeScript圖形渲染實戰:2D架構設計與實現
- 高效使用Greenplum:入門、進階與數據中臺
- Drupal 8 Development Cookbook(Second Edition)
- Koa與Node.js開發實戰
- Learning iOS Penetration Testing
- Learning Dynamics NAV Patterns
- KnockoutJS Blueprints