Diar Turkmani
Diar Turkmani

Reputation: 63

How To Change What You've Called In A Function To An Array

Suppose I create a function that flips an array's elements. For example, the function takes in [1,2,3,4] and flips it to [4,3,2,1]. My function is capable of doing that. However, I want to do something that doesn't seem to work. If I call the function like this: flip("hello"), I want it to change "hello" to an array like this: [h,e,l,l,o], flip the elements to become like this: o,l,l,e,h then join the elements together to make it olleh. This is what I have been able to make so far:

function reverse (A) {
if(typeof(A) == 'string') { A.toString().split(" "); }
var i1 = 0;
var i2 = A.length - 1;

function swap(A, i1, i2) {
var temp = A[i1];
A[i1] = A[i2];
A[i2] = temp;
return A;

}

var index1 = 0;
var index2 = A.length - 1;
var temp = A[index1];

for(let i = index1; i < index2; i++) { 
    swap(A, i, index2); index2--;
}
console.log(A);

}

This does not work at all. I think that is because I am not dealing with what is being called but rather the parameter itself. I have also tried:

if(typeof(reverse(A)) == 'string') {A.toString().split(" "); }

However, that gives me a result that says: RangeError: Maximum call stack size exceeded

I have been searching for an hour with no success. Any help?

Upvotes: 2

Views: 76

Answers (2)

Munish
Munish

Reputation: 11

<pre><code>
<script>
function myFunction() {
    var str = "hello";
    var splitting = str.split(""); 
    var reversed_array=splitting.reverse();
    var result=reversed_array.join("");
    document.getElementById("demo").innerHTML = result;
    }
</script>
</code></pre>

Function that are used split :- which will split the string into array . reverse :- which will be used to reverse the array . join :- It will join the reversed array

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

Replace

A.toString().split(" ");

with

A = A.split(""); // empty string for splitting, splits every character

because you need an assignment and while A is already an string, you do not need toString().

Later you have to return the joined array with:

return A.join('');

Methods used:

Complete working code with some minor changes:

function reverse(a) {
    function swap(b, i1, i2) {
        var temp = b[i1];
        b[i1] = b[i2];
        b[i2] = temp;
    }

    var index1 = 0,
        index2 = a.length - 1,
        isString = typeof a === 'string';

    if (isString) {
        a = a.split("");
    }

    for (index1 = 0; index1 < index2; index1++) {
        swap(a, index1, index2);
        index2--;
    }

    return isString ? a.join('') : a;
}

document.write('<pre>' + JSON.stringify(reverse([100, 101, 102]), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(reverse('hello'), 0, 4) + '</pre>');

Upvotes: 1

Related Questions