SlideShare a Scribd company logo
1 of 35
Download to read offline
Composition
Something something Mozart
I'm Josh Mock.
I'm @joshmock on all of the things.
Except email, that's josh@joshmock.com.
So original, right?
What is composition?
Combining simple objects in code to make
more complex ones.
How do I compose things?
Find repeated patterns or duplications in your
code and refactor them into reusable parts.
A simple example
var obj1 = {
message: 'hello world!',
sayHi: function () {
alert(this.message);
}
};
var obj2 = {
message: 'hey!',
sayHi: function () {
alert(this.message);
}
};
obj1.sayHi(); // 'hello world!'
obj2.sayHi(); // 'hey!'
A simple example
var obj1 = { message: 'hello world!' };
var obj2 = { message: 'hey!' };
var alerter = {
sayHi: function () {
alert(this.message);
}
};
obj1 = _.extend(obj1, alerter);
obj2 = _.extend(obj2, alerter);
obj1.sayHi(); // 'hello world!'
obj2.sayHi(); // 'hey!'
● Maximize code reuse
● Use objects without classes
● Avoid traps of single-parent inheritance
Mixins
Mixins in the wild
● Marionette Behaviors
● Bootstrap CSS classes
● Hapi plugins
Underscore.js
_.each(array, function) : Loop over each item in an array
_.map(array, function) : Reformat each item in an array
_.filter(array, function) : Make a new array containing only items that pass a test
_.reduce(array, function, start) : Calculate a single value from an array of items
Underscore.js
_.chain(myArray)
.map(/* reformat items */)
.filter(/* pull out items you don't need */)
.reduce(/* crunch down to a single value */)
.value();
myArray
.map(/* reformat items */)
.filter(/* pull out items you don't need */)
.reduce(/* crunch down to a single value */)
You can do this in plain JS too
mapped = map(..., my_array)
filtered = filter(..., mapped)
final_val = reduce(..., filtered)
And in Python
my_array.map(...).reduce(...).reduce(...)
...and Ruby
var myList = [
{ count: 17 },
{ count: 22 },
{ count: 3 },
{ count: 18 }
];
var sum = 0;
for (var i = 0; i < myList.length; i++) {
sum += myList[i].count;
}
Function reuse
Function reuse
function getCount (value) {
return value.count;
}
function noOdds (value) {
return value % 2 === 0;
}
function add (value1, value2) {
return value1 + value2;
}
Function reuse
var myList = [
{ count: 17 },
{ count: 22 },
{ count: 3 },
{ count: 18 }
];
var sum = _.chain(myList)
.map(getCount)
.filter(noOdds)
.reduce(add)
.value();
each / map / filter / reduce
function getForms (data) {
var forms = data.aggregate.all[window.location.protocol + '//' + window.location.host];
var formsOut = [];
var url = window.location.toString();
var formsToExclude = [];
for (var key in data.aggregate.exclude) {
if (new RegExp('^' + key + '$').test(url)) {
formsToExclude = formsToExclude.concat(data.aggregate.exclude[key]);
}
}
var filteredForms = [];
for (value in forms) {
if (formsToExclude.indexOf(value) === -1) {
filteredForms.push(value);
}
}
for (key in data.aggregate.include) {
if (new RegExp('^' + key + '$').test(url)) {
forms = forms.concat(data.aggregate.include[key]);
}
}
return formsOut;
}
each / map / filter / reduce
function getForms (data) {
var forms = data.aggregate.all[window.location.protocol + '//' + window.location.host];
var url = window.location.toString();
var formsToExclude = [];
_.each(data.aggregate.exclude, function (val, key) {
if (new RegExp('^' + key + '$').test(url)) {
formsToExclude = formsToExclude.concat(val);
}
});
forms = _.filter(forms, function (val) {
return formsToExclude.indexOf(val) === -1;
});
_.each(data.aggregate.include, function (val, key) {
if (new RegExp('^' + key + '$').test(url)) {
forms = forms.concat(val);
}
});
return forms || [];
}
each / map / filter / reduce
● Small, single-purpose functions
● Maintainable
● Reusable
● Easy to test
● Universally understandable
Web components
● HTML is perfectly composable:
<form>
<input type="text">
<button>click me</button>
</form>
● Custom elements = infinite composition possibilities!
$ cat index.js | grep 'var' | wc -l
5
Unix piping
"This is the Unix philosophy: Write programs
that do one thing and do it well. Write programs
to work together. Write programs to handle text
streams, because that is a universal interface."
- Doug McIlroy
The Unix Philosophy
A Node.js API to read in data, act on it in
chunks, then then write out to a new stream.
Node streams
Node streams
gulp.task('scripts', function() {
return gulp.src('js/*.js')
.pipe(concat('all.js'))
.pipe(gulp.dest('dist'))
.pipe(rename('all.min.js'))
.pipe(uglify())
.pipe(gulp.dest('dist'));
});
Functional reactive programming
Act on DOM events as though they were
streams or arrays.
Microservices
"...an approach to developing a single
application as a suite of small services, each
running in its own process."
Emma, 5 years ago
Emma, 2.5 years ago
Emma, now-ish
● Stop building behemoths
● Build single-purpose tools
● Chain them together to do big things
TL;DR
"One thing well."
@joshmock
josh@joshmock.com

More Related Content

What's hot (19)

Include
IncludeInclude
Include
 
Swift - Krzysztof Skarupa
Swift -  Krzysztof SkarupaSwift -  Krzysztof Skarupa
Swift - Krzysztof Skarupa
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
 
Swift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDCSwift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDC
 
Writing a compiler in go
Writing a compiler in goWriting a compiler in go
Writing a compiler in go
 
Bind me if you can
Bind me if you canBind me if you can
Bind me if you can
 
2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js
 
Introduction of ES2015
Introduction of ES2015Introduction of ES2015
Introduction of ES2015
 
Class ‘increment’
Class ‘increment’Class ‘increment’
Class ‘increment’
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
 
20151224-games
20151224-games20151224-games
20151224-games
 
Introduction to cron queue
Introduction to cron queueIntroduction to cron queue
Introduction to cron queue
 
completion_proc and history
completion_proc and historycompletion_proc and history
completion_proc and history
 
Php 5.6
Php 5.6Php 5.6
Php 5.6
 
Groovy
GroovyGroovy
Groovy
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
Fun with functions
Fun with functionsFun with functions
Fun with functions
 
Javascript this keyword
Javascript this keywordJavascript this keyword
Javascript this keyword
 

Similar to Composition in JavaScript

ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Mongoskin - Guilin
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - GuilinJackson Tian
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolveXSolve
 
Functional Javascript
Functional JavascriptFunctional Javascript
Functional Javascriptguest4d57e6
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairMark
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Calvin Cheng
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs偉格 高
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
 
From Javascript To Haskell
From Javascript To HaskellFrom Javascript To Haskell
From Javascript To Haskellujihisa
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 

Similar to Composition in JavaScript (20)

Javascript
JavascriptJavascript
Javascript
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Mongoskin - Guilin
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - Guilin
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
 
Functional Javascript
Functional JavascriptFunctional Javascript
Functional Javascript
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
8558537werr.pptx
8558537werr.pptx8558537werr.pptx
8558537werr.pptx
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
 
Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
 
From Javascript To Haskell
From Javascript To HaskellFrom Javascript To Haskell
From Javascript To Haskell
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
 
ES6, WTF?
ES6, WTF?ES6, WTF?
ES6, WTF?
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 

Recently uploaded

Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benonimasabamasaba
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxAnnaArtyushina1
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2
 

Recently uploaded (20)

Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 

Composition in JavaScript

  • 2. I'm Josh Mock. I'm @joshmock on all of the things. Except email, that's josh@joshmock.com. So original, right?
  • 3.
  • 4.
  • 5. What is composition? Combining simple objects in code to make more complex ones.
  • 6. How do I compose things? Find repeated patterns or duplications in your code and refactor them into reusable parts.
  • 7. A simple example var obj1 = { message: 'hello world!', sayHi: function () { alert(this.message); } }; var obj2 = { message: 'hey!', sayHi: function () { alert(this.message); } }; obj1.sayHi(); // 'hello world!' obj2.sayHi(); // 'hey!'
  • 8. A simple example var obj1 = { message: 'hello world!' }; var obj2 = { message: 'hey!' }; var alerter = { sayHi: function () { alert(this.message); } }; obj1 = _.extend(obj1, alerter); obj2 = _.extend(obj2, alerter); obj1.sayHi(); // 'hello world!' obj2.sayHi(); // 'hey!'
  • 9. ● Maximize code reuse ● Use objects without classes ● Avoid traps of single-parent inheritance Mixins
  • 10. Mixins in the wild ● Marionette Behaviors ● Bootstrap CSS classes ● Hapi plugins
  • 11. Underscore.js _.each(array, function) : Loop over each item in an array _.map(array, function) : Reformat each item in an array _.filter(array, function) : Make a new array containing only items that pass a test _.reduce(array, function, start) : Calculate a single value from an array of items
  • 12. Underscore.js _.chain(myArray) .map(/* reformat items */) .filter(/* pull out items you don't need */) .reduce(/* crunch down to a single value */) .value();
  • 13. myArray .map(/* reformat items */) .filter(/* pull out items you don't need */) .reduce(/* crunch down to a single value */) You can do this in plain JS too
  • 14. mapped = map(..., my_array) filtered = filter(..., mapped) final_val = reduce(..., filtered) And in Python
  • 16. var myList = [ { count: 17 }, { count: 22 }, { count: 3 }, { count: 18 } ]; var sum = 0; for (var i = 0; i < myList.length; i++) { sum += myList[i].count; } Function reuse
  • 17. Function reuse function getCount (value) { return value.count; } function noOdds (value) { return value % 2 === 0; } function add (value1, value2) { return value1 + value2; }
  • 18. Function reuse var myList = [ { count: 17 }, { count: 22 }, { count: 3 }, { count: 18 } ]; var sum = _.chain(myList) .map(getCount) .filter(noOdds) .reduce(add) .value();
  • 19. each / map / filter / reduce function getForms (data) { var forms = data.aggregate.all[window.location.protocol + '//' + window.location.host]; var formsOut = []; var url = window.location.toString(); var formsToExclude = []; for (var key in data.aggregate.exclude) { if (new RegExp('^' + key + '$').test(url)) { formsToExclude = formsToExclude.concat(data.aggregate.exclude[key]); } } var filteredForms = []; for (value in forms) { if (formsToExclude.indexOf(value) === -1) { filteredForms.push(value); } } for (key in data.aggregate.include) { if (new RegExp('^' + key + '$').test(url)) { forms = forms.concat(data.aggregate.include[key]); } } return formsOut; }
  • 20. each / map / filter / reduce function getForms (data) { var forms = data.aggregate.all[window.location.protocol + '//' + window.location.host]; var url = window.location.toString(); var formsToExclude = []; _.each(data.aggregate.exclude, function (val, key) { if (new RegExp('^' + key + '$').test(url)) { formsToExclude = formsToExclude.concat(val); } }); forms = _.filter(forms, function (val) { return formsToExclude.indexOf(val) === -1; }); _.each(data.aggregate.include, function (val, key) { if (new RegExp('^' + key + '$').test(url)) { forms = forms.concat(val); } }); return forms || []; }
  • 21. each / map / filter / reduce ● Small, single-purpose functions ● Maintainable ● Reusable ● Easy to test ● Universally understandable
  • 22. Web components ● HTML is perfectly composable: <form> <input type="text"> <button>click me</button> </form> ● Custom elements = infinite composition possibilities!
  • 23. $ cat index.js | grep 'var' | wc -l 5 Unix piping
  • 24. "This is the Unix philosophy: Write programs that do one thing and do it well. Write programs to work together. Write programs to handle text streams, because that is a universal interface." - Doug McIlroy The Unix Philosophy
  • 25. A Node.js API to read in data, act on it in chunks, then then write out to a new stream. Node streams
  • 26. Node streams gulp.task('scripts', function() { return gulp.src('js/*.js') .pipe(concat('all.js')) .pipe(gulp.dest('dist')) .pipe(rename('all.min.js')) .pipe(uglify()) .pipe(gulp.dest('dist')); });
  • 27. Functional reactive programming Act on DOM events as though they were streams or arrays.
  • 28. Microservices "...an approach to developing a single application as a suite of small services, each running in its own process."
  • 32. ● Stop building behemoths ● Build single-purpose tools ● Chain them together to do big things TL;DR
  • 34.