RSS

Tag Archives: functional-programming

BuzzWord: Functional Programming Short Guides

This is summary of: Anjana Vakil’s video

1. Do everything with functions. Function take input and return output.
Non functional

var name = “Anjana”;
var greeting = “Hi, I’m ”;
console.log(greeting + name);
// Output: “Hi, I’m Anjana”

Functional

function greet(name) {
    return “Hi, I’m ” + name;
}
greet(“Anjana”);
// Output: “Hi, I’m Anjana”

2. Avoid side effects. Function should only process input it is given and return output, everything else is distractions (ie: process global variables, run command not intended to process input, etc). This is pure functions.
Not pure

var name = “Anjana”;
function greet() {
    console.log(“Hi, I’m ” + name);
}

Pure

function greet(name) {
    return “Hi, I’m ” + name;
}

3. Could have higher-order functions. Inputs and outputs can be functions.

function makeAdjectifier(adjective) {
    return function (string) {
        return adjective + “ ” + string;
    };
}

var coolifier = makeAdjectifier(“cool”);
coolifier(“conference”);
// Output: "cool conference"

4. Don’t iterate. Instead of iterate, use functions (map, reduce, filter).
Iterate

var fruits = ["apple", "orange", "banana"];
var goodFruits = [];
for (var i = 0; i  fruit + " great");
// Output: ["apple great", "orange great", "banana great"]

5. Avoid mutability objects. Unintended changes to objects could cause confusion and introduce bugs. Instead, use immutable objects.
Mutable

var rooms = [“H1”, “H2”, “H3”];
rooms[2] = “H4”;
// Output: ["H1", "H2", "H4"]

Immutable objects with function

var rooms = [“H1”, “H2”, “H3”];
var newRooms = rooms.map(function (rm) {
    if (rm == “H3”) {
        return “H4”;
    } else {
        return rm;
    }
});
// Output: rooms => ["H1", "H2", "H3"]
// Output: newRooms => ["H1", "H2", "H4"]

6. Persistent data structure for efficient immutability.
Instead of copying immutable objects which take time and memory (space) for every single copy, use persistent data structure that treat object as nodes and connect them in tree structure, changes of objects will only affect certain nodes, not entire object. This can be achieved with third party framework such as Mori or Immutable.js

Advertisements
 
Leave a comment

Posted by on November 27, 2018 in General

 

Tags: , , , ,

 
%d bloggers like this: