Skip to content

Instantly share code, notes, and snippets.

@formula1
Created April 4, 2015 04:50
Show Gist options
  • Save formula1/2798c3cdf27313b27b0b to your computer and use it in GitHub Desktop.
Save formula1/2798c3cdf27313b27b0b to your computer and use it in GitHub Desktop.
Functional Programming Example
function SortFilterIterate(array){
this.ari = array;
this.fliter = [];
}
SortFilterIterate.prototype.filter = function(fn){
this.fliters.push(fn);
return this;
}
SortFilerIterate.prototype.sort = function(fn){
this.compare = fn;
return this;
}
SortFilterIterate.prototype.forEach = function(fn){
this.l = this.filters.length;
var half = Math.floor(this.ari.length/2);
this.mergeIterate(this.split(this.ari.slice(0,half)),this.split(ari.slice(half)), fn);
}
SortFilterIterate.prototype.asArray = function(){
this.l = this.filters.length;
return this.merge(this.split(this.ari.slice(0,half)),this.split(ari.slice(half)));
}
SortFilterIterate.prototye.split = function(ari){
if(ari.length === 0) return ari;
if(ari.length === 1){
var i = 0, l = this.l;
var item = ari[0];
while(i<l && this.filters[i](item) !== false) i++;
if(i < l) return [];
return ari;
}
var half = Math.floor(ari.length/2);
return this.merge(this.split(ari.splice(0,half)),this.split(ari));
}
SortFilterIterate.prototype.merge = function(ari1,ari2){
var ret = [];
var l = ari1.length, ll = ari2.length
while(l > 0 && ll > 0){
if(compare(ari1[0],ari2[0]) < 0){
l--;
ret.push(ari1.shift());
}else{
ll--
ret.push(ari2.shift());
}
}
if(l > 0){
ret = ret.concat(ari1);
}else if(ll > 0){
ret = ret.concat(ari2);
}
return ret;
}
SortFilterIterate.prototype.mergeIterate = function(ari1,ari2,fn){
var l = ari1.length, ll = ari2.length
while(l > 0 && ll > 0){
if(compare(ari1[0],ari2[0]) < 0){
l--;
fn(ari1.shift());
}else{
ll--
fn(ari2.shift());
}
}
while(l > 0){
fn(ari1.shift());
l--
}
while(ll > 0){
fn(ari2.shift());
ll--
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment