How to reverse an array of characters in place in JavaScript

Here is one way to reverse a string or an array of characters in place in JavaScript.
Space complexity: O(1)
Time complexity: O(n)

Note: In JavaScript, strings are immutable so we are using an array of characters to represent our string.

reverseStringTry in REPL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// since strings are immutable
// the param 'string' will be represented as an array of characters
function reverse(string) {
if (string === null) return null
if (string.length === 1) return string;
// iterate until midpoint of string and swap ends
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;
}
// ==== Tests
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); // All tests passed
// Test cases
// reverse(null); // null
// reverse(['']); // ''
// reverse(['f','o','o',' ','b','a','r']) // '['r', 'a', 'b', ' ', 'o', 'o', 'f']'
// ==== Test helpers
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); // All tests passed