Skip to content

Instantly share code, notes, and snippets.

@ktilcu
Last active December 10, 2015 16:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ktilcu/bfc946f989007e4d6def to your computer and use it in GitHub Desktop.
Save ktilcu/bfc946f989007e4d6def to your computer and use it in GitHub Desktop.
Functional programming is actually good for javascript developers

Rules

  • no side effects (function can't rely on anything not provided to it)
  • inputs and outputs

In Practice

  • Nested functions are always an indication of complexity

Creates Functions that are

  • Easy to read
  • Easy to reuse
  • Easy to test
  • Easy to change

Examples (all pulled from code I reviewed at PaperG just simplified and anonymized):

Reusability

// add foo to bar
var foo = 1;
var bar = 2;

function add (number_1) {
    return number_1 + bar;
}
// add foo to bar
var foo = 1;
var bar = 2;

function add (number_1, number_2) {
    return number_1 + number_2;
}

Testability

var foo = [1, 2, 3, 4, 5];
_.each(function (num) {
    num++;
});
var foo = [1, 2, 3, 4, 5];

function add_one (num) {
    return num + 1;
}

var bar = foo.map(add_one);
$scope.toggleView = function($event, grid) {
    if (grid) {
        stopCropping();
    }
    setGrid(grid);
    $event.stopPropagation();
};
function toggleView ($event, grid) {
    // not entirely sure how this code works but....
    var newView = _.cloneDeep(oldview);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment