Skip to content

Instantly share code, notes, and snippets.

@pgarciacamou
Last active August 29, 2015 14:19
Show Gist options
  • Save pgarciacamou/20beaccbf1ac8e1e9364 to your computer and use it in GitHub Desktop.
Save pgarciacamou/20beaccbf1ac8e1e9364 to your computer and use it in GitHub Desktop.
JavaScript Algorithms
// Recursive Binary Search
// Array must be sorted in ascending order
Array.prototype.binarySearch = function(num, from, to) {
to = to || this.length-1;
from = from || 0;
if(!num || from > to) return null;
var index = Math.floor((to-from) / 2) + from;
if(num < this[index]) return this.binarySearch(num, from, index-1);
if(num > this[index]) return this.binarySearch(num, index+1, to);
return index;
};
// How to use:
[1,2,3,4,5].binarySearch(5); // 4
function EventEmitter() {
this.events = {};
}
EventEmitter.prototype.addEventListener = function(ev, cb, ctx) {
this.events[ev] = this.events[ev] || [];
this.events[ev].push(cb.bind(ctx));
};
EventEmitter.prototype.emit = function(ev, args) {
(this.events[ev] || []).forEach(function(cb) {
cb(args);
});
};
function StateMachine(state, sMin, sMax) {
this.state = state || 0;
this.sMin = sMin || 0;
this.sMax = sMax || 1;
this.minChangeTime = 1250;
this.lastChanged = 0;
EventEmitter.call(this);
}
StateMachine.prototype = Object.create(EventEmitter.prototype);
StateMachine.prototype.changeState = function(nState) {
var t = new Date();
if (nState >= this.sMin && nState <= this.sMax && t - this.lastChanged > this.minChangeTime) {
this.emit("stateChange", {
oldState: this.state,
newState: nState
});
this.state = nState;
this.lastChanged = t;
if (nState === 0 || nState === 2) {
this.minChangeTime = 1250;
} else {
this.minChangeTime = 1000;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment