Skip to content

Instantly share code, notes, and snippets.

@remarkablemark
Last active January 25, 2016 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save remarkablemark/dde4c34afb3020748d1f to your computer and use it in GitHub Desktop.
Save remarkablemark/dde4c34afb3020748d1f to your computer and use it in GitHub Desktop.
Reverse a string or array using JavaScript.
'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