Created
February 7, 2017 06:43
-
-
Save xujihui1985/8d8886950b71cb606ce4b8ec39cbfb8d to your computer and use it in GitHub Desktop.
reverse sentense
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const assert = require('assert'); | |
function reverse(sentences) { | |
const tokens = sentences.split(' '); | |
const half = Math.floor(tokens.length / 2) | |
for(let i = 0; i < half; i++) { | |
const a = tokens[i]; | |
const b = tokens[tokens.length - (i + 1)]; | |
if (b === undefined) { | |
return; | |
} | |
const ab = a + b; | |
tokens[tokens.length - (i + 1)] = ab.substring(0, ab.length - b.length); | |
tokens[i] = ab.substring(a.length, ab.length); | |
} | |
return tokens.join(' '); | |
} | |
const cases = [{ | |
input: '1 2 3 4 5 6', | |
output: '6 5 4 3 2 1', | |
}, { | |
input: '1 2 3 4 5 6 7', | |
output: '7 6 5 4 3 2 1', | |
}]; | |
cases.forEach(c => { | |
assert.equal(c.output, reverse(c.input)); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment