Skip to content

Commit

Permalink
Merge pull request loverajoel#264 from sylvaindethier/gh-pages
Browse files Browse the repository at this point in the history
change cached fibonacci from @tommot348
  • Loading branch information
loverajoel committed Feb 22, 2016
2 parents 819f2e6 + e0f1ef8 commit 7d15d35
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,16 @@ var fibonacci = function(n){
it works, but not efficient. it did lots of duplicate computing works, we can cache its previously computed results to speed it up.

```js
var fibonacci = (function(){
var cache = {
0: 0,
1: 1
};
return function self(n){
return n in cache ? cache[n] : (cache[n] = self(n-1) + self(n-2));
var fibonacci = (function() {
var cache = [0, 1]; // cache the value at the n index
return function(n) {
if (cache[n] === undefined) {
for (var i = cache.length; i <= n; ++i) {
cache[i] = cache[i-1] + cache[i-2];
}
}
return cache[n];
}
})()
```
Also, we can define a higher-order function that accepts a function as its argument and returns a memoized version of the function.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,16 @@ var fibonacci = function(n){
它可以运行,但并不高效。它做了太多重复的运算,我们可以通过存储这些运算结果来使其加速。

```js
var fibonacci = (function(){
var cache = {
0: 0,
1: 1
};
return function self(n){
return n in cache ? cache[n] : (cache[n] = self(n-1) + self(n-2));
var fibonacci = (function() {
var cache = [0, 1]; // cache the value at the n index
return function(n) {
if (cache[n] === undefined) {
for (var i = cache.length; i <= n; ++i) {
cache[i] = cache[i-1] + cache[i-2];
}
}
return cache[n];
}
})()
```
我们也可以定义一个高阶函数,它接收一个方法作为参数,返回一个该方法运用存储后的新方法。
Expand Down

0 comments on commit 7d15d35

Please sign in to comment.