@guj/rif-js
Version:
Simplify filter,map and such when their use should be conditionnal
51 lines (43 loc) • 1.54 kB
JavaScript
// Credits for extension go to :
// https://gist.github.com/hns/663932/bca04dc7800e66f3b21c08d6ae22260d1d091a60
function Rif() {
}
Rif.prototype = Object.create(Array.prototype);
function turnArrayToRif(arrayToMutate) {
arrayToMutate.__proto__ = Rif.prototype;
return arrayToMutate;
}
Rif.of = function (originalArray) {
let arrayCopy = Array.from(originalArray);
return turnArrayToRif(arrayCopy);
};
function applyAsRifMethod(funk, thees) {
return function () {
thees = thees || this;
return turnArrayToRif(funk.apply(thees, arguments))
};
}
function integrateMethodToRif(funkName) {
let funk = Array.prototype[funkName];
Rif.prototype[funkName] = applyAsRifMethod(funk);
Rif.prototype[funkName + "If"] = function (doIMap) {
if (!doIMap) {
return () => this;
}
return applyAsRifMethod(funk, this);
};
};
Object.getOwnPropertyNames(Array.prototype)
.filter(key => key !== `splice`) //<- I'll deal with you the day you'll become a real function you dirty punk, you hybrid monstrosity
.filter(key => key !== `constructor`)
.filter(key => Array.prototype[key] instanceof Function)
.filter(key => {
const example = [null];
const result = Array.prototype[key].call(example, x => x);
if (!(result instanceof Array)) {
return false;
}
return result !== example;
}).forEach(integrateMethodToRif);
Object.getOwnPropertyNames(Rif)
.forEach(prop => exports[prop] = Rif[prop]);