SlideShare una empresa de Scribd logo
1 de 88
Descargar para leer sin conexión
Functional Programming
  using Underscore.js


      othree @ OSDC 2013
me


• @othree
• https://blog.othree.net
me

• PhD Candidate
• Front End Engineer
• On the way learning good from functional
  programming languages
Function of
    Functional Language

• Pure function
• First class citizen
• Higher order function
• ...
Pure Function

• Side effect free
• Same input, same output
• ex: trigonometric functions
First Class Citizen


• Function like variable
• ex: function expression

var f = function () { /*...*/ };
Higher Order Function


• Function takes or return functions
• ex: event listener
http://www.flickr.com/photos/78428166@N00/6036104277/
Take a Look
Examples from ‘Pure, functional JavaScript’




                          http://cjohansen.no/talks/2012/sdc-functional/
[
    {
         name: 'Gates',
         gender: 'M',
         org: 'M$'
    },
    {
         name: 'Peter'
         gender: 'M',
         org: 'Hㄒㄈ'
    }
]
"Mentioned by Gates, Peter, Jobs"
var str = "Mentioned by ";

for (var i = 0, l = tweeps.length; i < l; ++i) {
    str += tweeps[i].name;
    if (i < tweeps.length - 1) { str += ", "; }
}
[
    {
         name: 'Gates',
         gender: 'M',
         org: 'M$'
    },
    {
         name: 'Peter'
         gender: 'M',
         org: 'Hㄒㄈ'
    }
]
[
    'Gates',
    'Peter'
]
var names = [];

for (var i = 0, l = tweeps.length; i < l; ++i) {
    names.push(tweeps[i].name);
}
var str = "Mentioned by " + names.join(", ");
var names = tweeps.map(function (tweep) {
    return tweep.name;
});
var names = tweeps.map(function (t) { return t.name; });
var str = "Mentioned by " + tweeps.map(function (t) {
    return t.name;
}).join(", ");
function prop(name) {
    return function (object) {
        return object[name];
    };
}
var str = "Mentioned by " + tweeps.map(prop("name")).join(", ");
Case 2
[
    {
          getSummary: function () {
              return {
                  text: 'Summaries',
                  html: '<p>Summaries</p>'
              };
          }
    },
    {
          getSummary: function () {
              return {text: 'Summaried'};
          }
    },
    ...
]
<div>
  <p>Summaries</p>
  <p>Summaried</p>
  <p>Summary</p>
</div>
buildSummary: function () {
    var div = document.createElement("div"), p;

    for (var i = 0, l = this.components.length; i < l; ++i) {
        p = document.createElement("p");
        p.innerHTML = this.components[i].getSummary().text;
        div.appendChild(p);
    }

    return div;
}
DOM functions
var ul = cull.dom.el("ul");
ul.nodeType === 1 // true




                              https://github.com/culljs/dome/
var ul = cull.dom.el("ul", { className: "bands" });

//
var li = cull.dom.el("li", "Execration");
var ul = cull.dom.el("ul", { className: "bands" }, li);
var ul = cull.partial(cull.dom.el, "ul");
var li = cull.partial(cull.dom.el, "li");
["a", "br", "code", "div", ...].forEach(function (tagName) {
    cull.dom.el[tagName] = cull.partial(cull.dom.el, tagName);
});

//
["a", "br", "code", "div", ...].forEach(function (tagName) {
    root[tagName] = cull.partial(cull.dom.el, tagName);
});
http://www.flickr.com/photos/jackhynes/519904699/
buildSummary: function () {
    return div(this.components.map(function (component) {
         return p(component.getSummary().text);
    }));
}
buildSummary: function () {
    return div(this.components.map(function (component) {
         return p(component.getSummary().text);

}
    }));
                          1
buildSummary: function () {
    return div(this.components.map(function (component) {
         return p(component.getSummary().text);

}
    }));
                          1             2
buildSummary: function () {
    return div(this.components.map(function (component) {
         return p(component.getSummary().text);

}
    }));
              3           1             2
buildSummary: function () {
    return div(this.components.
        map(function (component) {
             return component.getSummary();
        }).map(function (summary) {
             return summary.text;
        }).map(function (text) {
             return p(text);
        }));
}
function func(name) {
    return function (object) {
        return object[name]();
    };
}
buildSummary: function () {
    return div(this.components.
        map(func("getSummary")).
        map(function (summary) {
             return summary.text;
        }).map(function (text) {
             return p(text);
        }));
}
buildSummary: function () {
    return div(this.components.
        map(func("getSummary")).
        map(prop("text")).
        map(function (text) {
             return p(text);
        }));
}
buildSummary: function () {
    return div(this.components.
        map(func("getSummary")).
        map(prop("text")).
        map(p));
}
var summarize = compose([p, prop("text"), func("getSummary")]);
var callGetSummary = func("getSummary");
var getText = prop("text");
var summarize = compose([p, getText, callGetSummary]);

// summarize(obj);
//   =>            callGetSummary(obj)
//   =>   getText(callGetSummary(obj))
//   => p(getText(callGetSummary(obj)))
buildSummary: function () {
    var summarize = compose([p, prop("text"), func("getSummary")]);
    return div(this.components.map(summarize));
}
var summarize = compose([p, prop("text"), func("getSummary")]);

// ...

buildSummary: function () {
    return div(this.components.map(summarize));
}
http://www.flickr.com/photos/guerson/5630633727/
Functional Programming
      in JavaScript
Native

• forEach
• map/reduce
• filter
Functional JavaScript


• by Oliver Steele at 2007
• First functional JavaScript Library I know
Underscore.js

• by Jeremy Ashkenas from DocumentCloud
• “Underscore is a utility-belt library for
  JavaScript that provides a lot of the
  functional programming support”
Lo-Dash


• Will talk later
cull.js

• by Christian Johansen and Magnar Sveen
• “Cull is a toolbelt for writing functional
  javascript.”
• Used in the examples above

                                    https://github.com/culljs/culljs
LiveScript & prelude.ls

• by George Zahariev
• A new compile to JavaScript language fork
  from Coco
• Stay in this room until tomorrow, Mindos
  have a talk about LiveScript
GHCJS


• by Hamish Mackenzie,Victor Nazarov, Luite
  Stegeman
• Haskell to JavaScript compiler
Underscore.js

• compose
• map/reduce
• filter
• pluck
var str = "Mentioned by " + tweeps.map(prop("name")).join(", ");
var str = "Mentioned by " + _.reduce(
   _.map(tweeps, function (t) { return t.name; }),
   function (memo, name, i) {
      return (i == 0) ? name : memo + ', ' + name; },
   ''
);
var str = "Mentioned by " + _(tweeps)
  .chain()
  .map(function (t) { return t.name; })
  .reduce(function (memo, name, i) {
    return (i == 0) ? name : memo + ', ' + name; }, '')
  .value();
var str = "Mentioned by " + _(tweeps)
  .map(function (t) { return t.name; })
  .join(', ');
var str = "Mentioned by " + _(tweeps).pluck('name').join(', ');
Still Not Enough


• curry, partial
• prop, func from above example
Lo-Dash
Functional Programming
  using Underscore.js


      othree @ OSDC 2013.1
Functional Programming
  using Underscore.js
            Lo-Dash



      othree @ OSDC 2013.1
-
_
_
-
_
-
What is Lo-Dash


• Underscore.js fork by John-David Dalton,
  Kit Cambridge, and Mathias Bynens
Difference
• Better performance
• Robust result
• Larger file size
• AMD supports
• Auto chain
• More power: cloneDeep, partial, result...
_.partial
var greet = function(greeting, name) {
    return greeting + ' ' + name;
};
var hi = _.partial(greet, 'hi');
hi('moe');
// ! 'hi moe'




                                         http://lodash.com/docs#partial
_.result
var object = {
   'cheese': 'crumpets',
   'stuff': function () {
     return 'nonsense';
   }
};

_.result(object, 'cheese');
// ! 'crumpets'

_.result(object, 'stuff');
// ! 'nonsense'




                                 http://lodash.com/docs#result
With Lo-Dash
var summarize = compose([p, prop("text"), func("getSummary")]);

// ...

buildSummary: function () {
    return div(map(summarize), this.components);
}
var summarize = _.compose(
    p,
    _.partialRight(_.result, 'name'),
    _.partialRight(_.result, 'getSummary')
);

// ...

buildSummary: function () {
    return div(_.map(this.components, summarize));
}
Performance?
Bad..
http://jsperf.com/for-vs-foreach/71
http://jsperf.com/for-vs-foreach/71
• Take benefits from functional programming
• Not change everything to functional
• Library helps, ex: lo-dash
References
Further Readings
http://interglacial.com/hoj/hoj.html
http://cjohansen.no/talks/2012/sdc-functional/
http://kitcambridge.be/blog/say-hello-to-lo-dash/
http://www.slideshare.net/ihower/fp-osdc2012v2
http://shop.oreilly.com/product/9781593272821.do
http://shop.oreilly.com/product/0636920028857.do
d
            se
          ea
        el
      tR
    Ye
 ot
N




        http://shop.oreilly.com/product/0636920028857.do
Questions?



      http://www.flickr.com/photos/roman/5610736/

Más contenido relacionado

La actualidad más candente

Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveEugene Zharkov
 
Writing Clean Code in Swift
Writing Clean Code in SwiftWriting Clean Code in Swift
Writing Clean Code in SwiftDerek Lee Boire
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is hereSebastiano Armeli
 
A New Baseline for Front-End Devs
A New Baseline for Front-End DevsA New Baseline for Front-End Devs
A New Baseline for Front-End DevsRebecca Murphey
 
Mulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitMulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitRebecca Murphey
 
jQuery Namespace Pattern
jQuery Namespace PatternjQuery Namespace Pattern
jQuery Namespace PatternDiego Fleury
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkG Woo
 

La actualidad más candente (20)

Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and Reactive
 
Writing Clean Code in Swift
Writing Clean Code in SwiftWriting Clean Code in Swift
Writing Clean Code in Swift
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
Js hacks
Js hacksJs hacks
Js hacks
 
Your JavaScript Library
Your JavaScript LibraryYour JavaScript Library
Your JavaScript Library
 
Fact, Fiction, and FP
Fact, Fiction, and FPFact, Fiction, and FP
Fact, Fiction, and FP
 
Lenses
LensesLenses
Lenses
 
A New Baseline for Front-End Devs
A New Baseline for Front-End DevsA New Baseline for Front-End Devs
A New Baseline for Front-End Devs
 
Mulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitMulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development Toolkit
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
jQuery Namespace Pattern
jQuery Namespace PatternjQuery Namespace Pattern
jQuery Namespace Pattern
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php framework
 

Similar a Functional programming using underscorejs

TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairMark
 
JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)Anders Jönsson
 
Mongoskin - Guilin
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - GuilinJackson Tian
 
Enterprise workflow with Apps Script
Enterprise workflow with Apps ScriptEnterprise workflow with Apps Script
Enterprise workflow with Apps Scriptccherubino
 
FunctionalJS - George Shevtsov
FunctionalJS - George ShevtsovFunctionalJS - George Shevtsov
FunctionalJS - George ShevtsovGeorgiy Shevtsov
 
1. George Shevtsov - Functional JavaScript
1. George Shevtsov - Functional JavaScript1. George Shevtsov - Functional JavaScript
1. George Shevtsov - Functional JavaScriptInnovecs
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScriptLuis Atencio
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsJarod Ferguson
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on AndroidSven Haiges
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascriptkvangork
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScriptkvangork
 
Gearmam, from the_worker's_perspective copy
Gearmam, from the_worker's_perspective copyGearmam, from the_worker's_perspective copy
Gearmam, from the_worker's_perspective copyBrian Aker
 
Gearmam, from the_worker's_perspective copy
Gearmam, from the_worker's_perspective copyGearmam, from the_worker's_perspective copy
Gearmam, from the_worker's_perspective copyBrian Aker
 
Building High Performance Web Applications and Sites
Building High Performance Web Applications and SitesBuilding High Performance Web Applications and Sites
Building High Performance Web Applications and Sitesgoodfriday
 
Developing web-apps like it's 2013
Developing web-apps like it's 2013Developing web-apps like it's 2013
Developing web-apps like it's 2013Laurent_VB
 

Similar a Functional programming using underscorejs (20)

TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
 
JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)
 
mobl
moblmobl
mobl
 
Mongoskin - Guilin
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - Guilin
 
Txjs
TxjsTxjs
Txjs
 
Enterprise workflow with Apps Script
Enterprise workflow with Apps ScriptEnterprise workflow with Apps Script
Enterprise workflow with Apps Script
 
FunctionalJS - George Shevtsov
FunctionalJS - George ShevtsovFunctionalJS - George Shevtsov
FunctionalJS - George Shevtsov
 
1. George Shevtsov - Functional JavaScript
1. George Shevtsov - Functional JavaScript1. George Shevtsov - Functional JavaScript
1. George Shevtsov - Functional JavaScript
 
Groovy
GroovyGroovy
Groovy
 
ES6, WTF?
ES6, WTF?ES6, WTF?
ES6, WTF?
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
 
Gearmam, from the_worker's_perspective copy
Gearmam, from the_worker's_perspective copyGearmam, from the_worker's_perspective copy
Gearmam, from the_worker's_perspective copy
 
Gearmam, from the_worker's_perspective copy
Gearmam, from the_worker's_perspective copyGearmam, from the_worker's_perspective copy
Gearmam, from the_worker's_perspective copy
 
Building High Performance Web Applications and Sites
Building High Performance Web Applications and SitesBuilding High Performance Web Applications and Sites
Building High Performance Web Applications and Sites
 
Developing web-apps like it's 2013
Developing web-apps like it's 2013Developing web-apps like it's 2013
Developing web-apps like it's 2013
 

Más de 偉格 高

Mobile web application
Mobile web applicationMobile web application
Mobile web application偉格 高
 
Web Developer Tools for ICOS 2013
Web Developer Tools for ICOS 2013Web Developer Tools for ICOS 2013
Web Developer Tools for ICOS 2013偉格 高
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS偉格 高
 
Vim Plugin Deployment
Vim Plugin DeploymentVim Plugin Deployment
Vim Plugin Deployment偉格 高
 
WAI-ARIA is More Than Accessibility
WAI-ARIA is More Than AccessibilityWAI-ARIA is More Than Accessibility
WAI-ARIA is More Than Accessibility偉格 高
 
TOSSUG HTML5 讀書會 新標籤與表單
TOSSUG HTML5 讀書會 新標籤與表單TOSSUG HTML5 讀書會 新標籤與表單
TOSSUG HTML5 讀書會 新標籤與表單偉格 高
 
Html5 New Features
Html5 New FeaturesHtml5 New Features
Html5 New Features偉格 高
 

Más de 偉格 高 (12)

node ffi
node ffinode ffi
node ffi
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
Web Component
Web ComponentWeb Component
Web Component
 
Mobile web application
Mobile web applicationMobile web application
Mobile web application
 
Web Developer Tools for ICOS 2013
Web Developer Tools for ICOS 2013Web Developer Tools for ICOS 2013
Web Developer Tools for ICOS 2013
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS
 
Vim Plugin Deployment
Vim Plugin DeploymentVim Plugin Deployment
Vim Plugin Deployment
 
WAI-ARIA is More Than Accessibility
WAI-ARIA is More Than AccessibilityWAI-ARIA is More Than Accessibility
WAI-ARIA is More Than Accessibility
 
WAI-ARIA
WAI-ARIAWAI-ARIA
WAI-ARIA
 
TOSSUG HTML5 讀書會 新標籤與表單
TOSSUG HTML5 讀書會 新標籤與表單TOSSUG HTML5 讀書會 新標籤與表單
TOSSUG HTML5 讀書會 新標籤與表單
 
Html5 New Features
Html5 New FeaturesHtml5 New Features
Html5 New Features
 
Base2
Base2Base2
Base2
 

Functional programming using underscorejs