JSFiddle - React, Tailwind, and code Playground
by Khalil Zhang
HTML
Implement collection pivot: Pivot means put all the things left of the middle element right, and vice versa,
Eg: Pivot {A, B, C} should give {C, B, A};
Pivot { 1, 2, 3, 4 } should give { 3, 4, 1, 2 };
Pivot { 1, 2, 3, 4, 5, 6, 7 } should give { 5, 6, 7, 4, 1, 2, 3 };
Pivot { 11, 8, 45 } should give { 45, 8, 11 };
Hint: What type should input/output be? Why?
JavaScript
Array.prototype.reverse = function () {
var floor_l = Math.floor(this.length / 2);
var ceil_l = Math.ceil(this.length / 2)
for (var i = 0; i < floor_l; i++) {
swap(this, i, i + ceil_l);
}
}
function swap(items, firstIndex, secondIndex) {
var temp = items[firstIndex];
items[firstIndex] = items[secondIndex];
items[secondIndex] = temp;
}
var arr = [1, 2, 3, 4];
arr.reverse();
console.dir(arr);
var arr = [1, 2, 3, 4, 5, 6, 7];
arr.reverse();
console.dir(arr);
var arr = [11, 8, 45];
arr.reverse();
console.dir(arr);