Beyond the Fat Arrow – Functional Programming in Javascript



Beyond the Fat Arrow – Functional Programming in Javascript

0 1


beyond-the-fat-arrow

Beyond the Fat Arrow - Functional Programming in Javascript

On Github benglass / beyond-the-fat-arrow

Beyond the Fat Arrow

Functional Programming in Javascript

Ben Glassman

Email @ ben@vtdesignworks.com Director of Development @ Vermont Design Works Adjunct Professor @ Champlain College

Interested in writing apps in React with ES6?We are hiring front-end and back-end devs!

Why Functional Programming?

“Write programs functions that do one thing and do it well. Write programs functions to work together.”

– Doug McIlroy, inventor of UNIX pipes

Why Functional Programming?

  • Smaller units of code are....
  • ...easier to understand
  • ...easier to test
  • ...easier to re-use
  • ...easier to refactor

Great,but How ?

To achieve our goal, we need to do 2 things:

Break our program into small units Combine these units into larger ones

This talk looks at techniques fordecomposition and composition.

How do we make this function more re-usable?

var characters = [
    {id: 1, name: 'Arrow'},
    {id: 2, name: 'Oblio'},
];
var characterIds = characters.map(function(character) {
    return character.id;
});

Step 1: Parameterize the Property Name

function get(propName, object) {
    return object[propName];
}
var characters = [
    {id: 1, name: 'Arrow'},
    {id: 2, name: 'Oblio'},
];
var characterIds = characters.map(get); // ?!@#

That was pointless!

Step 2: Make it Fit the Desired Interface

function get(propName, object) {
    return object[propName];
}
function getId(object) {
    return get('id', object);
}
var characters = [
    {id: 1, name: 'Arrow'},
    {id: 2, name: 'Oblio'},
];
var characterIds = characters.map(getId);

Manual and quite ugly. Wouldn't it be nice if we had a way to easilytransform get into getId?

First-class Functions

Functions as Values

A programming language has first-class functions if...

  • Functions can be passed as arguments
  • Functions can return functions as their return values
  • Functions can be assigned to variables

First-class Function Examples

  • Array.map/sort/filter
  • Promise.then
  • addEventListener

Step 3: Make get return a function

function get(propName) {
    return function(object) {
        return object[propName];
    };
}
var characters = [
    {id: 1, name: 'Arrow'},
    {id: 2, name: 'Oblio'},
];
var characterIds = characters.map(get('id'));

Better, but writing nested functions is tedious...

What is the Relationship between these 2 functions?

function getA(propName, object) {
    return object[propName];
}

function getB(propName) {
    return function(object) {
        return object[propName];
    };
}

getB takes getA's first argument (propName) and returns a function that takes getA's second argument (object) and returns getA(propName, object)

Can we write a function to turn getA into getB?

function getA(propName, object) {
    return object[propName];
}

function ???(getA, arg1) {
    return function(arg2) {
        return getA(arg1, arg2);
    };
}

What do we call it?

Left Apply

Partial Application: Application is calling a function with arguments, partial refers to the fact that we dont have all the arguments yet

function get(propName, object) {
    return object[propName];
}

function leftApply(fn, arg1) {
    return function(arg2) {
        return fn(arg1, arg2);
    };
}

const getId = leftApply(get, 'id');

characters.map(getId);

There is Another Name...

Javascript supports partial application natively.

function get(propName, object) {
    return object[propName];
}

const getId = get.bind(null, 'id');

characters.map(getId);

Partial Application

Allows us to write our function normally (immediately evaluating) and have the returning of nested functions handled automatically.

leftApply (and its corollary rightApply) helps us to decompose a function into a simpler function by supplying one of its arguments up front.

Higher Order Functions

Left apply is an example of a higher order function.

Higher Order functions are functions which accept a function as an argument OR return a function as a value.

We can write higher order functions to transform other functions.

Which is more Readable?

characters.map(leftApply(get, 'id'));

characters.map(get('id'));

Currying

A technique which turns a function of arity X of into a nested series of X unary (single argument) functions.

var character = { id: 5, name: 'Rock Man' };

get('name', character); // 'Rock Man'

var curriedGet = curry(get);

curriedGet('name')(character);  // 'Rock Man'

var getName = curriedGet('name');
getName(character);  // 'Rock Man'

Anybody know why its called currying?

Our get function from earlier was a curried function:

function get(propName, obj) { 
    return obj[propName];
}

function curriedGet(propName) { 
    return function(obj) { 
        return obj[propName];
     }; 
}

Curried functions accept 1 argument at a time. You call the returned function with the next argument, etc. When the final argument is supplied, the function is called and the value is returned.

Final Get Function

const get = curry(function get(propName, obj) {
    return obj[propName];
});

var characters = [
    {id: 3, name: 'The Count'},
    {id: 4, name: 'The Pointed Man'},
];

var characterIds = characters.map(get('id'));

Take it Further: Curried Map

const get = curry(function get(propName, obj) {
    return obj[propName];
});

const map = curry(function map(fn, mappable) {
    return mappable.map(fn);
});

var characters = [
    {id: 3, name: 'The Count'},
    {id: 4, name: 'The Pointed Man'},
];

const getIds = map(get('id'));

var characterIds = getIds(characters);

Functions as Values

Its not just passing functions as args or storing them in vars.

We can use functions that create new functions by breaking down existing functions, like leftApply or curry.

We can also use functions that create new functions by combining existing functions.

This makes sense when we think of functions as values in the same way as we think of numbers or strings as values. We can perform operations on them to combine or transform them and create new values.

What Makes the *NIX command line so powerful?

What Makes the *NIX command line so powerful?

# Edit the result of a command in vim
du -h /var | sort -hr | head -10 | vim -

# Create a file and edit it
touch myfile.txt && vim $_

# Open modified files in vim
vim $(git status -uno --porcelain | awk '{ print $2 }')

What Makes the *NIX command line so powerful?

  • Uniform Interface: Take a single input and return a single output
  • Composable: Pipes make it easy to chain commands together by passing the output of one into the input of the next.
  • Lazy: We can provide some args/options up front to the each command without executing it until the input is provided

Adding logging to a function:Manual Implementation

function logBeforeAdd(x, y) {
    console.log(x, y);
    return add(x, y);
}

Adding logging to a function:Higher Order Function

function logBefore(fn) {
    return function() {
        console.log(arguments);
        return fn.apply(this, arguments);
    };
}

What is the behavior of the logBefore fn?

Adding logging to a function:Decorator

A decorator is a higher order function that takes one function as its argument and returns a new function that is closely related to the original function

function logBefore(fn) {
    return function() {
        console.log(arguments);
        return fn.apply(this, arguments);
    }
}

Side-effect made explicit & isolated

Retry Decorator

function retry(fn, maxTries) {
    return function() {
        var error;
        while (maxTries--) {
            try {
                return fn.apply(this, arguments);
            } catch (err) {
              error = err;
            }
        }
        throw error;
    };
}

const resilientLoadUsers = retry(loadUsers, 3);
const users = resilientLoadUsers();

Memoize (Caching) Decorator

function memoize(fn) {
    var memos = {};
    return function() {
        var key = JSON.stringify(Array.from(arguments));
        if (!memos.hasOwnProperty(key)) { 
            console.log('cache miss on: '+key);
            memos[key] = fn.apply(this, arguments);
        } else {
            console.log('cache hit on: '+key);
        }
        return memos[key];
    };
};
const memoizedAdd = memoize(add);
memoizedAdd(1, 2); // cache miss on: [1,2]
memoizedAdd(1, 2); // cache hit on: [1,2]

More Decorators

  • flip: Reverse the function's argument order
  • unary: Ignore all but first argument
  • map: Calls the function on each element of an array
  • maybe: Return null if any of its arguments are falsy.
  • fluent, binary, comparator, cond, complement, and many more

Chaining Functions w/ Pipe

Decouple complex multi-step operation into small, manageable chunks.

function uppercase(string) {
    return string.toUpperCase();
}
function pipe() {
    const functionQueue = Array.from(arguments);
    return function() {
        const initialValue = arguments[0];
        return functionQueue.reduce(
            (returnValue, fn) => return fn(returnValue),
            initialValue
        );
    }
}

const getUppercaseName = pipe(get('name'), uppercase);
const uppercaseNames = characters.map(getUppercaseName);

compose = flip(pipe);

Generalizing logBefore

const log = console.log.bind(console);
function logBefore(fn) {
    return function() {
        log(arguments);
        return fn.apply(this, arguments);
    };
}

How do we make this more re-usable?

Step 1: Parameterize the beforeFn

const log = console.log.bind(console);
function before(beforeFn, mainFn) {
    return function() {
        beforeFn.apply(this, arguments);
        return mainFn.apply(this, arguments);
    };
}
const logBeforeAdd = before(log, add);
const logBeforeClick = before(log, handleClick);

Can we make this even more re-usable?

Step 2: Curried Before

const log = console.log.bind(console);
const before = curry(function before(beforeFn, mainFn) {
    return function() {
        beforeFn.apply(this, arguments);
        return fn.apply(this, arguments);
    };
});
const logBefore = before(log);
const logBeforeAdd = logBefore(add);
const logBeforeClick = logBefore(handleClick);

before is a Combinator

Combinators are functions that create more complex values by combining the provided arguments.

We're used to thinking about combining values likes numbers (addition), arrays (concat), or objects (Object.assign), but less so with functions.

before(beforeFn, mainFn) is a function combinator, a higher order function that create more complex functions by combining other functions.

Around Example

Return the result of calling aroundFn with mainFn and all other arguments. You can implement many decorators using around.

function around(wrapperFn, mainFn) {
  return function() {
    var args = [mainFn].concat(Array.from(arguments));
    return wrapperFn.apply(this, args);
  };
}

const addAndDouble = around(function(mainFn, ...args) {
  return mainFn(...args) * 2;
}, add);

addAndDouble(1, 2); // 6

Provided & Excepting Combinators

  • provided(predicateFn, mainFn) predicateFn serves as a guard clause where returning falsy prevents mainFn from being called.
  • excepting(predicateFn, mainFn) Inverse of provided, returning truthy from predicateFn will result in an early return.

Pre/Post Condition Combinators

  • precondition(conditionFn, exception, mainFn) Call conditionFn before mainFn and throw exception if it returns false.
  • postcondition(conditionFn, exception, mainFn) Call conditionFn after mainFn and throw exception if it returns false.

Uses

  • Separator of Concerns: Separate cross-cutting concerns like caching, logging, authentication, authorization, etc. from application code
  • Lazy Loading: before/around can be used to lazily initialize data when it is asked for.
  • Enforcing Invariants: Pre/post condition combinators can be used to share code that enforces invariants
  • Side Effects: before/after can be used to attach side-effects to otherwise pure functions
  • Guard Clauses: Useful to create early returns from functions

Summary

  • Smaller units of code make programs easier to understand
  • Functional concepts apply to any language with first-class functions
  • Declarative approach makes code more readable
  • Expands vocabulary for describing & creating relationships between functions

Beyond the Fat Arrow

Thank You!Matt, Everybody who showed up tonight

Ben Glassman

Email @ ben@vtdesignworks.com Director of Development @ Vermont Design Works Adjunct Professor @ Champlain College

Interested in writing apps in React with ES6?We are hiring front-end and back-end devs!

Resources

Beyond the Fat Arrow Functional Programming in Javascript Ben Glassman Email @ ben@vtdesignworks.com Director of Development @ Vermont Design Works Adjunct Professor @ Champlain College Interested in writing apps in React with ES6? We are hiring front-end and back-end devs!