fix: added reverse string inplace (#1406)

Co-authored-by: madhuredra <madhuredra.tiwari@zemosolabs.com>
This commit is contained in:
Madhurendra Nath Tiwari
2023-10-02 23:06:45 +05:30
committed by GitHub
parent 36dcff8c5d
commit 0ca18c2b2c
2 changed files with 14 additions and 42 deletions

View File

@ -16,24 +16,17 @@ function ReverseStringIterative (string) {
}
/**
* JS disallows string mutation so we're actually a bit slower.
*
* @complexity O(n)
* @author dev-madhurendra
* Reverses a number by converting it to a string.
*
* @param {string} str - The number to reverse.
* @returns {string} The reversed number.
*
* @example
* const reversed = reverseString("hello"); // Returns olleh
*/
function ReverseStringIterativeInplace (string) {
if (typeof string !== 'string') {
throw new TypeError('The given value is not a string')
}
const _string = string.split('')
for (let i = 0; i < Math.floor(_string.length / 2); i++) {
const first = _string[i]
_string[i] = _string[_string.length - 1 - i]
_string[_string.length - 1 - i] = first
}
return _string.join('')
}
const ReverseStringIterativeInplace = (str) => [...str].reverse().join('')
export { ReverseStringIterative, ReverseStringIterativeInplace }