2

I actually made this test passed but I am not satisfied with one thing.

If I passed the following:

var expected = [-5, '0', 5];
var actual = [-5, 0, 5];

I'll get this result:

FAILED [check mixed elements] Expected "-5,0,5", but got "-5,0,5"

As you can see, it shows two exactly the same thing, where in it must be:

FAILED [check mixed elements] Expected "-5,'0',5", but got "-5,0,5"

If I used the arrayToString function on the FAILED option of assertArraysEqual function it will look something like this:

FAILED [check mixed elements] Expected "-,5,',0,',5", but got "-,5,0,5"

Any idea how to fix this?

here's a copy of my full codes:

function arrayToString(array) {
  var convertedArrayToString = '';

  if(array[0] === "-"){
   array.splice(0, 2, (array[0] + array[1]));
  }

  for (var i = 0; i < array.length; i++) {
    if(typeof array[i] === 'number'){
       convertedArrayToString += Number(array[i]);
    }else if(typeof array[i] === 'string'){
      convertedArrayToString += `'${array[i]}'`;
    } else {
      convertedArrayToString += array[i];
    }
  }
  return convertedArrayToString.split('').join(',');
}


function assertArraysEqual(actual, expected, testName) {
  if (arrayToString(actual) === arrayToString(expected)) {
    return console.log('passed');
  } else {
    return console.log(`FAILED [${testName}] Expected "${arrayToString(expected)}", but got "${arrayToString(actual)}"`);
  }
}

var expected = [-5, '0', 5];
var actual = [-5, 0, 5];
assertArraysEqual(actual, expected, 'check mixed elements');

var expected = [1, 2, 3, 4];
var actual = [1, 2, 4];
assertArraysEqual(actual, expected, 'check length');

var expected = ['b', 'r', 'o', 'k', 'e', 'n'];
var actual = 'broken'.split('');
assertArraysEqual(actual, expected, 'splits string into array of characters');
3
  • 2
    What are you trying to do ? Commented Sep 2, 2017 at 20:25
  • I was trying to output FAILED [check mixed elements] Expected "-5,'0',5", but got "-5,0,5" exactly when I join the array elements. Read my post carefully. Commented Sep 2, 2017 at 20:29
  • Not sure what your trying to do, and why. But Javascript has a really nice feature for converting arrays into a string.. JSON.stringify([-5, '0', 5]) === JSON.stringify([-5, 0, 5]) Commented Sep 2, 2017 at 20:33

2 Answers 2

1

You could use JSON.stringify for each element for building a string.

function arrayToString(array) {
    return JSON.stringify(array);
}

console.log(arrayToString([5, '0', 5]));

Sign up to request clarification or add additional context in comments.

Comments

1

You should use JSON.stringify():

return console.log(`FAILED [${testName}] Expected ${JSON.stringify(expected)}, but got ${JSON.stringify(actual)}`);

should give you:

FAILED [check mixed elements] Expected [-5,"0",5], but got [-5,0,5]

Comments