en
Books
Dan Mantyla

Functional Programming in JavaScript

This is a fast-paced guide that will help you to write real-world applications by utilizing a wide range of functional techniques and styles.
The book first explores the core concepts of functional programming common to all functional languages, with examples of their use in JavaScript. It's followed by a comprehensive roundup of functional programming libraries for JavaScript that minimizes the burden of digging deep into JavaScript to expose a set of tools that makes functional programming not just possible but highly convenient. The book then rounds off with an overview of methods to effectively use and mix functional programming with object-oriented programming.
163 бумажные страницы
Год выхода издания
2015
Издательство
Packt Publishing
Уже прочитали? Что скажете?
👍👎

Впечатления

  • Zelimirделится впечатлением2 года назад
    👍Worth reading

Цитаты

  • .цитирует6 лет назад
    Lazy evaluation, also known as non-strict evaluation, call-by-need and deffered execution, is an evaluation strategy that waits until the value is needed to compute the result of a function and is particularly useful for functional programming. It's clear that a line of code that states x = func() is calling for x to be assigned to the returned value by func(). But what x actually equates to does not matter until it is needed. Waiting to call func() until x is needed is known as lazy evaluation.
  • .цитирует6 лет назад
    Pure functions

    Pure functions return a value computed using only the inputs passed to it. Outside variables and global states may not be used and there may be no side effects. In other words, it must not mutate the variables passed to it for input. Therefore, pure functions are only used for their returned value.
    A simple example of this is a math function. The Math.sqrt(4) function will always return 2, does not use any hidden information such as settings or state, and will never inflict any side effects.
    Pure functions are the true interpretation of the mathematical term for 'function', a relation between inputs and an output. They are simple to think about and are readily re-usable. Because they are totally independent, pure functions are more capable of being used again and again.
    To illustrate this, compare the following non-pure function to the pure one.
    // function that prints a message to the center of the screen
    var printCenter = function(str) {
    var elem = document.createElement("div");
    elem.textContent = str;
    elem.style.position = 'absolute';
    elem.style.top = window.innerHeight/2+"px";
    elem.style.left = window.innerWidth/2+"px";
    document.body.appendChild(elem);
    };
    printCenter('hello world');
    // pure function that accomplishes the same thing
    var printSomewhere = function(str, height, width) {
    var elem = document.createElement("div");
    elem.textContent = str;
    elem.style.position = 'absolute';
    elem.style.top = height;
    elem.style.left = width;
    return elem;
    };
    document.body.appendChild(printSomewhere('hello world', window.innerHeight/2)+10+"px",window.innerWidth/2)+10+"px")
    );
    While the non-pure function relies on the state of the window object to compute the height and width, the pure, self-sufficient function instead asks that those values be passed in. What this actually does is allow the message to be printed anywhere, and this makes the function much more versatile.
    And while the non-pure function may seem like the easier option because it performs the appending itself instead of returning an element, the pure function printSomewhere() and its returned value play better with other functional programming design techniques.
    var messages = ['Hi', 'Hello', 'Sup', 'Hey', 'Hola'];
    messages.map(function(s,i){
    return printSomewhere(s, 100*i*10, 100*i*10);
    }).forEach(function(element) {
    document.body.appendChild(element);
    });
  • .цитирует6 лет назад
    Anonymous functions

    Another benefit of treating functions as first-class objects is the advent of anonymous functions.
    As the name might imply, anonymous functions are functions without names. But they are more than that. What they allow is the ability to define ad-hoc logic, on-the-spot and as needed. Usually, it's for the benefit of convenience; if the function is only referred to once, then a variable name doesn't need to be wasted on it.
    Some examples of anonymous functions are as follows:
    // The standard way to write anonymous functions
    function(){return "hello world"};
    // Anonymous function assigned to variable
    var anon = function(x,y){return x+y};
    // Anonymous function used in place of a named callback function,
    // this is one of the more common uses of anonymous functions.
    setInterval(function(){console.log(new Date().getTime())}, 1000);
    // Output: 1413249010672, 1413249010673, 1413249010674, ...
    // Without wrapping it in an anonymous function, it immediately // execute once and then return undefined as the callback:
    setInterval(console.log(new Date().getTime()), 1000)
    // Output: 1413249010671
    A more involved example of anonymous functions used within higher-order functions:
    function powersOf(x) {
    return function(y) {
    // this is an anonymous function!
    return Math.pow(x,y);
    };
    }
    powerOfTwo = powersOf(2);
    console.log(powerOfTwo(1)); // 2
    console.log(powerOfTwo(2)); // 4
    console.log(powerOfTwo(3)); // 8
    powerOfThree = powersOf(3);
    console.log(powerOfThree(3)); // 9
    console.log(powerOfThree(10)); // 59049
    The function that is returned doesn't need to be named; it can't be used anywhere outside the powersOf() function, and so it is an anonymous function.
    Remember our accumulator function? It can be re-written using anonymous functions.
    var
    obj1 = {value: 1},
    obj2 = {value: 2},
    obj3 = {value: 3};
    var values = (function() {
    // anonymous function
    var values = [];
    return function(obj) {
    // another anonymous function!
    if (obj) {
    values.push(obj.value);
    return values;
    }
    else {
    return values;
    }
    }
    })(); // make it self-executing
    console.log(values(obj1)); // Returns: [obj.value]
    console.log(values(obj2)); // Returns: [obj.value, obj2.value]
    Right on! A pure, high-order, anonymous function. How did we ever get so lucky? Actually, it's more than that. It's also self-executing as indicated by the structure, (function(){...})();. The pair of parentheses following the anonymous function causes the function to be called right away. In the above example, the values instance is assigned to the output of the self-executing function call.
    Note
    Anonymous functions are more than just syntactical sugar. They are the embodiment of Lambda calculus. Stay with me on this… Lambda calculus was invented long before computers or computer languages. It was just a mathematical notion for reasoning about functions. Remarkably, it was discovered that—despite the fact that it only defines three kinds of expressions: variable references, function calls, and anonymous functions—it was Turing-complete. Today, Lambda calculus lies at the core of all functional languages if you know how to find it, including JavaScript.
    For this reason, anonymous functions are often called lambda expressions.
    One drawback to anonymous functions remains. They're difficult to identify in call stacks, which makes debugging trickier. They should be used sparingly.

На полках

fb2epub
Перетащите файлы сюда, не более 5 за один раз