According to Wikipedia, functional programming is the best-kept secret of a number of intellectuals and professionals from varied fields including:
– Mathematicians
– Scientific modelers
– Financial institutions
– Artificial intelligence researchers
– CPU designers
– Graphic designers
– Telecommunications engineers
There are a number of benefits of functional programming on the whole. No wonder experienced web programmers have fallen for it, irrespective of the language they use. The benefits include:
– All pure functions are easier to reason about
– The testing is known to be easier. Additionally, pure functions offer themselves well to practices such as property-based testing
– Programs are invincible
– Easier debugging
-All programs are written at a professional and higher level. Hence, it is easier to understand.
– Significant function signatures
– Easier concurrent/parallel programming
Understanding Chaining
Chaining can be defined as a technique that simplifies code specifically when several methods are applied to any object one after the other.
Comparison of the Two Styles – Imperative and Functional:
When it comes to the functional style, professionals make use of the basic toolbox for the following –
– List operations filter()
– Map()
– Chaining them together
Here, we will take the example of an assortment of tasks wherein a task possesses an id, type code, and description:
//Imperative style
var filteredTasks = [];
var task, i;
for(i=0; i<tasks.length; i++){
task = tasks[i];
if (task.type === “RE”) {
filteredTasks.push({ id : task.id, desc : task.desc });
}
}
//Functional style
function isReviewTask(task){
return task.type === “RE”;
}
function toTaskViewModel(task) {
return { id : task.id, desc : task.desc };
}
var filteredTasks = tasks.filter(isReviewTask)
.map(toTaskViewModel);
Notice the callbacks for filter() and map() as pure functions with intention revealing names.
Part Application or Partial Application
Now it is time to see what can be done to improve readability. Reusing an existing function is another factor to consider. Prior to undertaking this task, it is important to have a new function in the toolbox. Partial or part application is actually a process involving fixing of several arguments to a specific function. It can also be defined as a way to make a shift from generalization to specialization.
It is possible to make use of partial() function from a library such as lodash.js, underscore.js or use of bind(). Partial application can be done by bind() method. But the value assigned to this needs attention.
For instance, if you wish to refactor flowing code to functional style, you need to:
var priorityTasks= [];
var task, i;
for(i=0; i<tasks.length; i++){
task = tasks[i];
if (task.type === “RE” || task.type === “NC”) {
priorityTasks.push(task);
}
}
Here, we will develop a generic function to be utilized for filtering by any task type. The TaskOfType() is seen as the generic function. We will also see how bind() can be used for creating brand new predicates that filter by specific types.
What is a predicate function? It is mainly a function that takes an item as input and then returns true/false based on whether or not the item satisfies a condition.
var isTaskOfType = function(type, task){
return task.type === type;
}
var isNewContent = isTaskOfType.bind(null, “NC”);
var isReview = isTaskOfType.bind(null, “RE”);
Now it is time to use two new predicates. Observe callback of filter carefully. It also has a name voicing its intention. The code might change and even more complicated. However, if you read tasks.filter(isAPriorityTask), you must clearly understand the types of tasks selected.
function isAPriorityTask(task){
return isNewContent(task) || isReview(task);
}
var priorityTasks = tasks.filter(isAPriorityTask);
Reduce
Let’s start off by using a new shopping list example. Here, we require calculating the overall price and the price for fruits. Listed below is the imperative style:
var totalPrice = 0, fruitsPrice = 0, i, line;
for(i=0; i<shopingList.length; i++){
line = shopingList[i];
totalPrice += line.units * line.price;
if (line.type === “fruits”) {
fruitsPrice += line.units * line.price;
}
}
You must use reduce() for calculating the total price while taking functional approach in this situation.
The function reduce() can be used to accrue all values of the collection into single value.
We will create new functions for the needed callbacks and supply them names revealing intention such as: computePrice() and areFruits().
function computePrice(totalPrice, line){
totalPrice += line.units * line.price;
return totalPrice;
}
function areFruits(line){
return line.type === “fruits”;
}
var totalPrice = shopingList.reduce(computePrice, 0);
var fruitsPrice = shopingList.filter(areFruits)
.reduce(computePrice, 0);
To Sum Up
Functional Programming when applied for listing operations will segregate operations in various steps such as:
- Filter
2. Map
3. Reduce
4. Sort
Simultaneously, you must define the newest pure small functions for supporting those operations. The code readability will significantly improve when Functional Programming is accurately combined with the practice of assigning ‘Intention Reveling Names’ to newer functions.
=====================================================================