Last active
November 18, 2015 01:57
-
-
Save bangedorrunt/2f955a64d8905be72aa4 to your computer and use it in GitHub Desktop.
Basic recursion method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function multiBy10(n) { | |
| // Setup a base return | |
| if (n <= 1) | |
| return 10 | |
| // Loop recursive here | |
| else | |
| return 10 + multiBy10(n-1) | |
| } | |
| /** | |
| * multiBy10(3) = (10 + multiBy(2)) | |
| * = (10 + (10 + multiBy(1))) | |
| * = (10 + (10 + (10))) | |
| * = 30 | |
| **/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Reference from http://www.datchley.name/recursion-tail-calls-and-trampolines/ | |
| // Generate an array of integers in the range s -> e. | |
| // Iterative implementation | |
| function range(s, e) { | |
| var res = []; | |
| while (s != e) { | |
| res.push(s); | |
| s < e ? s++ : s--; | |
| } | |
| res.push(s); | |
| return res; | |
| } | |
| range(1,4); // [1,2,3,4] | |
| range(-5,1); // [-5,-4,-3,-2,-1,0,1] | |
| // Generate an array of numbers in a given range. | |
| // Recursive implementation | |
| function range(s, e) { | |
| var res = []; | |
| res.push(s); | |
| return s == e ? res : res.concat(range(s<e ? ++s : --s, e)); | |
| } | |
| range(1,4); // [1,2,3,4] | |
| /** | |
| * if we return the results of a function call (recursive or not) | |
| * at the end of our function and none of our function's local environment | |
| * is needed as part of that evaluation, then that function call is said | |
| * to be in tail position | |
| **/ | |
| // Generate an array of numbers in a given range. | |
| // Tail Recursive implementation | |
| function range(s, e, res) { | |
| res = res || []; | |
| res.push(s); | |
| return s == e ? res : range(s<e ? ++s : --s, e, res); | |
| } | |
| range(1,4); // [1,2,3,4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment