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 expressionvar f = function () { /*...*/ };
Higher Order Function• Function takes or return functions• ex: event listener
http://www.flickr.com/photos/78428166@N00/6036104277/
Take a LookExamples from ‘Pure, functional JavaScript’                          http://cjohansen.no/talks/2012/sdc-functio...
[    {         name: Gates,         gender: M,         org: M$    },    {         name: Peter         gender: M,         o...
"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.len...
[    {         name: Gates,         gender: M,         org: M$    },    {         name: Peter         gender: M,         o...
[    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: <...
<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; ...
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", {...
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);...
http://www.flickr.com/photos/jackhynes/519904699/
buildSummary: function () {    return div(this.components.map(function (component) {         return p(component.getSummary...
buildSummary: function () {    return div(this.components.map(function (component) {         return p(component.getSummary...
buildSummary: function () {    return div(this.components.map(function (component) {         return p(component.getSummary...
buildSummary: function () {    return div(this.components.map(function (component) {         return p(component.getSummary...
buildSummary: function () {    return div(this.components.        map(function (component) {             return component....
function func(name) {    return function (object) {        return object[name]();    };}
buildSummary: function () {    return div(this.components.        map(func("getSummary")).        map(function (summary) {...
buildSummary: function () {    return div(this.components.        map(func("getSummary")).        map(prop("text")).      ...
buildSummary: function () {    return div(this.components.        map(func("getSummary")).        map(prop("text")).      ...
var summarize = compose([p, prop("text"), func("getSummary")]);
var callGetSummary = func("getSummary");var getText = prop("text");var summarize = compose([p, getText, callGetSummary]);/...
buildSummary: function () {    var summarize = compose([p, prop("text"), func("getSummary")]);    return div(this.componen...
var summarize = compose([p, prop("text"), func("getSummary")]);// ...buildSummary: function () {    return div(this.compon...
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 ...
Lo-Dash• Will talk later
cull.js• by Christian Johansen and Magnar Sveen• “Cull is a toolbelt for writing functional  javascript.”• Used in the exa...
LiveScript & prelude.ls• by George Zahariev• A new compile to JavaScript language fork  from Coco• Stay in this room until...
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) {      ...
var str = "Mentioned by " + _(tweeps)  .chain()  .map(function (t) { return t.name; })  .reduce(function (memo, name, i) {...
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, ...
_.partialvar greet = function(greeting, name) {    return greeting +   + name;};var hi = _.partial(greet, hi);hi(moe);// !...
_.resultvar object = {   cheese: crumpets,   stuff: function () {     return nonsense;   }};_.result(object, cheese);// ! ...
With Lo-Dash
var summarize = compose([p, prop("text"), func("getSummary")]);// ...buildSummary: function () {    return div(map(summari...
var summarize = _.compose(    p,    _.partialRight(_.result, name),    _.partialRight(_.result, getSummary));// ...buildSu...
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
ReferencesFurther 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 otN        http://shop.oreilly.com/product/0636920028857.do
Questions?      http://www.flickr.com/photos/roman/5610736/
Upcoming SlideShare
Loading in...5
×

Functional programming using underscorejs

627

Published on

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
627
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
6
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Functional programming using underscorejs

  1. 1. Functional Programming using Underscore.js othree @ OSDC 2013
  2. 2. me• @othree• https://blog.othree.net
  3. 3. me• PhD Candidate• Front End Engineer• On the way learning good from functional programming languages
  4. 4. Function of Functional Language• Pure function• First class citizen• Higher order function• ...
  5. 5. Pure Function• Side effect free• Same input, same output• ex: trigonometric functions
  6. 6. First Class Citizen• Function like variable• ex: function expressionvar f = function () { /*...*/ };
  7. 7. Higher Order Function• Function takes or return functions• ex: event listener
  8. 8. http://www.flickr.com/photos/78428166@N00/6036104277/
  9. 9. Take a LookExamples from ‘Pure, functional JavaScript’ http://cjohansen.no/talks/2012/sdc-functional/
  10. 10. [ { name: Gates, gender: M, org: M$ }, { name: Peter gender: M, org: Hㄒㄈ }]
  11. 11. "Mentioned by Gates, Peter, Jobs"
  12. 12. var str = "Mentioned by ";for (var i = 0, l = tweeps.length; i < l; ++i) { str += tweeps[i].name; if (i < tweeps.length - 1) { str += ", "; }}
  13. 13. [ { name: Gates, gender: M, org: M$ }, { name: Peter gender: M, org: Hㄒㄈ }]
  14. 14. [ Gates, Peter]
  15. 15. var names = [];for (var i = 0, l = tweeps.length; i < l; ++i) { names.push(tweeps[i].name);}
  16. 16. var str = "Mentioned by " + names.join(", ");
  17. 17. var names = tweeps.map(function (tweep) { return tweep.name;});
  18. 18. var names = tweeps.map(function (t) { return t.name; });
  19. 19. var str = "Mentioned by " + tweeps.map(function (t) { return t.name;}).join(", ");
  20. 20. function prop(name) { return function (object) { return object[name]; };}
  21. 21. var str = "Mentioned by " + tweeps.map(prop("name")).join(", ");
  22. 22. Case 2
  23. 23. [ { getSummary: function () { return { text: Summaries, html: <p>Summaries</p> }; } }, { getSummary: function () { return {text: Summaried}; } }, ...]
  24. 24. <div> <p>Summaries</p> <p>Summaried</p> <p>Summary</p></div>
  25. 25. 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;}
  26. 26. DOM functions
  27. 27. var ul = cull.dom.el("ul");ul.nodeType === 1 // true https://github.com/culljs/dome/
  28. 28. var ul = cull.dom.el("ul", { className: "bands" });//var li = cull.dom.el("li", "Execration");var ul = cull.dom.el("ul", { className: "bands" }, li);
  29. 29. var ul = cull.partial(cull.dom.el, "ul");var li = cull.partial(cull.dom.el, "li");
  30. 30. ["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);});
  31. 31. http://www.flickr.com/photos/jackhynes/519904699/
  32. 32. buildSummary: function () { return div(this.components.map(function (component) { return p(component.getSummary().text); }));}
  33. 33. buildSummary: function () { return div(this.components.map(function (component) { return p(component.getSummary().text);} })); 1
  34. 34. buildSummary: function () { return div(this.components.map(function (component) { return p(component.getSummary().text);} })); 1 2
  35. 35. buildSummary: function () { return div(this.components.map(function (component) { return p(component.getSummary().text);} })); 3 1 2
  36. 36. buildSummary: function () { return div(this.components. map(function (component) { return component.getSummary(); }).map(function (summary) { return summary.text; }).map(function (text) { return p(text); }));}
  37. 37. function func(name) { return function (object) { return object[name](); };}
  38. 38. buildSummary: function () { return div(this.components. map(func("getSummary")). map(function (summary) { return summary.text; }).map(function (text) { return p(text); }));}
  39. 39. buildSummary: function () { return div(this.components. map(func("getSummary")). map(prop("text")). map(function (text) { return p(text); }));}
  40. 40. buildSummary: function () { return div(this.components. map(func("getSummary")). map(prop("text")). map(p));}
  41. 41. var summarize = compose([p, prop("text"), func("getSummary")]);
  42. 42. 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)))
  43. 43. buildSummary: function () { var summarize = compose([p, prop("text"), func("getSummary")]); return div(this.components.map(summarize));}
  44. 44. var summarize = compose([p, prop("text"), func("getSummary")]);// ...buildSummary: function () { return div(this.components.map(summarize));}
  45. 45. http://www.flickr.com/photos/guerson/5630633727/
  46. 46. Functional Programming in JavaScript
  47. 47. Native• forEach• map/reduce• filter
  48. 48. Functional JavaScript• by Oliver Steele at 2007• First functional JavaScript Library I know
  49. 49. Underscore.js• by Jeremy Ashkenas from DocumentCloud• “Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support”
  50. 50. Lo-Dash• Will talk later
  51. 51. 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
  52. 52. 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
  53. 53. GHCJS• by Hamish Mackenzie,Victor Nazarov, Luite Stegeman• Haskell to JavaScript compiler
  54. 54. Underscore.js• compose• map/reduce• filter• pluck
  55. 55. var str = "Mentioned by " + tweeps.map(prop("name")).join(", ");
  56. 56. var str = "Mentioned by " + _.reduce( _.map(tweeps, function (t) { return t.name; }), function (memo, name, i) { return (i == 0) ? name : memo + , + name; }, );
  57. 57. var str = "Mentioned by " + _(tweeps) .chain() .map(function (t) { return t.name; }) .reduce(function (memo, name, i) { return (i == 0) ? name : memo + , + name; }, ) .value();
  58. 58. var str = "Mentioned by " + _(tweeps) .map(function (t) { return t.name; }) .join(, );
  59. 59. var str = "Mentioned by " + _(tweeps).pluck(name).join(, );
  60. 60. Still Not Enough• curry, partial• prop, func from above example
  61. 61. Lo-Dash
  62. 62. Functional Programming using Underscore.js othree @ OSDC 2013.1
  63. 63. Functional Programming using Underscore.js Lo-Dash othree @ OSDC 2013.1
  64. 64. -
  65. 65. _
  66. 66. _-
  67. 67. _-
  68. 68. What is Lo-Dash• Underscore.js fork by John-David Dalton, Kit Cambridge, and Mathias Bynens
  69. 69. Difference• Better performance• Robust result• Larger file size• AMD supports• Auto chain• More power: cloneDeep, partial, result...
  70. 70. _.partialvar greet = function(greeting, name) { return greeting + + name;};var hi = _.partial(greet, hi);hi(moe);// ! hi moe http://lodash.com/docs#partial
  71. 71. _.resultvar object = { cheese: crumpets, stuff: function () { return nonsense; }};_.result(object, cheese);// ! crumpets_.result(object, stuff);// ! nonsense http://lodash.com/docs#result
  72. 72. With Lo-Dash
  73. 73. var summarize = compose([p, prop("text"), func("getSummary")]);// ...buildSummary: function () { return div(map(summarize), this.components);}
  74. 74. var summarize = _.compose( p, _.partialRight(_.result, name), _.partialRight(_.result, getSummary));// ...buildSummary: function () { return div(_.map(this.components, summarize));}
  75. 75. Performance?
  76. 76. Bad..
  77. 77. http://jsperf.com/for-vs-foreach/71
  78. 78. http://jsperf.com/for-vs-foreach/71
  79. 79. • Take benefits from functional programming• Not change everything to functional• Library helps, ex: lo-dash
  80. 80. ReferencesFurther Readings
  81. 81. http://interglacial.com/hoj/hoj.html
  82. 82. http://cjohansen.no/talks/2012/sdc-functional/
  83. 83. http://kitcambridge.be/blog/say-hello-to-lo-dash/
  84. 84. http://www.slideshare.net/ihower/fp-osdc2012v2
  85. 85. http://shop.oreilly.com/product/9781593272821.do
  86. 86. http://shop.oreilly.com/product/0636920028857.do
  87. 87. d se ea el tR Ye otN http://shop.oreilly.com/product/0636920028857.do
  88. 88. Questions? http://www.flickr.com/photos/roman/5610736/
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×