HTML and CSS Reference
In-Depth Information
This implementation simply returns the next function, and assigns hasNext
as a property of it. Every call to next updates the hasNext property. Leveraging
this we can update the loop test to look like Listing 6.24.
Listing 6.24 Looping with functional iterators
"test should loop collection with iterator":
function () {
var collection = [1, 2, 3, 4, 5];
var next = tddjs.iterator(collection);
var result = [];
while (next.hasNext) {
result.push(next());
}
assertEquals(collection, result);
}
6.4 Memoization
Our final closure example will be provided by memoization, a caching technique at
the method level and a popular example of the power of JavaScript functions.
Memoization is a technique that can be employed to avoid carrying out ex-
pensive operations repeatedly, thus speeding up programs. There are a few ways
to implement memoization in JavaScript, and we'll start with the one closest to the
examples we've worked with so far.
Listing 6.25 shows an implementation of the Fibonacci sequence, which uses
two recursive calls to calculate the value at a given point in the sequence.
Listing 6.25 The Fibonacci sequence
function fibonacci(x) {
if(x<2){
return 1;
}
return fibonacci(x - 1) + fibonacci(x - 2);
}
The Fibonacci sequence is very expensive, and quickly spawns too many recur-
sive calls for a browser to handle. By wrapping the function in a closure, we can
manually memoize values to optimize this method, as seen in Listing 6.26.
 
 
Search WWH ::




Custom Search