Reverse inplace
by Alex Myronov
JavaScript
const message = 'find you will pain only go you recordings security the into if'
// 1.
// const result = message.split(' ').reverse().join(" ")
// console.log(result)
// 2.
// const reverse = arr =>
// arr.reduce((res, item) => {
// res.unshift(item)
// return res
// }, [])
// console.log(reverse(message.split(' ')).join(' '))
const reverseInPlace = (arr) => {
let i = -1
let word = []
const words = []
while (i++ < arr.length) {
if (arr[i] === ' ' || i == arr.length) {
console.log('word: %o', word)
words.push(word.join(''))
word = []
} else {
word.push(arr[i])
}
}
const phrase = []
while (words.length) {
phrase.push(words.pop())
}
return phrase.join(' ')
}
console.log(reverseInPlace('hello there you'.split('')))
// 'if into the security recordings you go only pain will you find'