Skip to content

Instantly share code, notes, and snippets.

@njj
Forked from ktilcu/Functional-Programming.md
Last active December 10, 2015 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save njj/d8f4a78154ebd19b5dca to your computer and use it in GitHub Desktop.
Save njj/d8f4a78154ebd19b5dca 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):

Pure vs Impure

// pure functions have no side effects

// the results are predictable and consistent
function square (num) {
    return num * num;
}

// pure functions do not mutate their agruments
function squareAll (nums) {
    return nums.map(square);
}

// impure function that mutates arguments
function badSquareAll (nums) {
    for (var i = 0; i < nums.length; i++) {
        nums[i] = square(nums[i])
    }
}

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