Answer the question
In order to leave comments, you need to log in
Is JavaScript array reversal properly tested?
Good day, dear community members!
In the book Expressive JavaScript by Marain Haverbeck, it is suggested as an exercise to write an array reversal function, that is, you need to take an array and reverse it so that the elements that were at the beginning are at the end. There is a standard .reverse() method for arrays that performs this function.
This problem has already been mentioned among the questions, and a number of interesting solutions have been proposed.
For training, I solved the problem in several ways and decided to check how long each option takes.
I have implemented 4 functions.
First option with a While loop:
function reversInPlaceWhile(arr) {
var len = arr.length - 1;
var i = 0, temp;
while (i < len - i) {
temp = arr[i];
arr[i] = arr[len - i];
arr[len - i] = temp;
i++;
}
return arr;
}
function reversInPlaceFor(arr) {
var len = arr.length - 1;
var temp;
for (var i = 0, iter = Math.floor(len / 2); i < iter; i++) {
temp = arr[i];
arr[i] = arr[len - i];
arr[len - i] = temp;
}
return arr;
}
function reversInPlaceStandart(arr) {
arr.reverse();
return arr;
}
function reversInPlaceSplice(arr) {
var len = arr.length - 1;
for (var i = 0; i < len; i++) {
arr.splice(i, 0, arr.pop());
}
return arr;
}
function newArrayLine(count) {
var arr = [];
for (var i = 0; i < count; i++) {
arr[i] = i;
}
return arr;
}
function test(arr, iter, callback) {
var start = Date.now();
for (var i = 0; i < iter; i++) {
callback(arr);
}
var end = Date.now();
return end - start;
}
Answer the question
In order to leave comments, you need to log in
copal And if thus. Although something strongly confuses me with such an approach, I will ask anyway.
We create a reversArray object and it has three methods with different implementations of array reversal.
Next, we call it with code:
function testOne() {
var start = Date.now();
reversArray.reversInPlaceWhile(newArrayLine(100000));
var end = Date.now();
return end - start;
}
function testTwo() {
var start = Date.now();
newArrayLine(100000).reverse();
var end = Date.now();
return end - start;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question