未加星标

Concepts of Functional Programming in Javascript

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二05 | 时间 2019 | 作者 红领巾 ] 0人收藏点击收藏

Concepts of Functional Programming in Javascript

After a long time learning and working with object-oriented programming, I took a step back to think about system complexity.

“Complexity is anything that makes software hard to understand or to modify." ― John Outerhout

Doing some research, I found functional programming concepts like immutability and pure function. Those concepts are big advantages to build side-effect-free functions, so it is easier to maintain systems ― with some other benefits .

In this post, I will tell you more about functional programming, and some important concepts, with a lot of code examples. In javascript!

What is functional programming? Functional programming is a programming paradigm ― a style of building the structure and elements of computer programs ― that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data ― Wikipedia Pure functions
Concepts of Functional Programming in Javascript

The first fundamental concept we learn when we want to understand functional programming is pure functions . But what does that really mean? What makes a function pure?

So how do we know if a function is pure or not? Here is a very strict definition of purity:

It returns the same result if given the same arguments (it is also referred as deterministic )

It does not cause any observable side effects

It returns the same result if given the same arguments

Imagine we want to implement a function that calculates the area of a circle. An impure function would receive radius as the parameter, and then calculate radius * radius * PI :

const PI = 3.14; function calculateArea(radius) { return radius * radius * PI; } calculateArea(10); // returns 314.0

Why is this an impure function? Simply because it uses a global object that was not passed as a parameter to the function.

Now imagine some mathematicians argue that the PI value is actually 42 and change the value of the global object.

Our impure function will now result in 10 * 10 * 42 = 4200 . For the same parameter ( radius = 10 ), we have a different result. Let's fix it!

const PI = 3.14; function calculateArea(radius, pi) { return radius * radius * pi; } calculateArea(10, PI); // returns 314.0

TA-DA :tada:! Now we’ll always pass the PI value as a parameter to the function. So now we are just accessing parameters passed to the function. No external object .

For the parameters radius = 10 & PI = 3.14 , we will always have the same the result: 314.0

For the parameters radius = 10 & PI = 42 , we will always have the same the result: 4200

Reading Files

If our function reads external files, it’s not a pure function ― the file’s contents can change.

function charactersCounter(text) { return `Character count: ${text.length}`; } function analyzeFile(filename) { let fileContent = open(filename); return charactersCounter(fileContent); } Random number generation

Any function that relies on a random number generator cannot be pure.

function yearEndEvaluation() { if (Math.random() > 0.5) { return "You get a raise!"; } else { return "Better luck next year!"; } } It does not cause any observable sideeffects

Examples of observable side effects include modifying a global object or a parameter passed by reference.

Now we want to implement a function to receive an integer value and return the value increased by 1.

let counter = 1; function increaseCounter(value) { counter = value + 1; } increaseCounter(counter); console.log(counter); // 2

We have the counter value. Our impure function receives that value and re-assigns the counter with the value increased by 1.

Observation: mutability is discouraged in functional programming.

We are modifying the global object. But how would we make it pure ? Just return the value increased by 1. Simple as that.

let counter = 1; function increaseCounter(value) { return value + 1; } increaseCounter(counter); // 2 console.log(counter); // 1

See that our pure function increaseCounter returns 2, but the counter value is still the same. The function returns the incremented value without altering the value of the variable.

If we follow these two simple rules, it gets easier to understand our programs. Now every function is isolated and unable to impact other parts of our system.

Pure functions are stable, consistent, and predictable. Given the same parameters, pure functions will always return the same result. We don’t need to think of situations when the same parameter has different results ― because it will never happen.

Pure functions benefits

The code’s definitely easier to test. We don’t need to mock anything. So we can unit test pure functions with different contexts:

Given a parameter A → expect the function to return value B

Given a parameter C → expect the function to return value D

A simple example would be a function to receive a collection of numbers and expect it to increment each element of this collection.

let list = [1, 2, 3, 4, 5]; function incrementNumbers(list) { return list.map(number => number + 1); }

We receive the numbers array, use map incrementing each number, and return a new list of incremented numbers.

incrementNumbers(list); // [2, 3, 4, 5, 6] For the input [1, 2, 3, 4, 5] , the expected output would be [2, 3, 4, 5, 6] . Immutability Unchanging over time or unable to bechanged.
Concepts of Functional Programming in Javascript
after it’s created.If you want to change an immutable object, you can’t. Instead,you create a new object with the new value.

In Javascript we commonly use the for loop. This next for statement has some mutable variables.

var values = [1, 2, 3, 4, 5]; var sumOfValues = 0; for (var i = 0; i < values.length; i++) { sumOfValues += values[i]; } sumOfValues // 15

For each iteration, we are changing the i and the sumOfValue state . But how do we handle mutability in iteration? Recursion!

let list = [1, 2, 3, 4, 5]; let accumulator = 0; function sum(list, accumulator) { if (list.length == 0) { return accumulator; } return sum(list.slice(1), accumulator + list[0]); } sum(list, accumulator); // 15 list; // [1, 2, 3, 4, 5] accumulator; // 0 So here we have the sum function that receives a vector of numerical values. The function calls itself until we get the list empty (

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

代码区博客精选文章
分页:12
转载请注明
本文标题:Concepts of Functional Programming in Javascript
本站链接:https://www.codesec.net/view/627807.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(76)