Make your code easier to read with Functional Programming
Using the filter, map, reduce arrays methods, and more
Pure functions are easier to read and understand. All the function’s dependencies are in its definition and are therefore easier to see. Pure functions also tend to be small and do one thing. They don’t use this
, a constant source of confusion.
Chaining
Chaining is a technique used to simplify code where multiple methods are applied to an object one after another.
Let’s look and compare the two styles: imperative and functional. In the functional style, I use the basic toolbox for list operations filter()
and map()
. Then I chain them together.
I took the case of a collection of tasks. A task has an id
, a description (desc
) a boolean completed
, a type
and an assigned user
object. The user object has a name
property.
//Imperative style
let filteredTasks = [];
for(let i=0; i<tasks.length; i++){
let task = tasks[i];
if (task.type === "RE" && !task.completed) {
filteredTasks.push({ ...task, userName: task.user.name });
}
}//Functional style
function isPriorityTask(task){
return task.type === "RE" && !task.completed;
}function toTaskView(task) {
return…