Last active
January 25, 2016 17:17
-
-
Save remarkablemark/dde4c34afb3020748d1f to your computer and use it in GitHub Desktop.
Reverse a string or array using JavaScript.
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
'use strict'; | |
/** | |
* Reverses a string or array. | |
* | |
* @param {(String|Array)} i - The string or array. | |
* @return {(String|Array)} | |
*/ | |
function reverse(i) { | |
var isString = false; | |
if (typeof i === 'string') { | |
isString = true; | |
} else if (i.constructor !== Array) { | |
return null; | |
} | |
var result = []; | |
for (var n = 0, len = i.length; n < len; n++) { | |
result.unshift( | |
isString ? i.slice(n, n + 1) : i.slice(n, n + 1)[0] | |
); | |
} | |
return isString ? result.join('') : result; | |
} | |
if (typeof module !== 'undefined' && module.exports) { | |
module.exports = reverse; | |
} | |
// tests | |
console.assert(reverse('foobar') === 'raboof'); | |
console.assert(reverse('') === ''); | |
console.assert(reverse([1, 3, 3, 7]).toString() === '7,3,3,1'); | |
console.assert(JSON.stringify(reverse([])) === '[]'); | |
console.assert(reverse({}) === null); | |
console.assert(reverse(42) === null); | |
// benchmark | |
console.time('reverse'); | |
Array.apply({}, { length: 10000 }).forEach(function() { | |
reverse('lorem ipsum dolor sit amet'); | |
}); | |
console.timeEnd('reverse'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment