dimitris papadimitriou
dimitris papadimitriou More than 12 years’ experience as full stack developer and Software Architect . Functional javascript with categories.

Lazy functor

Lazy functor

A thunk ()=>{…} is a subroutine used to inject an additional calculation into another subroutine. Thunks are primarily used to delay a calculation until its result is needed, or to insert operations at the beginning or end of the other subroutine. For example, a very common pattern is to initialize an object only when it is needed. This is called Lazy initialization because if we have a very costly computation that may not be needed, we should not eagerly evaluate it.

1
2
3
4
5
var bigArrayComputation = [...Array(10e6)]
.map((_, i) => i)
.reduce((a, i) => a + i)

MayOrnMayNotDisplay(bigArrayComputation)

Instead of eager initialization, we can the creation or evaluation with a factory method that is only performed once if/and when it is needed.

1
2
3
4
5
6
7
8
9
10
11
12
13
var Lazy = function (fn) {

  this.value = () => {
   if (!this.v) { this.v = fn(); }
   return this.v;
  }
}

 

var v = new Lazy(() => [...Array(10e6)].map((_, i) => i).reduce((a, i) => a + i))
var s = v.value();    //if we use value then the calculation is performed and cached 
var s1 = v.value();   //

Run This: Js Fiddle

This Lazy structure is known as Lazy loading design pattern and can be extended to a functor by providing the following method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 var Lazy = function (fn) {

  this.value = () => {
   if (!this.v) {
    this.v = fn();
   }
   return this.v;
  }

  this.map = (f) => {
   return new Lazy(() => f(this.value()))
  }
 }


var lazy = new Lazy(() => 2).map(x => x + 3);
//the value was not accessed when we used the map method 
console.log("still not accessed the value")


 var result = lazy.value();// only now the sequence is evaluated
 console.log(result)

Run This: Js Fiddle


Excerpt from the Book Functional Programming in Javascript in LeanPub https://leanpub.com/functional-programming-in-js-with-categories

comments powered by Disqus