I'm working on a JavaScript exercise and having some trouble untangling the logic as to why it works. It basically has a function called "mystery" that uses a bunch of very simple functions, and returns an array you give it but in reversed order. I've been sitting in front of a whiteboard for an hour trying to figure out the logic behind it, and not getting it. Can a kind soul take a look at these functions and explain how the mystery function returns a reversed array? Thank you!
function rest(arr) {
return arr.slice(1);
}
function first(arr) {
return arr[0];
}
function conj(arr, value) {
arr.push(value);
return arr;
}
function mystery(array) {
if (array.length === 0) {
return [];
}
return conj(mystery(rest(array)), first(array));
}
mystery is a recursive function.
It calls itself using the return value of the rest function, which returns everything except the first element.
It uses the result of that + the result of first, which returns the first character, and concatenates them again (using conj), but with the first element at the end.
So, say you put in [H e l l o],
it will return conj(mystery([e l l o], H)
mystery([e l l o]) will return conj(mystery([l l o], e)
mystery([l l o]) will return conj(mystery([l o], l)
and so on, until the array that goes into mistery is empty, in which case the recursion ends, and we bubble back up to the first call.
Side note, recursion is often used for exercises like this, but although it has some specific uses, in many cases it's way more efficient to not use recursion, because the overhead of making another function call is relatively hard work, compared to other solutions using a simple loop to move or swap items around.
You can see what is happening if you output some information:
function rest(arr) {
return arr.slice(1);
}
function first(arr) {
return arr[0];
}
function conj(arr, value) {
arr.push(value);
return arr;
}
function mystery(array, level) {
if (array.length === 0) {
console.log('mystery level '+level+' is called with an empty array. Recursion ends here.. Stay tuned for the answer.');
return [];
}
console.log('mystery level '+level+' is called with '+array+
'. I will move '+first(array)+' to the end.');
var result = conj(mystery(rest(array), level+1), first(array));
console.log('returning '+result+' for level '+level);
return result;
}
console.log(mystery(['H','e','l','l','o'], 0));
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