Add a module for general functional programming stuff

This commit is contained in:
Tissevert 2019-02-14 22:01:28 +01:00
parent f05459ef80
commit d7d967e7cd

64
fun.js Normal file
View file

@ -0,0 +1,64 @@
function Fun() {
return {
defaultCompare: defaultCompare,
defined: defined,
insert: insert,
map: map,
mapFilter: mapFilter,
of: of,
proj: proj
};
function insert(obj, t, compare, min, max) {
min = min == undefined ? 0 : min;
max = max == undefined ? t.length : max;
compare = compare == undefined ? defaultCompare : compare;
if(max - min < 1) {
return min;
}
var avg = Math.floor((max + min) / 2);
if (compare(obj, t[avg]) < 0) {
return insert(obj, t, compare, min, avg);
} else {
return insert(obj, t, compare, avg+1, max);
}
}
function defaultCompare(a, b) {
if(a < b) {
return -1;
} else if(a > b) {
return 1;
} else {
return 0;
}
}
function map(mapper, f) {
return function() {
var args = Array.prototype.map.call(arguments, mapper);
return f.apply(null, args);
}
}
function of(o) {
return function(key) {return o[key];};
}
function proj(key) {
return function(o) {return o[key];};
}
function mapFilter(mapper, predicate) {
return function(array) {
return array.reduce(function(accumulator, elem) {
var v = mapper(elem);
return predicate(v) ? accumulator.concat(v) : accumulator;
}, []);
};
}
function defined(x) {
return x != undefined;
}
}