SlideShare ist ein Scribd-Unternehmen logo
1 von 41
Downloaden Sie, um offline zu lesen
The Awesome Parts
ES6
Domenic Denicola
• http://domenic.me/ (blog)
• https://github.com/domenic
• https://npmjs.org/~domenic
• http://slideshare.net/domenicdenicola
Things I'm doing:
• @esdiscuss onTwitter
• The Promises/A+ spec
• The Extensible Web Manifesto
Why ES6?
“Stagnation on the web is a social ill.”
—Brendan Eich
http://news.ycombinator.com/item?id=4634735
Why JavaScript?
“It is the one language that every vendor is committed to
shipping compatibly. Evolving JS has the leverage to
add/change the semantics of the platform in a way that
no other strategy credibly can.”
—Alex Russell
http://infrequently.org/2013/07/why-javascript/
Why ShouldYou Care?
•It’s not often that, as a programmer, you get
entirely new tools and capabilities in your toolbox.
•Learning Haskell or a Lisp will do it, but then what
do you build?
•ES6 provides a unique opportunity.
The Awesome Parts
•Generators
•Template strings
•Proxies (no time today )
Generators
function zeroOneTwo() {
return [0, 1, 2];
}
var array = zeroOneTwo();
for (var i of array) {
console.log(i);
}
function* zeroOneTwo() {
yield 0;
yield 1;
yield 2;
}
var generator = zeroOneTwo();
for (var i of generator) {
console.log(i);
}
function* zeroOneTwo() {
yield 0;
yield 1;
yield 2;
}
var generator = zeroOneTwo();
for (var i of generator) {
console.log(i);
}
function* zeroOneTwo() {
yield 0;
yield 1;
yield 2;
}
var generator = zeroOneTwo();
generator.next(); // { value: 0, done: false }
generator.next(); // { value: 1, done: false }
generator.next(); // { value: 2, done: false }
generator.next(); // { value: undefined, done: true }
function* fibonacci() {
var previous = 0, current = 1;
while (true) {
var temp = previous;
previous = current;
current = temp + current;
yield current;
}
}
for (var i of fibonacci()) {
console.log(i);
}
// 1, 2, 3, 5, 8, 13, ..., Infinity!
function* take(iterable, numberToTake) {
var i = 0;
for (var taken of iterable) {
if (i++ === numberToTake) {
return;
}
yield taken;
}
}
for (var i of take(fibonacci(), 5)) {
console.log(i);
}
// 1, 2, 3, 5, 8 (and done!)
Lazy sequences
• You can write lazy versions of everything: filter, map, reduce, all those
Underscore.js methods, …
var awesomeEls = filter(domEls, isAwesome);
var awesomeTexts = map(awesomeEls, el => el.textContent);
var awesomeString = reduce(awesomeTexts, (acc, t) => acc + t);
• Since filter and map return generators, nothing happens until reduce, a
non-generator function, executes: then it's all done in a single pass.
• You get the benefits of declarative functional data manipulation without the
performance and memory downsides of intermediate arrays.
Lazy sequences
• You can write lazy versions of everything: filter, map, reduce, all those
Underscore.js methods, …
var awesomeEls = filter(domEls, isAwesome);
var awesomeTexts = map(awesomeEls, el => el.textContent);
var awesomeString = reduce(awesomeTexts, (acc, t) => acc + t);
• Since filter and map return generators, nothing happens until reduce, a
non-generator function, executes: then it's all done in a single pass.
• You get the benefits of declarative functional data manipulation without the
performance and memory downsides of intermediate arrays.
But wait
• Suspending execution until someone calls next() is a powerful feature.
• What if you suspended execution until an async operation finished?
Lots of people are starting to explore this in Node.js right now, leveraging e.g.
promises to turn yield into a kind of “await.”
function* loadUI() {
showLoadingScreen();
yield loadUIDataAsynchronously();
hideLoadingScreen();
}
spawn(loadUI);
This function returns a promise
Write the function spawn so that:
• It calls next() and thus gets the loading promise.
• It waits for the promise to fulfill before calling next() again.
So we've suspended execution until the async operation finishes!
function* loadAndShowData() {
var data = yield loadData();
showData(data);
}
spawn(loadAndShowData);
This function returns a promise for data
You can actually pass data back in to the generator, causing yield to either
return a value or throw an exception inside the generator body.
• So if the promise fulfills, send back its fulfillment value, so that the data
variable ends up holding it.
• But if the promise rejects, tell the generator to throw the rejection
reason as an exception.
function* loadAndShowData() {
showLoadingIndicator();
try {
var data = yield loadData();
showData(data);
} catch (e) {
showError(e);
} finally {
removeLoadingIndicator();
}
}
spawn(loadAndShowData);
function* loadAndShowData() {
showLoadingIndicator();
try {
var data = yield loadData();
showData(data);
} catch (e) {
showError(e);
} finally {
removeLoadingIndicator();
}
}
spawn(loadAndShowData);
Where Can I UseThis?
• Traceur: yes
• Continuum: yes
• Browsers: Chrome, Firefox*
• Node.js: 0.11.3+
es6ify http://thlorenz.github.io/es6ify/
Template Strings
var someArithmetic = `${x} + ${y} = ${x + y}`;
var longString = `long
string
is
long`;
var someArithmetic = `${x} + ${y} = ${x + y}`;
var longString = `long
string
is
long`;
var someArithmetic = `${x} + ${y} = ${x + y}`;
var longString = `long
string
is
long`;
var whatsThis = func`${x} + ${y}n= ${x + y}`;
// becomes
var whatsThis = func(
{
raw: ['', ' + ', 'n = ', ''],
cooked: ['', ' + ', 'n = ', '']
},
x,
y,
x + y
);
var whatsThis = func`${x} + ${y}n= ${x + y}`;
// becomes
var whatsThis = func(
{
raw: ['', ' + ', 'n = ', ''],
cooked: ['', ' + ', 'n = ', '']
},
x,
y,
x + y
);
var whatsThis = func`${x} + ${y}n= ${x + y}`;
// becomes
var whatsThis = func(
{
raw: ['', ' + ', 'n = ', ''],
cooked: ['', ' + ', 'n = ', '']
},
x,
y,
x + y
);
var whatsThis = func`${x} + ${y}n= ${x + y}`;
// becomes
var whatsThis = func(
{
raw: ['', ' + ', 'n = ', ''],
cooked: ['', ' + ', 'n = ', '']
},
x,
y,
x + y
);
Contextual Auto-Escaping
var els = document.querySelectorAll('.' + className);
// what if className contains "."?
var els = qsa`.${className}`;
// => qsa({ raw: ['.', ''], … }, className);
// if we write qsa well, it can detect the preceding "."
// and escape className!
function qsa({ raw, cooked }, ...vars) {
// `raw[0]` ends in '.'
// so `vars[0]` needs to be escaped like a CSS class
// similar rules for IDs, attribute selectors, etc.
}
Contextual Auto-Escaping In Overdrive
safehtml`<a href="${url}?q=${query}"
onclick="alert('${message}')"
style="color: ${color}">
${message}
</a>`
validate (no "s or such)
filter (e.g. no javascript: URLs)
percent-encode
escape JS (e.g. closing quote)
HTML encode
escape CSS (e.g. ; or :)
censor unsafe CSS (e.g. expression())
HTML encode
HTML encode
Contextual Auto-Escaping In Overdrive
var url = 'http://example.com/', query = 'Hello & Goodbye';
var message = 'Goodbye & Hello', color = 'expression(alert(1337))';
safehtml`<a href="${url}?q=${query}"
onclick="alert('${message}')"
style="color: ${color}">
${message}
</a>`
<a href="http://example.com/?q=Hello%20%26%20Goodbye"
onclick="alert(&#39;Goodbye&#32;x26&#32;Hello&#39;)"
style="color: CENSORED">
Goodbye &amp; Hello
</a>
http://js-quasis-libraries-and-repl.googlecode.com/svn/trunk/safetemplate.html
Localization and Formatting
l10n`Hello ${name}; you are visitor number ${visitor}:n!
You have ${money}:c in your account!`
// Write a l10n function that:
// - if it sees nothing after the var, it does nothing
// - if it sees :n, it uses localized number formatter
// - if it sees :c, it uses localized currency formatter
Dynamic Regular Expressions
/d+,d+/
// But now ',' needs to be configurable, so you do
new RegExp('d+' + separator + 'd+')
// Ick! Instead, write a re function to make this work
re`d+${separator}d+`
Embedded HTML/XML
jsx`<a href="${url}">${text}</a>`
// write a smart jsx function that transforms this into
React.DOM.a({ href: url }, text)
// zomg, no compile-to-JS language required!
DSLs for Code Execution
var childProcess = sh`ps ax | grep ${pid}`;
var xhr = POST`http://example.org/service?a=${a}&b=${b}
Content-Type: application/json
Authorization: ${credentials}
{ "foo": ${foo}, "bar": ${bar} }`;
We Just Solved:
• String interpolation/basic templating
• Multiline strings
• Contextual auto-escaping (giving generic injection protection)
• Localization and formatting
• Dynamic regular expressions
• Embedded HTML
… and opened up a whole new world of DSLs for writing intuitive, readable JS
We Just Solved:
• String interpolation/basic templating
• Multiline strings
• Contextual auto-escaping (giving generic injection protection)
• Localization and formatting
• Dynamic regular expressions
• Embedded HTML
… and opened up a whole new world of DSLs for writing intuitive, readable JS
Where Can I UseThis?
• Traceur: yes
• Continuum: yes
• Browsers: no
• Node.js: no
The Future Now
 The future of JS: it’s important!
 Learn more:
 es6isnigh.com
 harmony:proposals wiki page
 Follow @esdiscuss / read esdiscuss.org.
 Be adventurous; use a transpiler!
 Don't stagnate.

Weitere ähnliche Inhalte

Was ist angesagt?

What's New in ES6 for Web Devs
What's New in ES6 for Web DevsWhat's New in ES6 for Web Devs
What's New in ES6 for Web DevsRami Sayar
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)Domenic Denicola
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!Brendan Eich
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAnkit Agarwal
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptŁukasz Kużyński
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Ben Lesh
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsPiotr Pelczar
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptjnewmanux
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
ES6 in Production [JSConfUY2015]
ES6 in Production [JSConfUY2015]ES6 in Production [JSConfUY2015]
ES6 in Production [JSConfUY2015]Guillermo Paz
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jscacois
 
React Native Evening
React Native EveningReact Native Evening
React Native EveningTroy Miles
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaFlorent Pillet
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot CampTroy Miles
 

Was ist angesagt? (20)

What's New in ES6 for Web Devs
What's New in ES6 for Web DevsWhat's New in ES6 for Web Devs
What's New in ES6 for Web Devs
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
 
Domains!
Domains!Domains!
Domains!
 
Effective ES6
Effective ES6Effective ES6
Effective ES6
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
JavaScript Promise
JavaScript PromiseJavaScript Promise
JavaScript Promise
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascript
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Promise pattern
Promise patternPromise pattern
Promise pattern
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
ES6 in Production [JSConfUY2015]
ES6 in Production [JSConfUY2015]ES6 in Production [JSConfUY2015]
ES6 in Production [JSConfUY2015]
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
ES6: Features + Rails
ES6: Features + RailsES6: Features + Rails
ES6: Features + Rails
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
 

Ähnlich wie ES6: The Awesome Parts

Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax BasicsRichard Paul
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
Getting started with ES6 : Future of javascript
Getting started with ES6 : Future of javascriptGetting started with ES6 : Future of javascript
Getting started with ES6 : Future of javascriptMohd Saeed
 
Express Presentation
Express PresentationExpress Presentation
Express Presentationaaronheckmann
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScriptChengHui Weng
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойSigma Software
 
ESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. NowESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. NowKrzysztof Szafranek
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonAlex Payne
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 

Ähnlich wie ES6: The Awesome Parts (20)

Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 
Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
 
Wakanday JS201 Best Practices
Wakanday JS201 Best PracticesWakanday JS201 Best Practices
Wakanday JS201 Best Practices
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
Getting started with ES6 : Future of javascript
Getting started with ES6 : Future of javascriptGetting started with ES6 : Future of javascript
Getting started with ES6 : Future of javascript
 
Express Presentation
Express PresentationExpress Presentation
Express Presentation
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScript
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
CppTutorial.ppt
CppTutorial.pptCppTutorial.ppt
CppTutorial.ppt
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
ESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. NowESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. Now
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 

Mehr von Domenic Denicola

Mehr von Domenic Denicola (17)

The State of JavaScript (2015)
The State of JavaScript (2015)The State of JavaScript (2015)
The State of JavaScript (2015)
 
The jsdom
The jsdomThe jsdom
The jsdom
 
The Final Frontier
The Final FrontierThe Final Frontier
The Final Frontier
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
Streams for the Web
Streams for the WebStreams for the Web
Streams for the Web
 
After Return of the Jedi
After Return of the JediAfter Return of the Jedi
After Return of the Jedi
 
The State of JavaScript
The State of JavaScriptThe State of JavaScript
The State of JavaScript
 
How to Win Friends and Influence Standards Bodies
How to Win Friends and Influence Standards BodiesHow to Win Friends and Influence Standards Bodies
How to Win Friends and Influence Standards Bodies
 
The Extensible Web
The Extensible WebThe Extensible Web
The Extensible Web
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
 
Client-Side Packages
Client-Side PackagesClient-Side Packages
Client-Side Packages
 
Creating Truly RESTful APIs
Creating Truly RESTful APIsCreating Truly RESTful APIs
Creating Truly RESTful APIs
 
Promises, Promises
Promises, PromisesPromises, Promises
Promises, Promises
 
JavaScript on the Desktop
JavaScript on the DesktopJavaScript on the Desktop
JavaScript on the Desktop
 
Real World Windows 8 Apps in JavaScript
Real World Windows 8 Apps in JavaScriptReal World Windows 8 Apps in JavaScript
Real World Windows 8 Apps in JavaScript
 
Unit Testing for Great Justice
Unit Testing for Great JusticeUnit Testing for Great Justice
Unit Testing for Great Justice
 
Understanding the Node.js Platform
Understanding the Node.js PlatformUnderstanding the Node.js Platform
Understanding the Node.js Platform
 

Kürzlich hochgeladen

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 

Kürzlich hochgeladen (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

ES6: The Awesome Parts

  • 2. Domenic Denicola • http://domenic.me/ (blog) • https://github.com/domenic • https://npmjs.org/~domenic • http://slideshare.net/domenicdenicola Things I'm doing: • @esdiscuss onTwitter • The Promises/A+ spec • The Extensible Web Manifesto
  • 3. Why ES6? “Stagnation on the web is a social ill.” —Brendan Eich http://news.ycombinator.com/item?id=4634735
  • 4. Why JavaScript? “It is the one language that every vendor is committed to shipping compatibly. Evolving JS has the leverage to add/change the semantics of the platform in a way that no other strategy credibly can.” —Alex Russell http://infrequently.org/2013/07/why-javascript/
  • 5. Why ShouldYou Care? •It’s not often that, as a programmer, you get entirely new tools and capabilities in your toolbox. •Learning Haskell or a Lisp will do it, but then what do you build? •ES6 provides a unique opportunity.
  • 6. The Awesome Parts •Generators •Template strings •Proxies (no time today )
  • 8. function zeroOneTwo() { return [0, 1, 2]; } var array = zeroOneTwo(); for (var i of array) { console.log(i); }
  • 9. function* zeroOneTwo() { yield 0; yield 1; yield 2; } var generator = zeroOneTwo(); for (var i of generator) { console.log(i); }
  • 10. function* zeroOneTwo() { yield 0; yield 1; yield 2; } var generator = zeroOneTwo(); for (var i of generator) { console.log(i); }
  • 11. function* zeroOneTwo() { yield 0; yield 1; yield 2; } var generator = zeroOneTwo(); generator.next(); // { value: 0, done: false } generator.next(); // { value: 1, done: false } generator.next(); // { value: 2, done: false } generator.next(); // { value: undefined, done: true }
  • 12. function* fibonacci() { var previous = 0, current = 1; while (true) { var temp = previous; previous = current; current = temp + current; yield current; } } for (var i of fibonacci()) { console.log(i); } // 1, 2, 3, 5, 8, 13, ..., Infinity!
  • 13. function* take(iterable, numberToTake) { var i = 0; for (var taken of iterable) { if (i++ === numberToTake) { return; } yield taken; } } for (var i of take(fibonacci(), 5)) { console.log(i); } // 1, 2, 3, 5, 8 (and done!)
  • 14. Lazy sequences • You can write lazy versions of everything: filter, map, reduce, all those Underscore.js methods, … var awesomeEls = filter(domEls, isAwesome); var awesomeTexts = map(awesomeEls, el => el.textContent); var awesomeString = reduce(awesomeTexts, (acc, t) => acc + t); • Since filter and map return generators, nothing happens until reduce, a non-generator function, executes: then it's all done in a single pass. • You get the benefits of declarative functional data manipulation without the performance and memory downsides of intermediate arrays.
  • 15. Lazy sequences • You can write lazy versions of everything: filter, map, reduce, all those Underscore.js methods, … var awesomeEls = filter(domEls, isAwesome); var awesomeTexts = map(awesomeEls, el => el.textContent); var awesomeString = reduce(awesomeTexts, (acc, t) => acc + t); • Since filter and map return generators, nothing happens until reduce, a non-generator function, executes: then it's all done in a single pass. • You get the benefits of declarative functional data manipulation without the performance and memory downsides of intermediate arrays.
  • 16. But wait • Suspending execution until someone calls next() is a powerful feature. • What if you suspended execution until an async operation finished? Lots of people are starting to explore this in Node.js right now, leveraging e.g. promises to turn yield into a kind of “await.”
  • 17. function* loadUI() { showLoadingScreen(); yield loadUIDataAsynchronously(); hideLoadingScreen(); } spawn(loadUI); This function returns a promise Write the function spawn so that: • It calls next() and thus gets the loading promise. • It waits for the promise to fulfill before calling next() again. So we've suspended execution until the async operation finishes!
  • 18. function* loadAndShowData() { var data = yield loadData(); showData(data); } spawn(loadAndShowData); This function returns a promise for data You can actually pass data back in to the generator, causing yield to either return a value or throw an exception inside the generator body. • So if the promise fulfills, send back its fulfillment value, so that the data variable ends up holding it. • But if the promise rejects, tell the generator to throw the rejection reason as an exception.
  • 19. function* loadAndShowData() { showLoadingIndicator(); try { var data = yield loadData(); showData(data); } catch (e) { showError(e); } finally { removeLoadingIndicator(); } } spawn(loadAndShowData);
  • 20. function* loadAndShowData() { showLoadingIndicator(); try { var data = yield loadData(); showData(data); } catch (e) { showError(e); } finally { removeLoadingIndicator(); } } spawn(loadAndShowData);
  • 21. Where Can I UseThis? • Traceur: yes • Continuum: yes • Browsers: Chrome, Firefox* • Node.js: 0.11.3+
  • 24. var someArithmetic = `${x} + ${y} = ${x + y}`; var longString = `long string is long`;
  • 25. var someArithmetic = `${x} + ${y} = ${x + y}`; var longString = `long string is long`;
  • 26. var someArithmetic = `${x} + ${y} = ${x + y}`; var longString = `long string is long`;
  • 27. var whatsThis = func`${x} + ${y}n= ${x + y}`; // becomes var whatsThis = func( { raw: ['', ' + ', 'n = ', ''], cooked: ['', ' + ', 'n = ', ''] }, x, y, x + y );
  • 28. var whatsThis = func`${x} + ${y}n= ${x + y}`; // becomes var whatsThis = func( { raw: ['', ' + ', 'n = ', ''], cooked: ['', ' + ', 'n = ', ''] }, x, y, x + y );
  • 29. var whatsThis = func`${x} + ${y}n= ${x + y}`; // becomes var whatsThis = func( { raw: ['', ' + ', 'n = ', ''], cooked: ['', ' + ', 'n = ', ''] }, x, y, x + y );
  • 30. var whatsThis = func`${x} + ${y}n= ${x + y}`; // becomes var whatsThis = func( { raw: ['', ' + ', 'n = ', ''], cooked: ['', ' + ', 'n = ', ''] }, x, y, x + y );
  • 31. Contextual Auto-Escaping var els = document.querySelectorAll('.' + className); // what if className contains "."? var els = qsa`.${className}`; // => qsa({ raw: ['.', ''], … }, className); // if we write qsa well, it can detect the preceding "." // and escape className! function qsa({ raw, cooked }, ...vars) { // `raw[0]` ends in '.' // so `vars[0]` needs to be escaped like a CSS class // similar rules for IDs, attribute selectors, etc. }
  • 32. Contextual Auto-Escaping In Overdrive safehtml`<a href="${url}?q=${query}" onclick="alert('${message}')" style="color: ${color}"> ${message} </a>` validate (no "s or such) filter (e.g. no javascript: URLs) percent-encode escape JS (e.g. closing quote) HTML encode escape CSS (e.g. ; or :) censor unsafe CSS (e.g. expression()) HTML encode HTML encode
  • 33. Contextual Auto-Escaping In Overdrive var url = 'http://example.com/', query = 'Hello & Goodbye'; var message = 'Goodbye & Hello', color = 'expression(alert(1337))'; safehtml`<a href="${url}?q=${query}" onclick="alert('${message}')" style="color: ${color}"> ${message} </a>` <a href="http://example.com/?q=Hello%20%26%20Goodbye" onclick="alert(&#39;Goodbye&#32;x26&#32;Hello&#39;)" style="color: CENSORED"> Goodbye &amp; Hello </a> http://js-quasis-libraries-and-repl.googlecode.com/svn/trunk/safetemplate.html
  • 34. Localization and Formatting l10n`Hello ${name}; you are visitor number ${visitor}:n! You have ${money}:c in your account!` // Write a l10n function that: // - if it sees nothing after the var, it does nothing // - if it sees :n, it uses localized number formatter // - if it sees :c, it uses localized currency formatter
  • 35. Dynamic Regular Expressions /d+,d+/ // But now ',' needs to be configurable, so you do new RegExp('d+' + separator + 'd+') // Ick! Instead, write a re function to make this work re`d+${separator}d+`
  • 36. Embedded HTML/XML jsx`<a href="${url}">${text}</a>` // write a smart jsx function that transforms this into React.DOM.a({ href: url }, text) // zomg, no compile-to-JS language required!
  • 37. DSLs for Code Execution var childProcess = sh`ps ax | grep ${pid}`; var xhr = POST`http://example.org/service?a=${a}&b=${b} Content-Type: application/json Authorization: ${credentials} { "foo": ${foo}, "bar": ${bar} }`;
  • 38. We Just Solved: • String interpolation/basic templating • Multiline strings • Contextual auto-escaping (giving generic injection protection) • Localization and formatting • Dynamic regular expressions • Embedded HTML … and opened up a whole new world of DSLs for writing intuitive, readable JS
  • 39. We Just Solved: • String interpolation/basic templating • Multiline strings • Contextual auto-escaping (giving generic injection protection) • Localization and formatting • Dynamic regular expressions • Embedded HTML … and opened up a whole new world of DSLs for writing intuitive, readable JS
  • 40. Where Can I UseThis? • Traceur: yes • Continuum: yes • Browsers: no • Node.js: no
  • 41. The Future Now  The future of JS: it’s important!  Learn more:  es6isnigh.com  harmony:proposals wiki page  Follow @esdiscuss / read esdiscuss.org.  Be adventurous; use a transpiler!  Don't stagnate.