Wednesday, July 1, 2015

Thorough Introduction to Functional JavaScript Programming

Overview

The rapid pace of web platforms, the evolution of browsers, and, most importantly, the demand of your end users has had a profound effect in the way we design web applications today. Users demand web applications feel more like a native desktop or mobile app so that they can interact with rich and responsive widgets, which forces JavaScript developers to think more broadly about the solution domain push for adequate programming paradigms.

With the advent of Single Page Architecture (SPA) applications, JavaScript developers began jumping into object-oriented design. Then, we realized embedding business logic into the client side is synonymous with very complex JavaScript applications, which can get messy and unwieldy very quickly if not done with proper design and techniques. As a result, you easily accumulate lots of entropy in your code, which in turn makes your application harder write, test, and maintain. Enter Functional Programming.

Functional programming is a software methodology that emphasizes the evaluation of functions to create code that is clean, modular, testable, and succinct. The goal is to abstract operations on the data with functions in order to avoid side effects and reduce mutation of state in your application. However, thinking functionally is radically different from thinking in object-oriented terms. So, how do you become functional? How do you begin to think functionally? Functional programming is actually very intuitive once you’ve grasped its essence. Unlearning old habits is actually the hardest part as it can be a huge paradigm shift for most people that come from an object-oriented background. Let’s convert a simple imperative “Hello World” program written in JavaScript, to functional:

Imperative


Functional



These smaller functions combine to implement a program that is easier to reason about as a whole. Why does the functional solution look this way? I like to think of it as basically parameterizing your code so that you can easily change it in a non-invasive manner. This is due to functional programming’s inherent declarative mode of development. Imperative programming tells the computer, in great detail, how to perform a certain task.             

Declarative programming, on the other hand, separates program description from evaluation. It focuses on the use of expressions to describe what the logic of a program is without necessarily specifying its control flow or state changes.

This programming style is possible in JavaScript because of its support for first-class, high-order functions, which is a simple way of defining a function that accepts other functions as parameters or whose return value is a function.

While adopting a declarative style can be beneficial, sometimes you might find that functional code can be a bit harder write; this is a natural first impression before unlearning old methods and habits, as well as becoming comfortable with a higher level of abstraction or expressiveness. So why do it? The remarkable quality of declarative programs is that you wind up writing fewer lines of code and, simultaneously, get more work done. Consider this example: Write a short program to find the longest name in a collection of names. Your first approach is to write something like:



This imperative approach manually iterates over the array from start to finish and keeps track of the longest state name as I iterate. Functional programming takes a different approach by raising the level of abstraction in your code and yielding most of the work to the most robust and optimized artifact in your application, your language runtime, without having to loop at all using recursion. Let’s use it to refactor the same program:



Why go through so much effort to eradicate loops from our code? Loops imply code that is constantly changing or mutating in response to new iterations. Functional programs aim for statelessness and immutability as much as possible so that after a section of code runs no existing variables are changed. To achieve this, functional programming makes use of functions that avoid side effects and changes of state—also known as pure functions.

Pure Functions

Functional programming is based on the premise that you will build immutable programs solely based on pure functions. A pure function has the following qualities:

  • Depends only on the input provided and not on any hidden or external state that may change as a function’s evaluation proceeds or between function calls.
  • Does not inflict changes beyond its scope, like modifying a global object or a parameter reference.

Pure functions can be very hard to use in a world full of dynamic behavior and mutation. But, practical functional programming doesn’t restrict absolutely all state changes; it just provides a framework to help you manage and reduce, while allowing you separate the pure from the impure. It’s more critical to ensure no externally visible side effects occur—immutability from the application’s point of view.

Functions with side effects are, generally, bad design because they rely on data outside of the local scope of the function call, making it difficult to determine exactly what a function is supposed to do when they are run. Pure functions, on the other hand, have clear contracts as part of their signatures that describes clearly all of the function’s formal parameters, making them simpler to understand.
Consider the example of fetching for processing a payment for student given their SSN. Let’s model this with three side effect free functions.



    Composing all three functions makes up our processPayment function:



      Removing all practical side effects made our programs less brittle to changing external conditions. Making a function’s result consistent and predicable is a trait of pure functions called referential transparency.

      Referential transparency and substitutability

      Referential transparency is a more formal way of defining a pure function. Purity in this sense refers to the existence of a pure mapping between a function’s arguments and its return value. Hence, if a function consistently yields the same result on the same input, it is said to be referentially transparent. Here’s a quick example:


      This function always returns the same output when provided the same input. If this were not the case, it must mean that that the function’s return value is being influenced by some external factor. This quality of referential transparency is inherited from mathematical functions, which state that a function is a pure relation between inputs and outputs with the property that each input yields exactly one output.


      Let’s tackle a more complex example: adding a new grade to a list and compute its average. I will create two functions append and average:



      Putting it all together:


      This function yields a consistent result based only on the provided input and does not cause any side effects to the grades list after returning. Referential transparency is a very important quality of pure functions as it allows functional languages to optimize function calls, as you’ll see later in this post.


      Furthermore, a corollary of referential transparency is the principle of substitutability. Because the result of a referentially transparent functions consistently depends only on the values of the arguments provided to it, we say that a function’s return value can be directly replaced into an expression without changing its meaning. Math operators behave this way: adding 2 + 3 can be substituted with 5 into any equation and the result of the equation will forever remain the same. The following statements are all equivalent:

      (2 + 3) * 8 === (5) * 8 === 40

      The same expectations we hold for mathematical operators should also apply to pure functions as well. Now that you’ve caught a glimpse at the fundamental principles behind functional programming, perhaps its definition is more tractable now. So what is functional programming?

      Functional programming refers to the declarative evaluation of pure functions to create immutable programs by avoiding externally observable side effects.

      Becoming functional
      In order to become functional, you must learn to think functionally and have the proper tools to develop your functional awareness—the instinct of looking at problems as a combination of simple functions that together provide a whole solution. Functional programming is a software paradigm that, while based on very foundational concepts, will completely shift the way you think about a problem.


      Modularizing your code
      At a high level, functional programming is effectively the interplay between decomposition (breaking programs into small pieces) and composition (joining pieces to make programs). It is this duality that makes functional programs modular. As I mentioned previously, the unit of modularity, or “unit of work” is the function. Thinking functionally typically begins with decomposition by learning to break up a particular task into logical subtasks (functions):


      If need be, these can be decomposed further until arriving at simple, pure functions, each of which is an independent unit of work. Modularization in functional programming is closely related to the singularity principle, which states that functions should have a single purpose, which is exactly what I was able to achieve.

      Functional composition can be understood simply as taking the output of one function and plugging it into the next. The result of composing two functions together is another function that gets called with the actual arguments. Remember this from school?

      f . g = f(g(x))

      Its back! It reads: “f composed of g,” which supposes a type-safe relationship between what g returns and f receives. As seen in our previous example:






      Behind the scenes, the new roster array returned from append will be passed into calcAverage:
      Given a class roster array with students Haskell, Rosser, and Church with grades 97, 82, 100, respectively, if Alan Turing’s grade in the class was a 75, the new average will be:




      The concept of pure functions transitively applies to computeAverageGrade. Because it was built from the composition of two pure functions, it is itself pure. Understanding compose is crucial for learning how to implementing modularity and reusability in functional applications, as it leads to code where the meaning of the entire expression can be understood from the meaning of its individual pieces, a quality that becomes very hard to achieve in other paradigms. Also, it raises the level of abstraction so that you can clearly outline all of the steps performed in this code without being exposed to any of its underlying details. Because the compose function accepts other functions as arguments, it is known as a high-order function, a artifact in functional languages.
      Functional programming not only makes your code more modular, but in some cases it can also speed up the evaluation of your functions.

      Optimizing your function calls
      Functional programming will not speed up the evaluation times of your individual functions; rather, its strategy is based on avoiding duplicated function calls, which can potentially speed up your application overall. This technique is called memoization, which originates from the premise of functions being referentially transparent. Recall that referentially transparent functions always return the same value on same inputs. Through memoization the set of input parameters are encoded as a string or number and used as the cache key to a function’s result, internally persisted and looked up when the function is invoked again on the same input.



      Consider a function that computes a secure hash based on a user’s password. Depending on the type of algorithm used, this function can be very expensive to call. Generally, with secure encryption the more intense the algorithm the stronger the hash will be. Caching these results can be a tremendous improvement.


      Calling generateSecureHash again on this same input bypasses the computation and returns the memoized result. The effectiveness of memoization is directly proportional to the level modularity in your code. As you decompose big tasks into a greater number of smaller, single-purpose functions, memoization can be used more efficiently to achieve a higher level of fine-grained caching and optimization.

      Memoization is not a native JavaScript feature, but one way to install it is with API code by augmenting JavaScript’s extensible Function object. You can also have it as a standalone call.

      The beauty of this level of caching in functional languages like JavaScript is that it can be implemented without adding any boilerplate code of placing cache checks and inserts all over your functions.

      While on the topic of writing boilerplate code, consider null checks. Handling errors and null values generally leads to an explosion of if-else conditions in your code. This excessive use of branching logic creates code that is hard to maintain and test. As an example, suppose I need to extract the country name of a student’s school address. I think we’ve all seen similar convoluted code before:


      This anti-pattern of clean design is addressed with functional data types called monads used for null-safe operations as well as high-level abstractions that will allow you to write more robust, extensible code while handling errors effectively.

      Handling errors fluently using Monads
      Functional programming places a clear distinction between pure error handling and exception handling. Our goal is to implement pure error handling as much as possible, and allow exceptions to fire in truly exceptional conditions, just as the ones described earlier.

      I will use a purely functional data type called monads to order to treat potentially hazardous state as safe, encapsulated values that use high-order functions to abstract out and consolidate error-handling logic and defensive null-checks. By returning consistent, predictable values, referential transparency is preserved across function calls and error-bearing expressions can easily be combined in a very fluent manner.

      This is possible using the Maybe monad. Maybe is a data type that implements a very intuitive concept: a value is maybe there, maybe not. When wrapping a potentially unsafe value, Maybe either returns an object containing the value or an object containing “nothing.” Instead of returning unsafe null values that then you’ll have to check for, let’s show getCountry based on Maybe.



      Building extensible code with function chains
      Let’s tackle a different problem. Suppose you are tasked to write a program that would compute the average grade of students that have enrolled in more than one class. Approaching this problem from a functional mindset, you can identify three major steps:
      •  Selecting the proper set of students (whose enrollment is greater than one)
      • Extracting their grades
      • Calculating their average grade

        So far you’ve seen how functional programming can help us create modular, testable, and extensible applications. So, how does all this fare when running in a browser environment?

        Streamline client-side development
        Client side events come in many flavors: mouse clicks, text field changes, focus changes, etc. Consider the scenario of handling value changes on a text field and using the value entered to update a welcome banner. Naturally, as any JavaScript developer would do, I resort to jQuery:


        Arguably, this code is not very modular, as I am required to implement the logic of dealing with user input and updating the banner into a single function. Rather, the functional approach to handling events is to subscribe to asynchronous streams and, in a similar fashion to traversing an infinite collection of items, be able to compose a series of functions onto any event instance in a way that is separated from the actual browser event handling logic. In addition, I want to be able to port the concepts of referential transparency and immutability. Client side developing in functional is done reactive with Functional Reactive Programming (FRP). 

        FRP is the combination of reactive programming, or programming with data streams, with a strong focus on composition. For this I can leverage a functional library called Bacon.js that enhances JQuery’s API to define the asEventStream function that works with asynchronous data streams. For example, to subscribe to all keyup events on an input field, I can write the following code:



          Here’s where the functional programming comes in. The onKeyUp function is like an event bus that can treat events as if they were elements in a collection, which means I can easily map functions onto it to immutably manipulate the target objects. I will create a function to extract and run logic on the value in the event stream. Calling the toProperty method on the stream creates a value accessor on any keyup events that occur on that HTML field, which I can listen for and handle within the onValue method. 
              
          Now, I pose to you the same questions with which we started the section: Is this program: Modular? Testable? Extensible? Readable? Maintainable? Functional programming is a paradigm shift that can drastically transform the way in which you tackle solutions to any programming challenges. So, is functional programming a replacement for the more popular object-oriented design? Fortunately, applying functional programming to your code is not an “all or nothing” approach.

          In fact, lots of applications can benefit from it when used alongside an object-oriented architecture. Due to rigid control for immutability and shared state, functional programming is also known for making multi-threaded programming more straightforward. Because JavaScript is a single-threaded platform, this is not something we’ll need to worry about or cover in this post.

          Wrap-up
          In sum, client-side applications are becoming more and more complex every day and, if done poorly, can become a nightmare for companies to maintain. Some companies actually enforce the use of certain paradigms and coding styles, others don’t and welcome the investment of time to learn new and better ways to accomplish certain tasks. Hybrid languages like JavaScript become really useful in these cases as they allow developers to experiment with a mix of styles. Whichever your situation is, I truly believe getting familiar with functional programming, even if you had no immediate plans to move into it, can truly enhance your skills and your ability to tackle complex problems in a way not possible using conventional methods.


          If you liked this article and topic and want to read about it more in-depth, please order my book, which you can get at a 50% off discount: mlatencio.

          Enjoy!






            Saturday, June 13, 2015

            Currying everything in JavaScript

            Overview

            In this post I will discuss the benefits and practical uses of currying, a functional programming technique typically found in pure functional languages, but can be easily ported to JavaScript. I will also make use of a functional library called Ramda.js. Let's dive in.

            Curried functions

            Currying is a technique that converts a multivariable function into a step-wise sequence of unary functions. In other words, a curried function is one that evaluates only when all arguments have been provided; otherwise, it returns a new function that waits for the next.
            Here’s the formal definition of a curry of three parameters:
            
            curry(f) :: (a,b,c) -> f(a) -> f(b) -> f(c)
            
            This formal notation suggests curry is a mapping from functions to functions that deconstructs the input tuple (a,b,c) into separate single-argument invocations. In pure functional programming languages, like Haskell, currying is a built-in feature and automatically part of all function definitions.

            In order to understand currying in JavaScript, first you must understand the difference between a curried and a regular (non-curried) function evaluation. A non-curried function call, as all JavaScript functions are, is permitted to execute with missing arguments. In other words, if I define a function f(a,b,c) and call it with just a, the evaluation proceeds where b and c are set to undefined by the runtime engine.

            This is unfortunate and most likely the reason why curry (and later partial) is not a built-in features of the language. As you can imagine, not declaring any arguments at all and relying on the arguments object within functions exacerbates this issue. On the other hand, a curried function is one where all arguments have been explicitly defined so that, when called with a subset of the arguments, it returns a new function that waits for the rest of the parameters to be supplied before running. Visually this looks like this:

            JavaScript does not automatically curry functions, so we need to write some supporting code. Before we go into auto-currying, let’s start out with a simple scenario of manually currying two arguments:

            function curry2(fn) {
                 return function(firstArg) {              
                      return function(secondArg) {        
                          return fn(firstArg, secondArg); 
                      };
                 };
                }
            

            As you can see in the code above, currying is just another case of a lexical scope (closure) where the returned functions are nothing more than trivial nested function wrappers to capture the arguments for later use. Let’s see curry2 in action; I can use currying to implement a function to check types. It is based on Ramda’s type check function R.is:

            
                // checkType :: Type => Type => Type | TypeError
                var checkType = curry2(function(typeDef, actualType) {
            
                    if(R.is(typeDef, actualType)) {
                        return actualType;
                    }
                    else {
                        throw new TypeError('Type mismatch. Expected [' + typeDef + '] but found [' + typeof actualType + ']');
                    }
                });
            
                checkType(String)('Curry');  //-> String
                checkType(Number)(3);        //-> Number
                checkType(Date)(new Date()); //-> Date
                checkType(Object)({});       //-> Object
                checkType(String)(42);       //-> Throws TypeError
            

            For very simple tasks, curry2 is adequate, but as we start building more complex functionality we’ll certainly need to handle any number of arguments automatically. Normally, I would show you the function’s polyfill, but curry is a particularly long and convoluted function to explain with co-recursive calls, so I’ll spare you the headache and move into a more useful discussion.

            I will use Ramda’s version of R.curry to simulate automatic currying present in pure functional languages that works on any number of arguments. You can imagine automatic currying as simply artificially creating nested function scopes corresponding to the number of arguments a function declares. Visually, currying takes a function like doWork:
            
            // doWork :: (a,b,c,...) -> z
            var doWork = function (a, b, c, ... ) {
            

            Which operates on multiple arguments, and transform it (conceptually) into a function of the form:
            
            // doWork :: a -> b -> c ->... -> z
            var doWork = 
               function (a) {
               return function (b)  {
                       return function (c) {
                       ... 
            

            Curries have many useful applications. For our discussion we will focus on:
            1. Implementing reusable function templates
            2. Building step-wise functions
            3. Destructuring function arguments

            Implementing reusable function templates

            Curries are useful for creating function templates, which are reusable ways of evaluating a family of functions. Suppose I need to configure different families of logging functions to handle different conditions like: errors, warnings, etc. For this example, I will use the popular library Log4js. Most developers implement logging using default parameters:
            
            var logger = new Log4js.getLogger('StudentConsole');
            logger.info('Student added successfully!');
            

            But with Log4js you can do so much more. Suppose you need instead to display messages on the screen as a popup. You can configure an appender to do so:

            logger.addAppender(new Log4js.JSAlertAppender());


            And you can also change the layout so that it outputs messages in JSON format with a layout:

            appender.setLayout(new Log4js.JSONLayout());
            

            There are many settings you can configure as needed and copy and pasting this code into each file causes lots of duplicated code. Instead, let’s use currying to define a reusable function template, which will give you the utmost flexibility and reuse, as shown below:

              var logger = function(appender, layout, name, level, message) {
                    var appenders = {                                   
                        'alert': new Log4js.JSAlertAppender(),
                        'console': new Log4js.BrowserConsoleAppender()
                    };   
                    var layouts = {        
                        'basic': new Log4js.BasicLayout(),
                        'json': new Log4js.JSONLayout(),
                        'xml' : new Log4js.XMLLayout()
                    };
                    var appender = appenders[appender];                 
                    appender.setLayout(layouts[layout]);
                    var logger = new Log4js.getLogger(name);
                    logger.addAppender(appender);
                    logger.log(level, message, null);                   
                };
            

            Now, by currying the logger function I can centrally manage and reuse appropriate loggers for each occasion:
             
                var log = R.curry(logger)('alert', 'json', 'FJS');
            
                log('ERROR', 'Error condition detected!!');
            

            If you are implementing many error-handling conditions into one function or file, you also have the flexibility of partially defining all but the last parameter, as such:

                var logError = R.curry(logger)('console', 'basic', 'FJS', 'ERROR');
                logError('Error code 404 detected!!');
                logError('Error code 402 detected!!');
            

            Behind the scenes, subsequent calls to curry this function are being called, yielding a unary function. The fact that you are able to create new functions from existing ones and pass any number of parameters leads to easily building functions in steps, as argument become defined.

            Building step-wise functions

            Due its ability to partially create function objects, curried functions come handy in cases where you don’t have the values of all function arguments at your disposal, so that you may build functions in steps as the data becomes available. For example, here’s a refactored payment function:
            
            var sendPayment = R.curry(
            function (service, taxRate, currency, amount) {
                    var total = amount + (taxRate * amount);
                    var Money = Tuple(Number, String);
                    return service.submit(new Money(total, currency));
            });
            

            This code shows a function of four parameters that could be applied all at once or as needed. I also took the liberty of removing some side effects by explicitly declaring a payment service parameter used to handle payment submissions; hence, providing sendPayment with all necessary data it needs to execute. Listing 4.8 shows how I can progressively build a function as data becomes available:
            
                function makePayment(student, amount) {
             
                    var payment = sendPayment(new PaymentService());            
            
                    var taxRate = getCurrentTaxRateFor(student.getAddress());
                    payment = payment(taxRate);                            
            
                    if(student.getAddress().getCountry() === 'USA') {
                        var pay = payment('USD');              
                    }
                    else {
                        pay = payment('Other');                                 
                    }
                    return pay(amount);                                         
                }
            
                var student = new Student('Alonzo', 'Church', 'Princeton')
                    .setAddress('New Jersey', 'USA');
            
                makePayment(student, 100); //-> (107, 'USD');
            

            If instead of building functions piece by piece you’d rather apply all arguments at once, currying can be used to lift functions so that arrays can be overlaid over its arguments, also called destructuring assignment.

            Destructuring function arguments

            Destructuring data refers to the ability of a language to bind the constituents of a complex type, say a tuple or an array, to variables. In ES6 we can do the following:
                
            [a, b, c] = [1, 2, 3]
            

            Where a, b, and c will be assigned 1, 2, and 3, respectively. We can use currying to simulate a similar effect when it comes to a function’s arguments. For instance, calculating a student’s final grade for the class, I can use the following function:

               var computeFinalGrade = R.curry(function (hw1, hw2, midterm, final) {
                    return Math.round((hw1 + hw2 + midterm + final) / 4);
                }); 
            

            But, suppose the grades data is stored in an array, how would you pass the array to this function? Certainly, you can index each individual grade value and plug it into each parameter, but then you’ll have to cases where a grade value is invalid (for missed tests) and other mundane concerns. Fortunately, we can use curry to create a function, spread, which will allow you apply a list of arguments of length N to any curried function of N-arity. Here’s how it works:

            spread(computeFinalGrade)([98, 99, 100, 87]); //-> 96
            

            Here’s an implementation of the spread function:

               var spread = R.curryN(2, function(cf, args) {
                    var fn = this;
                    return args.reduce(function(cf, nextArg) {    
                        return cf.call(fn, nextArg)               
                    }, cf);
                });
            

            Furthermore, I’ve also taken the opportunity to show you a very useful variant of currying available in Ramda called, curryN, which returns a curried function with a specified arity—only the first N parameters will be curried. By default if no length is specified, the function’s length property is used.

            Aside from gaining reusability, as I mentioned before, the principal motivation behind currying is to allow us to convert multi-argument functions into unary functions so that they can be easily composed as components of a function pipeline. An alternative to currying is partial function application or function binding, moderately supported by the JavaScript language, to produce functions of smaller arity that also work well when plugged into function pipelines.

            Resources

            1. http://ramdajs.com/0.14/index.html

            Friday, May 1, 2015

            Optimizing your JavaScript with Functional Programming

            Overview

            Generally speaking, there are many ways to optimize your code. For instance, you could re-evaluate your core algorithms and perhaps try to speed up the execution of some loops. Also, you can adopt some best practices like avoiding large string concatenation or excessive use of closures. But, instead of reducing the execution time of your functions, what if you could avoid calling unnecessary functions? Being that JavaScript is a functional programming language, there are a couple of techniques we can use to reduce the execution time of your programs:

            1. Lazy Evaluation
            2. Memoization

            Before we get started, here are some concepts you will need to understand in order make sense of the rest:

            Pure functions: A function is pure when it has no side effects, i.e does not read/modify any external data.

            Referential transparency (RT): Piggy-backing on pure functions, RT functions are ones which compute their return values based solely on the input provided. It's the closest thing to a mathematical function. Because its result is consistent with respect to the input, RT functions are very easy to reason about and test.

            Now, Let's jump in:

            Lazy Evaluation

            In JavaScript, function composition plays an important part in implementing lazy evaluation. Lazy evaluation is a “call by need” execution strategy whereby a function is invoked only when needed. Non-strict languages like Haskell have built-in lazy evaluation consistently in every call; however, JavaScript is a strict language, which means that all functions are evaluated eagerly. Consider the following example: Suppose we wanted to extract a finite subset of numbers from an infinite set. What? Bear with me. We can create a function called range(begin, end) which creates an array of whole numbers from a specified beginning to end:

            
            var firstTenItems = range(1, Infinity).take(10);
            
            firstTenItems();//-> 1, 2, 3, 4....10?
            

            You might wondering: how can this function call ever terminate if we are generating an infinite list of numbers? In a non-strict language like Haskell, we could write an equivalent program that will actually terminate and take the first 10 items, efficiently. In JavaScript, this similar program will generate an infinite loop since it will try to eagerly evaluate the range function first. Because lazy evaluation is not built-in to JavaScript, the only alternative is to emulate it with an API, which is based on functional composition in order to circumvent JavaScript’s eager evaluation mechanism at its core by a functional library called Lazy.js.

            
                var evenNumbers = Lazy.generate(function (x) {           
                    return 2 * x;
                }); //-> 2, 4, 6, 8,...
            
                evenNumbers.take(300).each(doWork);                      
            

            The Lazy.generate function is essentially a stream data structure. A stream is an array-like data structure that behaves very closely to a linked list (in a language like Java). It can be used to generate an infinite amount of elements. While this sounds bizarre, behind the scenes it is the power of lazy evaluation via function composition that allows this to happen. The code previously shown is a classical problem of separating a function that can generate infinite number of possible values, and a selector that chooses the appropriate ones.

            Using Lazy.js allows us to modularize this program effectively as the initialization of the number stream is deferred until the each function is called. Without it, you would be forced to write code like looks similar to:
            
            var threshold = 10;
            for (var i = 0; i < Infinity; i+=2) {
              if (i >= threshold) {
                  break;
              }
              else {
                var item = items[i]; 
                
                // do work on item
              }
            }
            
            This one-off code isn’t reusable at all, takes longer to write and it’s harder to maintain. Using Lazy.js we will avoid writing code like this in favor of a more declarative approach that takes advantage of lazy evaluation. Because it avoids unnecessary computations (or at the very least defer to only when needed), lazy evaluation has also shown to speed up the execution of JavaScript programs.

            Memoization

            Another form of laziness is by avoiding computing a function call altogether. In traditional object-oriented systems this is accomplished by placing a cache or proxy layer that is checked before a function is called. Upon return, the result of the function is given a key that references it uniquely and this key-value pair is persisted in the cache.

            Functional languages implement a caching mechanism akin to the object-oriented model but built-in to the platform so a function’s result is stored and can be retrieved when calling it again with the same input. This technique is called Memoization and it relies on the notion of referentially transparent functions. Recall that pure functions always return the same value on same inputs.
            Through Memoization the set of input parameters are encoded as the key to a function’s result, internally cached, and looked up when the function is invoked again on the same input.

            Consider a function that computes a secure hash based on a user’s unique username and password. Depending on the type of algorithm used, this function can be very expensive to call. Generally, with secure encryption the more intense the algorithm the stronger the hash will be.
            
            function generateSecureHash(username, password) {
             // run expensive algorithm
            
             return hash;
            }
            generateSecureHash('jim', 'Jim@Pwd!');
            
            Based on the premise of pure functions, calling generateSecureHash again on this same input bypasses the computation and returns the memorized result. The effectiveness of Memoization is directly proportional to the level modularity in your code. As you decompose big tasks into a greater number of smaller, single-purpose functions, Memoization can be used to achieve a higher level of fine-grained caching.

            Like lazy evaluation, Memoization is not a native JavaScript feature, but can be installed by augmenting JavaScript’s extensible Function object, and looks like this:
            
            var computeFactors = (function factors(num) {
             
            // run algorithm
            
             return factors;
            }).memoize();
            
            computeFactors(100); //-> [1,2,4,8,16,32,64]
            

            Again, subsequent calls with 100 will be lazy and just return the memorized result. The beauty of this level of caching in functional languages and in JavaScript is can be implemented without adding any boilerplate code of placing cache checks/adds all over our functions. Here's a look at implementing memoization by extending the Function object:
            
            
            Function.prototype.memoized = function (key) {
            
                    if (this.length === 0) {
                        console.log("Cannot memoize function call with empty arguments");
                        return;
                    }
                    else {
                        // Handle identifiable objects
                        if (key.getId && (typeof key.getId === 'function')) {
                            // Extract objs ID
                            key = key.getId();
                        }
                        else {
                            // Last resort, handle objects by JSON-stringifying them
                            if (!isNumeric(key) && !isString(key)) {
                                // stringify key
                                key = JSON.stringify(key);
                            }
                        }
                    }
            
                    // Create a local cache
                    this._cache = this._cache || {};
                    var val = this._cache[key];
            
                    if (val === undefined || val === null) {
                        //alert("Cache miss, apply function");
                        console.log("Cache miss");
                        val = this.apply(this, arguments);
                        this._cache[key] = val;
                    }
                    else {
                        console.log("Cache hit");
                    }
                    return val;
                };
            
                // Enhance Function prototypes
            
                // Provide ability for functions to memoize (or be proxied)
                Function.prototype.memoize = function () {
            
                    var fn = this;
            
                    if (fn.length === 0 || fn.length > 1)
                        return fn;  // only handle functions with a single formal argument
            
                    return function () {
                        return fn.memoized.apply(fn, arguments);
                    };
                };
            
            Functional languages cede mechanisms for lazy evaluation to the language platform and free developers from having to worry about implementing and testing this. In JavaScript, we can do the same by letting with high-level constructs like compose and memoize handle any optimizations in our code. This is preferable because it means that we are free to test our functions independently of any optimization mechanism. Hopefully we've enjoyed this blog post and begin to embraces functional programming is your programming paradigm of choice! Stay tuned for more!

            Resources

            1. http://danieltao.com/lazy.js/