Advertisement
framp

underscore vs functional

Jun 3rd, 2013
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //underscore way (from Functional JavaScript, already publicly available here:
  2. //http://cdn.oreillystatic.com/oreilly/booksamplers/9781449360726_sampler.pdf)
  3. function lameCSV(str) {
  4.   return _.reduce(str.split("\n"), function(table, row) {
  5.     table.push(_.map(row.split(","), function(c) { return c.trim()}));
  6.     return table;
  7.   }, []);
  8. };
  9. console.log(lameCSV("name,age,hair\nMerble,35,red\nBob,64,blonde"));
  10.  
  11. //more functional way
  12. function split(separator, string){
  13.   if (is("Array", string))
  14.     return string.map(split.bind(0, separator));
  15.   return string.split(separator);
  16. };
  17. var splitRow = split.bind(0, "\n");
  18. var splitCell = split.bind(0, ",");
  19. var coolCSV = compose(splitCell, splitRow);
  20. console.log(coolCSV("name,age,hair\nMerble,35,red\nBob,64,blonde"));
  21.  
  22. //Utils
  23. function is(type, object){
  24.   return toString.call(object) === '[object ' + type + ']';
  25. };
  26. function compose(fn1, fn2){
  27.   return function(){
  28.     return fn1.call(this,fn2.apply(this, arguments));
  29.   }
  30. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement