Even within the training context, an array based collector for aggregating the reversed string data does not contradict the algorithm, the trainer/teacher might have in mind.
Thus, create a result
array of same length of string and initialize a counter value of rounded half the length of the string's length. Count down this value to zero while separately incrementing a left side index starting from -1 and decrementing a right side index starting from the string's length.
Then assign the string's right index related character to the array's left index position and the string's left index related character to the arrays right index position. The iteration steps have been cut to half and the result
array gets returned as its own join
ed string value representation.
function reverseString(value) {
value = String(value);
let idxLeft = -1;
let idxRight = value.length;
let count = Math.ceil(idxRight / 2);
let result = new Array(idxRight);
while (count--) {
result[++idxLeft] = value[--idxRight];
result[idxRight] = value[idxLeft];
}
return result.join('');
}
console.log(
'Hello World =>', reverseString('Hello World')
);
console.log(
'Anna Otto =>', reverseString('Anna Otto')
);
console.log(
'null =>', reverseString(null)
);
console.log(
'undefined =>', reverseString()
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
Taking into account Bergi's comment ...
"OP wrote that their trainer doesn't want them to use .join()
though…"
... a reverse functionality based on (half) a loop, swapping and just string concatenation could be implemented like follows ...
function reverseString(value) {
value = String(value);
const strLength = value.length;
const isEvenLength = strLength % 2 === 0;
const halfWayIndex = Math.floor(strLength / 2);
const halfWayOffset = isEvenLength && 1 || 0;
let result = !isEvenLength && value[halfWayIndex] || '';
for (let idx = 1; idx <= halfWayIndex; ++idx) {
result =
value[halfWayIndex - halfWayOffset + idx] +
result +
value[halfWayIndex - idx];
}
return result;
}
console.log(
`'Hello World' => '${ reverseString('Hello World')}'`
);
console.log(
`'Anna Otto' => '${ reverseString('Anna Otto')}'`
);
console.log(
`null => '${ reverseString(null)}'`
);
console.log(
`undefined => '${ reverseString()}'`
);
.as-console-wrapper { min-height: 100%!important; top: 0; }