Skip to content

Instantly share code, notes, and snippets.

@federicofazzeri
Created February 24, 2017 18:47
Show Gist options
  • Save federicofazzeri/3d63b85a182c2e27c3b9c42e4ce8aafe to your computer and use it in GitHub Desktop.
Save federicofazzeri/3d63b85a182c2e27c3b9c42e4ce8aafe to your computer and use it in GitHub Desktop.
A simple Angular service for function composition
(function(window, angular) {
'use strict';
/****
* Simple composition factory for Angular 1x
*****/
var composer = angular.module('composerModule', []);
composer.factory('Composer', Composer);
function Composer() {
// basic validation if a custom function is not provided
var isSafe = function isSafe(val) {
if(val === undefined || val === null) {
return false;
}
return true;
};
//input validation and check if the function throws an error
function fnCheck(fn) {
return function(value) {
if( isSafe(value) ) {
try{
return fn(value);
} catch (e){
console.log(fn.name + ' error: ' + e);
return value;
}
}else {
return value;
}
};
}
//set custom validation
function setValidator(myCheck) {
if(typeof myCheck === 'function') {
isSafe = myCheck;
}
return this;
}
//pipe the functions to compose
function pipe() {
var fns = Array.prototype.slice.call(arguments);
return fns.reduceRight(function (fn1, fn2) {
fn1 = fnCheck(fn1);
fn2 = fnCheck(fn2);
return function(input) {
return fn1(fn2(input));
};
});
}
return {
pipe: pipe,
setValidator: setValidator
};
}
}(window, window.angular));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment