function reverse(string) {
if (string === null) return null
if (string.length === 1) return string;
for (let i = 0; i < Math.floor((string.length-1)/2); i++) {
const front = i;
const back = string.length-1-i;
swap(string, front, back);
}
return string;
}
function swap(array, i, j) {
const temp = array[i];
array[i] = array[j]
array[j] = temp;
}
function runTests(func) {
const inputOutput = [[null, null], [[''], ['']], [['f','o','o',' ', 'b', 'a', 'r'], ['r', 'a', 'b', ' ', 'o', 'o', 'f']]];
for (let i = 0; i < inputOutput.length; i++) {
const input = inputOutput[i].slice(0, inputOutput[i].length-1);
const expected = inputOutput[i][inputOutput[i].length-1];
const result = func(...input);
if (!deepEquals(result, expected)) {
return `Test failed: Expected - ${expected}. Got ${result}`;
}
}
return 'All tests passed!'
}
runTests(reverse);
function deepEquals(x, y) {
if ((typeof x === "object" && x !== null) && (typeof y === "object" && y !== null)) {
if (Object.keys(x).length != Object.keys(y).length)
return false;
for (var prop in x) {
if (y.hasOwnProperty(prop))
{
if (!deepEquals(x[prop], y[prop]))
return false;
}
else
return false;
}
return true;
}
else if (x !== y)
return false;
else
return true;
}
runTests(reverse);