FunctionalPrograming, To abstract

FunctionalPrograming


function splat(fun){
 return function(array){
  return fun.apply(null, array);
 }
};
var addArrayElements = splat(function(x, y){
 return x + y
});
addArrayElements([1, 2]);
//3

function unsplat(fun){
 return function(){
  return fun.call(null, _.toArray(arguments));
 };
}
var joinElements = unsplat(function(array){return array.join("")});
joinElements('_', '$', '/', '!', ':');
//"_$/!:"

To abstract


//origin
function parseAge(age){
 if(!_.isString(age)) throw new Error("this is not String")
 var a;
 console.log("you will change age to number");
 a = parseInt(age, 10);
 if(_.isNaN(a)){
  console.log(["cant change age to number"].join(""));
  a = 0;
 }
 return a;
}
parseAge("42")
//you will change age to number
//42

parseAge(42)
//Uncaught Error: this is not String(…)

parseAge("frab")
//you will change age to number
//can't change age to number
//0


//To abstract
function fail(thing){
 throw new Error(thing);
}
function warn(thing){
 console.log(["worn:", thing].join(""));
}
function note(thing){
 console.log(["info:", thing].join(""));
}

function parseAge(age){
 if(!_.isString(age)) fail("this is not String");
 var a;
 note("you will change age to number");
 a = parseInt(age, 10);
 if(_.isNaN(a)){
  warn(["cant change age to number"].join(""));
  a = 0;
 }
 return a;
}

parseAge("fbob");

//info:you will change age to number
//warn:can't change age to number
//0

parseAge("1");

//info:you will change age to number
//1

reference

(Visited 1 times, 1 visits today)