Implementation of cache format
VaR memoize = function (FN) {var cache = []; return function (I) {return (I in cache )? Cache [I]: (Cache [I] = fn. call (arguments. callee, I) ;};} var fib = new memoize (function (I) {if (I = 0 | I = 1) return 1; return this (I-1) + This (I-2 );})
<Br/> <! Doctype HTML> <br/> <pead> <br/> <title> cached function fib </title> <br/> <style> <br/> table {<br/> border-collapse: collapse; <br/> width: 100%; <br/>}< br/> table TD {<br/> border: 1px solid firebrick; <br/>}</P> <p> </style> <br/> <SCRIPT> </P> <p> var memoize = function (FN) {<br/> var cache = []; <br/> return function (I) {<br/> return (I in cache )? Cache [I]: <br/> (Cache [I] = fn. call (arguments. callee, I); <br/>}; <br/>}</P> <p> var fib = new memoize (function (I) {<br/> if (I = 0 | I = 1) <br/> return 1; <br/> return this (I-1) + This (I-2 ); <br/>}); </P> <p> var draw = function () {</P> <p> var table = ["<Table>"] <br/> function test (n) {<br/> var T = new date; <br/> for (VAR I = 0; I <1000; I ++) {<br/> var res = fib (N ); <br/>}< br/> T = new date-T; <br/> table. push ('<tr> <TD>', N, '</TD> <TD>', res, '</TD> <TD>', T, '</TD> <TD>', (T/N ). tofixed (2), '</TD> </tr>'); <br/>}</P> <p> for (VAR I = 0; I <79; I ++) {<br/> test (I); <br/>}< br/> table. push ('</table>'); <br/> var DIV = document. createelement ('div '); <br/> Div. innerhtml = table. join (''); <br/> document. body. appendchild (DIV ); </P> <p >}</P> <p> </SCRIPT> <br/> </pead> <br/> <body onload = "Draw (); "> </P> <p> </body> <br/> </ptml> <br/>
RunCode
New Implementation:
Function fib (n) {function _ fib (n, a, B, arg1, arg2) {If (n> 1) _ fib (n-1, A, B, arguments, arg1); Return arg1 [2] = arg2 [1] = a + B;} return _ fib (n, 0, 1, [], []);}
<Br/> <! Doctype HTML> <br/> <pead> <br/> <title> use arguments to recursively implement fib </title> <br/> <style> <br/> table {<br/> border-collapse: collapse; <br/> width: 100%; <br/>}< br/> table TD {<br/> border: 1px solid firebrick; <br/>}</P> <p> </style> <br/> <SCRIPT> </P> <p> function fib (N) {<br/> function _ fib (n, a, B, arg1, arg2) {<br/> If (n> 1) _ fib (n-1, A, B, arguments, arg1); <br/> return arg1 [2] = arg2 [1] = a + B; <br/>}< br/> return _ fib (n, 0, 1, [], []); <br/>}</P> <p> var draw = function () {</P> <p> var table = ["<Table>"] <br/> function test (n) {<br/> var T = new date; <br/> for (VAR I = 0; I <1000; I ++) {<br/> var res = fib (N ); <br/>}< br/> T = new date-T; <br/> table. push ('<tr> <TD>', N, '</TD> <TD>', res, '</TD> <TD>', T, '</TD> <TD>', (T/N ). tofixed (2), '</TD> </tr>'); <br/>}</P> <p> for (VAR I = 0; I <79; I ++) {<br/> test (I); <br/>}< br/> table. push ('</table>'); <br/> var DIV = document. createelement ('div '); <br/> Div. innerhtml = table. join (''); <br/> document. body. appendchild (DIV ); </P> <p >}</P> <p> </SCRIPT> <br/> </pead> <br/> <body onload = "Draw (); "> </P> <p> </body> <br/> </ptml> <br/>
run the Code