Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

question about Basic:Recursion #60

Closed
qqibrow opened this issue Jul 18, 2014 · 2 comments
Closed

question about Basic:Recursion #60

qqibrow opened this issue Jul 18, 2014 · 2 comments

Comments

@qqibrow
Copy link

qqibrow commented Jul 18, 2014

I was fascinated by the solution of reduce function. Can anyone tell me about your thoughts here? How you analysis this problem and tackle it step by step? Thank you!

@fkysly
Copy link

fkysly commented Sep 11, 2014

My solution:
function reduce(arr, fn, initial) {
if (!arr.length)
return;
initial = fn(inital, arr[0], 0, arr);
reduce(arr.slice(1), fn, initial);
return initial;
}
module.exports = reduce;

The simple method to solve this problem is using loop to execute the "fn" many times, then the initial will be the right answer.
Like this:

funtion reduce(arr, fn, initial) {
for(var k = 0; k < arr.length, k++) {
initial = fn(initial, arr[k], k, arr);
}
...

But we can't use loop to solve this problem.

Recursion is another method to solve this problem.We can't use recursion in the "fn", because we can't override this function, but we can use recursion in our reduce function to execute the "fn" function many times, and make the inintial be the right answer.

@ghost
Copy link

ghost commented Nov 8, 2014

@fkysly, that's a good solution and it's what i've done at first. But the index agrument in callback function becomes useless this way, because it's always equal to 0, so user can't get the index of the item in the array.

@qqibrow qqibrow closed this as completed Nov 8, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants