SlideShare a Scribd company logo
Sexier Javascript 
With Lodash & ES6 
By 
Omry Nachman [omry@wix.com]
Agenda 
Declarative Vs. Imperative 
Functional Programming 
Harness ES6 and Lodash 
Functional best practices
Declarative 
Programming 
Declarative programming 
focuses on the what 
* * * 
Imperative programming 
focuses on the how
Imperative Code 
function followers(person, data) { 
var result = []; 
for (var i=0 ; i<data.length ; i++) { 
if (data[i].follows.indexOf(person._id) >= 0 ) { 
result.push(data[i]); 
} 
} 
return result; 
}
Declarative Code 
var followers = (person, data) => _.where(data, {follows: [person._id]})
Functional Programming
“In mathematics, a function is a relation between a set 
of inputs <domain> and a set of permissible outputs 
<range> with the property that each input is related 
to exactly one output.” 
Wikipedia 
http://en.wikipedia.org/wiki/Function_%28mathematics%29
Functions 
f(x)=2x+3 
round(x) 
person => person’s mother
Not (Math) 
Functions 
person => person’s child 
function add(x) { 
this.sum += x; 
return this.sum; 
} 
function getSum(){ 
return this.sum; 
}
Math => Code 
Advantages of pure (===math style) functions 
Constant output per input => Cacheable, Parallelizable 
Composable => Single responsibility, Reusability, Great 
for DSLs 
Known domain and range => Simplicity, Consistency 
No side effects => Easy to test, Easy to reproduce
Enough Theory 
Let’s look at some code patterns
Functional Approach 
minFollowers = (min, data) => _.where(data, 
person => followers(person, data) >= min) 
maxFollowers = (max, data) => _.where(data, 
person => followers(person, data) >= max) 
rangeFollowers = (min, max, data) => 
maxFollowers(max, minFollowers(min, data))
Composition & Partial 
rangeFollowers = (min, max, data) => 
_.compose( 
_.partial(maxFollowers, max), 
_.partial(minFollowers, min) 
)
DSLs 
Isn’t this syntax nice? 
minFollowers = (min, data) => 
followersCount(isMoreThen(min), data) 
maxFollowers = (max, data) => 
followersCount(lessThen(min), data) 
rangeFollowers = (min, max, data) => 
followersCount(inRange(min, max), data)
DSLs 
It requires this bootstrapping: 
moreThen = min => (val => val >= min) 
lessThen = max => (val => value <= max), 
inRange = (min, max) => (val => val>= min && val <= max) 
followersCount = (filter, data) => _.where(data, 
person => filter(getFollowersOf(data, person._id)) 
So don’t get curried way…
Memoize 
Pure functions can be memorised (cached) per input, 
trading CPU for memory 
// O(2^n) 
var fib = n => (n<2) ? 1 : fib(n-2) + fib(n-1) 
//O(n) 
var fib = _.memoize(n => (n<2) ? 1 : fib(n-2) + fib(n-1)) 
By default, the first argument is the cache key, 
but it can be customised
Immutability & Statelessness 
No mutation, no side effects 
setName = (obj, name) => { 
obj.name = name; 
} 
withName = (obj, name) => 
_.merge(obj, {name: name})
Let’s Mess With Some Data 
The functional way
Group Common Names 
Say we want to create a histogram of people’s names 
[{name:{first:’David’, last:’Jones’},…}, 
{name:{first:’David’, last:’Kulas’},…}, 
{name:{first:’Mia’, last:’Angelo’},…}, 
{name:{first:’Lucia’, last:’Stroman’},…}] 
histogram = _(data). 
groupBy(person => person.name.first). 
mapValues(people => people.length). 
transform( 
(acc, count, name) => 
acc[count] = _.union(acc[count], [name])). 
value(); 
{ 
1:[‘Lucia’, ‘Mia’] 
2:[‘David] 
}
Group Common * 
histogram = (data, predicate) => _(data). 
groupBy(predicate). 
mapValues(people => people.length). 
transform( 
(acc, count, name) => 
acc[count] = _.union(acc[count], [name])). 
value(); 
So now we can do 
histogram(data, ’age’) 
histogram(data, _.partialRight(followers, data))
Best Practices 
*And Worst Practices
Good Idea 
Access App State In One Place 
var appState = {…} // hidden by closure, class or module 
updateData = data => { // privileged method 
appState.data = data 
updateView(appState.data, appState.renderSettings, setView) 
} 
updateState = newPartialState => { // privileged method 
appState = _merge(appState, newPartialState) 
updateView(appState.data, appState.renderSettings, setView) 
} 
goGetData().then(updateData) 
app.addEvenrListener(‘state-change’, updateState)
Bad Idea 
Using functional style to 
make your code obscured 
var myFunc = isVery => 
obscured => (because, i) => 
(just, learned) => about => 
functional => programming (and, 
arrow, notation) => but => 
maybe => iShould => 
breakeItDown.toSmaller.function 
s
Questions?!?

More Related Content

PDF
Lodash js
PDF
Chaining and function composition with lodash / underscore
PDF
Python dictionary : past, present, future
PDF
Developing Applications with MySQL and Java for beginners
PDF
Symfony2 and Doctrine2 Integration
PDF
Modern Application Foundations: Underscore and Twitter Bootstrap
PPTX
Js types
ODP
Patterns for slick database applications
Lodash js
Chaining and function composition with lodash / underscore
Python dictionary : past, present, future
Developing Applications with MySQL and Java for beginners
Symfony2 and Doctrine2 Integration
Modern Application Foundations: Underscore and Twitter Bootstrap
Js types
Patterns for slick database applications

What's hot (20)

PPTX
jQuery
PDF
Using Scala Slick at FortyTwo
PPTX
Sequelize
PPTX
11. session 11 functions and objects
PDF
Variables, expressions, standard types
KEY
Indexing thousands of writes per second with redis
PDF
iRODS Rule Language Cheat Sheet
PPTX
ActionScript3 collection query API proposal
PPT
Basic Object Oriented Concepts
PDF
Java script objects 1
 
PDF
Swipe 2011 - iOS Gems
PPT
Spsl v unit - final
PPTX
Python data structures
PPTX
Prototype Framework
PDF
Your code sucks, let's fix it
PDF
Metaprogramovanie #1
PPT
Oop lecture9 13
PDF
RxSwift 시작하기
PPTX
Indexing documents
jQuery
Using Scala Slick at FortyTwo
Sequelize
11. session 11 functions and objects
Variables, expressions, standard types
Indexing thousands of writes per second with redis
iRODS Rule Language Cheat Sheet
ActionScript3 collection query API proposal
Basic Object Oriented Concepts
Java script objects 1
 
Swipe 2011 - iOS Gems
Spsl v unit - final
Python data structures
Prototype Framework
Your code sucks, let's fix it
Metaprogramovanie #1
Oop lecture9 13
RxSwift 시작하기
Indexing documents
Ad

Similar to Functional es6 (20)

PDF
MongoDB With Style
PDF
Monads and Monoids by Oleksiy Dyagilev
PDF
Артём Акуляков - F# for Data Analysis
PDF
A bit about Scala
PDF
Patterns in Terraform 12+13: Data, Transformations and Resources
PDF
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
PDF
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
PDF
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
PDF
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
PDF
Big Data LDN 2017: From Zero to AI in 30 Minutes
PDF
An introduction into Spring Data
PPTX
Basics of Python programming (part 2)
PPTX
DataStructures in Pyhton Pandas and numpy.pptx
PPT
Xm lparsers
PDF
PDF
Everything is composable
ODP
Querying your database in natural language by Daniel Moisset PyData SV 2014
ODP
Quepy
PDF
React.js Basics - ConvergeSE 2015
MongoDB With Style
Monads and Monoids by Oleksiy Dyagilev
Артём Акуляков - F# for Data Analysis
A bit about Scala
Patterns in Terraform 12+13: Data, Transformations and Resources
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Big Data LDN 2017: From Zero to AI in 30 Minutes
An introduction into Spring Data
Basics of Python programming (part 2)
DataStructures in Pyhton Pandas and numpy.pptx
Xm lparsers
Everything is composable
Querying your database in natural language by Daniel Moisset PyData SV 2014
Quepy
React.js Basics - ConvergeSE 2015
Ad

Recently uploaded (20)

PPTX
Slides PPTX World Game (s) Eco Economic Epochs.pptx
PDF
Best Practices for Testing and Debugging Shopify Third-Party API Integrations...
DOCX
Unit-3 cyber security network security of internet system
PPTX
PptxGenJS_Demo_Chart_20250317130215833.pptx
PPT
isotopes_sddsadsaadasdasdasdasdsa1213.ppt
PPTX
E -tech empowerment technologies PowerPoint
PPT
Design_with_Watersergyerge45hrbgre4top (1).ppt
PDF
Introduction to the IoT system, how the IoT system works
PDF
WebRTC in SignalWire - troubleshooting media negotiation
PDF
Tenda Login Guide: Access Your Router in 5 Easy Steps
PPTX
INTERNET------BASICS-------UPDATED PPT PRESENTATION
PPTX
Introduction about ICD -10 and ICD11 on 5.8.25.pptx
PDF
Cloud-Scale Log Monitoring _ Datadog.pdf
PDF
💰 𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓 💰
PPTX
Module 1 - Cyber Law and Ethics 101.pptx
PPTX
Digital Literacy And Online Safety on internet
PPTX
CHE NAA, , b,mn,mblblblbljb jb jlb ,j , ,C PPT.pptx
PPT
tcp ip networks nd ip layering assotred slides
PPTX
522797556-Unit-2-Temperature-measurement-1-1.pptx
PPTX
international classification of diseases ICD-10 review PPT.pptx
Slides PPTX World Game (s) Eco Economic Epochs.pptx
Best Practices for Testing and Debugging Shopify Third-Party API Integrations...
Unit-3 cyber security network security of internet system
PptxGenJS_Demo_Chart_20250317130215833.pptx
isotopes_sddsadsaadasdasdasdasdsa1213.ppt
E -tech empowerment technologies PowerPoint
Design_with_Watersergyerge45hrbgre4top (1).ppt
Introduction to the IoT system, how the IoT system works
WebRTC in SignalWire - troubleshooting media negotiation
Tenda Login Guide: Access Your Router in 5 Easy Steps
INTERNET------BASICS-------UPDATED PPT PRESENTATION
Introduction about ICD -10 and ICD11 on 5.8.25.pptx
Cloud-Scale Log Monitoring _ Datadog.pdf
💰 𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓 💰
Module 1 - Cyber Law and Ethics 101.pptx
Digital Literacy And Online Safety on internet
CHE NAA, , b,mn,mblblblbljb jb jlb ,j , ,C PPT.pptx
tcp ip networks nd ip layering assotred slides
522797556-Unit-2-Temperature-measurement-1-1.pptx
international classification of diseases ICD-10 review PPT.pptx

Functional es6

  • 1. Sexier Javascript With Lodash & ES6 By Omry Nachman [omry@wix.com]
  • 2. Agenda Declarative Vs. Imperative Functional Programming Harness ES6 and Lodash Functional best practices
  • 3. Declarative Programming Declarative programming focuses on the what * * * Imperative programming focuses on the how
  • 4. Imperative Code function followers(person, data) { var result = []; for (var i=0 ; i<data.length ; i++) { if (data[i].follows.indexOf(person._id) >= 0 ) { result.push(data[i]); } } return result; }
  • 5. Declarative Code var followers = (person, data) => _.where(data, {follows: [person._id]})
  • 7. “In mathematics, a function is a relation between a set of inputs <domain> and a set of permissible outputs <range> with the property that each input is related to exactly one output.” Wikipedia http://en.wikipedia.org/wiki/Function_%28mathematics%29
  • 8. Functions f(x)=2x+3 round(x) person => person’s mother
  • 9. Not (Math) Functions person => person’s child function add(x) { this.sum += x; return this.sum; } function getSum(){ return this.sum; }
  • 10. Math => Code Advantages of pure (===math style) functions Constant output per input => Cacheable, Parallelizable Composable => Single responsibility, Reusability, Great for DSLs Known domain and range => Simplicity, Consistency No side effects => Easy to test, Easy to reproduce
  • 11. Enough Theory Let’s look at some code patterns
  • 12. Functional Approach minFollowers = (min, data) => _.where(data, person => followers(person, data) >= min) maxFollowers = (max, data) => _.where(data, person => followers(person, data) >= max) rangeFollowers = (min, max, data) => maxFollowers(max, minFollowers(min, data))
  • 13. Composition & Partial rangeFollowers = (min, max, data) => _.compose( _.partial(maxFollowers, max), _.partial(minFollowers, min) )
  • 14. DSLs Isn’t this syntax nice? minFollowers = (min, data) => followersCount(isMoreThen(min), data) maxFollowers = (max, data) => followersCount(lessThen(min), data) rangeFollowers = (min, max, data) => followersCount(inRange(min, max), data)
  • 15. DSLs It requires this bootstrapping: moreThen = min => (val => val >= min) lessThen = max => (val => value <= max), inRange = (min, max) => (val => val>= min && val <= max) followersCount = (filter, data) => _.where(data, person => filter(getFollowersOf(data, person._id)) So don’t get curried way…
  • 16. Memoize Pure functions can be memorised (cached) per input, trading CPU for memory // O(2^n) var fib = n => (n<2) ? 1 : fib(n-2) + fib(n-1) //O(n) var fib = _.memoize(n => (n<2) ? 1 : fib(n-2) + fib(n-1)) By default, the first argument is the cache key, but it can be customised
  • 17. Immutability & Statelessness No mutation, no side effects setName = (obj, name) => { obj.name = name; } withName = (obj, name) => _.merge(obj, {name: name})
  • 18. Let’s Mess With Some Data The functional way
  • 19. Group Common Names Say we want to create a histogram of people’s names [{name:{first:’David’, last:’Jones’},…}, {name:{first:’David’, last:’Kulas’},…}, {name:{first:’Mia’, last:’Angelo’},…}, {name:{first:’Lucia’, last:’Stroman’},…}] histogram = _(data). groupBy(person => person.name.first). mapValues(people => people.length). transform( (acc, count, name) => acc[count] = _.union(acc[count], [name])). value(); { 1:[‘Lucia’, ‘Mia’] 2:[‘David] }
  • 20. Group Common * histogram = (data, predicate) => _(data). groupBy(predicate). mapValues(people => people.length). transform( (acc, count, name) => acc[count] = _.union(acc[count], [name])). value(); So now we can do histogram(data, ’age’) histogram(data, _.partialRight(followers, data))
  • 21. Best Practices *And Worst Practices
  • 22. Good Idea Access App State In One Place var appState = {…} // hidden by closure, class or module updateData = data => { // privileged method appState.data = data updateView(appState.data, appState.renderSettings, setView) } updateState = newPartialState => { // privileged method appState = _merge(appState, newPartialState) updateView(appState.data, appState.renderSettings, setView) } goGetData().then(updateData) app.addEvenrListener(‘state-change’, updateState)
  • 23. Bad Idea Using functional style to make your code obscured var myFunc = isVery => obscured => (because, i) => (just, learned) => about => functional => programming (and, arrow, notation) => but => maybe => iShould => breakeItDown.toSmaller.function s