Skip to content

Instantly share code, notes, and snippets.

@jesus-seijas-sp
Last active October 19, 2018 23:44
Show Gist options
  • Save jesus-seijas-sp/ab039b8ac10eed65f40c554ecd27242e to your computer and use it in GitHub Desktop.
Save jesus-seijas-sp/ab039b8ac10eed65f40c554ecd27242e to your computer and use it in GitHub Desktop.
array reverse
const numElements = 10000;
const numLoops = 100000;
const arr = [];
for (let i = 0; i < numElements; i += 1) {
arr.push(i);
}
function reverse1(a) {
const reversed = [];
const aLength = a.length;
if (aLength >= 0) {
for (let i = aLength; i >= 0; i -= 1) {
reversed.push(a[i]);
}
return reversed;
}
return a;
}
function reverse2(a) {
for (let l = 0, m = a.length / 2, r = a.length - 1; l < m; l += 1, r -= 1) {
const t = a[l];
a[l] = a[r];
a[r] = t;
}
return a;
}
function reverse3(a) {
const result = new Array(a.length);
for (let i = 0, r = a.length - 1; r >= 0; i += 1, r -= 1) {
result[i] = a[r];
}
return result;
}
console.time('Method 1');
for (let i = 0; i < numLoops; i += 1) {
reverse1(arr);
}
console.timeEnd('Method 1');
console.time('Method 2');
for (let i = 0; i < numLoops; i += 1) {
reverse2(arr);
}
console.timeEnd('Method 2');
console.time('Method 3');
for (let i = 0; i < numLoops; i += 1) {
reverse3(arr);
}
console.timeEnd('Method 3');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment