Skip to content

Instantly share code, notes, and snippets.

@Kuzcoo
Last active December 10, 2016 10:33
Show Gist options
  • Save Kuzcoo/294e1bdd3ed4a82546853bd698bbeddf to your computer and use it in GitHub Desktop.
Save Kuzcoo/294e1bdd3ed4a82546853bd698bbeddf to your computer and use it in GitHub Desktop.
Array.prototype.findHalf = function () {
return Math.floor(this.length/2);
};
Array.prototype.isEmpty = function () {
return this.length === 0;
};
Array.prototype.first = function () {
return this[0];
};
Array.prototype.last = function () {
return this[this.length-1];
};
//
let recurChop = (target,array,index) => {
if (array.isEmpty() ||
array.first() > target ||
array.last() < target) {return -1;}
if (array.first() === target) {return index;}
let newArr = null,
half = array.findHalf(),
firstSlice = array.slice(0,half),
firstLen = firstSlice.length;
if (firstSlice.last() < target) {
newArr = array.slice(half);
index+=firstLen;
return recurChop(target,newArr,index);
}
return recurChop(target,firstSlice,index);
};
let chop = (target,array) => {
return recurChop(target,array,0);
};
//
let chop2 = (target,array) => {
let index = 0;
if (array.first() > target ||
array.last() < target ||
array.isEmpty()) {
return -1;
}
while (array.first() != target) {
let half = array.findHalf(),
firstSlice = array.slice(0,half);
if (firstSlice.last() < target) {
array = array.slice(half);
if (array.length > 1) {
index += array.length;
}
} else {
array = firstSlice;
}
}
return index;
};
//
let chop3 = (target,array) => {
let index = 0;
if (array.first() > target ||
array.last() < target ||
array.isEmpty()) {
return -1;
}
for (let i = 0; array.first() != target; i++) {
let half = array.findHalf(),
firstSlice = array.slice(0,half);
if (firstSlice.last() < target) {
array = array.slice(half);
if (array.length > 1) {
index += array.length;
}
} else {
array = firstSlice;
}
}
return index;
};
module.exports = {
chop,
chop2,
chop3
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment