I need another set of eyes. There has to be something small I'm just missing here.
I'm inputting a string which is brokend into an array of words, then takes every 5 indexes (words) and joins them into their own index.
This is accomplished through a recursive call.
The final call of the recursion prints the correct result I'm looking for while inside, but the actual returned value outside is undefined..
Please help me out here.
const limit = str => {
const arr = str.split(' ');
function recursiveLimit(arr, acc = []) {
if (arr.length !== 0) {
const toSlice = arr.length < 5 ? arr.length : 5;
const newArr = arr.slice(toSlice);
const newAcc = [...acc, arr.slice(0, toSlice).join(' ')];
recursiveLimit(newArr, newAcc);
} else {
console.log('final array: ', acc); // the array I want to return (looks good here)
return acc; // return it
}
}
return recursiveLimit(arr); // undefined
};
console.log(
'OUTPUT: limit',
limit(
'one two three four five six seven eight nine ten eleven twelve thirteen fourteen'
)
);
To maintain the callstack you should always return recursive function calls. Inside your first if
statement, you don't return a call to your function which leads to an undefined
value. So while acc
moves down the callstack and is properly logged, it doesn't get return
ed back up the callstack and stored in the limit
variable. Simply adding a return
fixes the problem
const limit = str => {
const arr = str.split(' ');
function recursiveLimit(arr, acc = []) {
if (arr.length !== 0) {
const toSlice = arr.length < 5 ? arr.length : 5;
const newArr = arr.slice(toSlice);
const newAcc = [...acc, arr.slice(0, toSlice).join(' ')];
// missing return was here
return recursiveLimit(newArr, newAcc);
} else {
console.log('final array: ', acc);
return acc;
}
}
return recursiveLimit(arr);
};
console.log(
'OUTPUT: limit',
limit(
'one two three four five six seven eight nine ten eleven twelve thirteen fourteen'
)
);
All you need to do is add a return
before your recursive call of recursiveLimit
on line 8.
Fixed code:
const arr = str.split(' ');
function recursiveLimit(arr, acc = []) {
if (arr.length !== 0) {
const toSlice = arr.length < 5 ? arr.length : 5;
const newArr = arr.slice(toSlice);
const newAcc = [...acc, arr.slice(0, toSlice).join(' ')];
return recursiveLimit(newArr, newAcc);
} else {
console.log('final array: ', acc); // the array I want to return (looks good here)
return acc; // return it
}
}
return recursiveLimit(arr); // undefined
};
console.log(
'OUTPUT: limit',
limit(
'one two three four five six seven eight nine ten eleven twelve thirteen fourteen'
)
);```
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With