lazy.js
lazy.js copied to clipboard
Feature Idea: `generate` automatically holds a sequence(array) in closure
Great job as usual. Thanks daniel tao. I have a thought of new feature.
IMO, your fibonacci sample is hard to follow.
The reason is
- We need to implement closure to pass the proper function to
generate
. - You just use too many variables, such as
x
,y
,prev
. - (2) typically occurs when we employ Imperative Programming and try to design algorithm flow. We definitely can and should define a Sequence in Math manner since this is a library for Declarative programming.
So, here's my code:
var _ = require('lazy.js');
var fibF = function()
{
var seq = []; //build array sequence in this closure
var f = function(n)
{
var val;
if (n <= 1)
{
val = 1; // as the Fib definition in Math
}
else
{
val = seq[n - 2] + seq[n - 1]; // as the Fib definition in Math
}
seq[n] = val;
return val;
};
return f;
}();
var Fib = _.generate(fibF);
var fib_10 =
Fib
.take(10)
.toArray();
console.log(fib_10); //[ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ]
This works, however, I think the code could be much much cleaner like:
var _ = require('lazy.js');
var fibF = function(n)
{
if (n <= 1)
{
return 1; // as the Fib definition in Math
}
else
{
return _.this(n - 2) + _.this(n - 1); // as the Fib definition in Math
}
};
var Fib = _.generate(fibF);
var fib_10 =
Fib
.take(10)
.toArray();
console.log(fib_10); //[ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ]
I am looking forward to your thought.
Thanks!
:thumbsup:
This is harder than I thought.
To make this work for recursive functions such as fibonacci sequence, the only working method I found so far is, to wrap the function by some memoize
function at the declaration., like underscore
does.
http://underscorejs.org/#memoize
var memoize = require('memoizee');
var fib = memoize(function(n)
{
if (n <= 1)
{
return 1; // as the Fib definition in Math
}
else
{
return fib(n - 2) + fib(n - 1); // as the Fib definition in Math
}
});