Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //underscore way (from Functional JavaScript, already publicly available here:
- //http://cdn.oreillystatic.com/oreilly/booksamplers/9781449360726_sampler.pdf)
- function lameCSV(str) {
- return _.reduce(str.split("\n"), function(table, row) {
- table.push(_.map(row.split(","), function(c) { return c.trim()}));
- return table;
- }, []);
- };
- console.log(lameCSV("name,age,hair\nMerble,35,red\nBob,64,blonde"));
- //more functional way
- function split(separator, string){
- if (is("Array", string))
- return string.map(split.bind(0, separator));
- return string.split(separator);
- };
- var splitRow = split.bind(0, "\n");
- var splitCell = split.bind(0, ",");
- var coolCSV = compose(splitCell, splitRow);
- console.log(coolCSV("name,age,hair\nMerble,35,red\nBob,64,blonde"));
- //Utils
- function is(type, object){
- return toString.call(object) === '[object ' + type + ']';
- };
- function compose(fn1, fn2){
- return function(){
- return fn1.call(this,fn2.apply(this, arguments));
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement