3

I'm trying to write an array replication function in JavaScript that will take an array and a replication factor as input parameters, and return that replicated array.

Like such:

expect(replicate([2,3,4],2).toEqual([2,3,4,2,3,4]));

And I'm trying to accomplish this with a recursively-called, self-executing inner function that should return the desired value to the outer function when finished.

The inner function seems to work correctly:

var replicate = function (inputArray, n) {
    var outputArray = [];
    return (function replicateInner(n) {
        if (n > 0) {
            outputArray.push(inputArray.slice(0));
            replicateInner(--n)
        } else {
            alert('inner function returns: ' + outputArray);
            //inner function returns: [2,3,4,2,3,4]
            return outputArray;
        }
    })(n);

 };

But when I call the outer function, it returns undefined

alert(replicate([2,3,4],2)); // returns undefined, not [2,3,4,2,3,4]

Any idea what I might be missing here? Thanks!

2 Answers 2

4

Because you are not returning the result from replicateInner(--n), like this

return replicateInner(--n);

Also, when you push the inputArray.slice(0) to outputArray, the result will be like this

[ [ 2, 3, 4 ], [ 2, 3, 4 ] ]

What you need to do is to concatenate the arrays like this

outputArray = outputArray.concat(inputArray.slice(0));

with this change, the output becomes

[ 2, 3, 4, 2, 3, 4 ]
Sign up to request clarification or add additional context in comments.

6 Comments

That did it! Thanks! Here's the working fiddle: jsfiddle.net/databass/hX8Qk
@DavidByman Glad to have been of help! Feel free to accept my answer if you feel it was useful to you. :-)
But I do get the same results whether using push or concat.
@DavidByman Are you sure? When you use .push, you would be getting an array of array.
@DavidByman Correct, you are getting two arrays, right? But you don't want that.
|
1

Awesome question. Here is a simplified answer that has both an IIFE and the recursion. We don't need to pass anything around or pass anything to the IIFE since it is all in closure scope.

var replicate = function (inputArray, n) {
    var outputArray = [];
    (function replicateInner() {
        if (n > 0) {
            outputArray = outputArray.concat(inputArray.slice(0));
            --n;
            replicateInner()
        }
    })();
    return outputArray;
};

1 Comment

this is much cleaner. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.