SlideShare a Scribd company logo
Introducing ƒancy
Writing functional javascript that can hit production
Write performant, stable, readable,
debuggable, and production worthy code
quickly.
In short, to make life easier.
I won't invoke complex vocabulary, math, and
theory; I don't need to.
What is my goal here?
What is functional programming?
● Avoids State
● Emphasizes application of functions
● Avoids side-effects
● Combines functions
● Solves problems conceptually (no loops)
What is fancy?
Fancy is a mashup:
a. Underscore.js functions (Jeremy Ashkenas)
b. Functional.js features (Oliver Steele)
c. 1-off pseudo-arrays much like a jQuery collection
d. And some other functions I felt were needed
(chunk)
FancyArray([1,2,3]).sortBy("%2");
>>> [2, 1, 3]
a b
c
Wait, how do I use this?
1. Construct a FancyArray([foo, bar]) from any array.
Construct a FancyObject({foo: bar}) from an object.
2. Call normal underscore functions on your FancyArray (or object).
3. When one of those calls would return an array, it instead returns a
FancyArray, thus allowing chaining. When one of underscore's functions
would have returned an object, it instead returns a FancyObject.
However, unlike underscore's .chain method, these one-off objects act very
much like normal arrays or objects.
And-
Also, any function that takes another function as an
argument (like map) can take a string to represent that
function as devised by Oliver Steele
FancyArray([1,2,3]).map("*2")
>> [2,4,6]
FancyArray([1,2,3]).map("12/x")
>> [12,6,4]
FancyArray([1,2,3]).map("x,y->x+y")
>> [1,3,5]
Like this:
var samplePeople = new FancyObject(
{
0: {name: "Alice", age: 15, ranking: 3, team: 2},
1: {name: "David", age: 25, ranking: 2, team: 1},
2: {name: "Charlie", age: 32, ranking: 4, team: 1},
3: {name: "Bob", age: 24, ranking: 1, team: 4}
});
samplePeople.values().sortBy(".age").pluck("name");
>>>["Alice", "Bob", "David", "Charlie"]
Returns a FancyArray
Though you may not see
from the chrome console
output, this is still a
FancyArray
Functional.js style function
How does that make my life easier?
You can read your code left-to-right, like english
It's now shorter than declarative, with less ugly nesting.
No pollution of public scope or prototypes.
var samplePeople = { ... };
// fancy - This is prettier
FO(samplePeople).values().sortBy( ".age").pluck("name");
// plain underscore - Than that
_.chain(samplePeople).values().sortBy(
function(p) { return p.age; }).pluck( "name").value();
Let's consider a sample problem
● Not fibonacci
● Not prime numbers
● Not foobar or fizzbuzz.
Evaluating poker hands.
How do poker hands work?
1st - Hand Types:
1. Straight Flush
2. 4 of a kind
3. Full-House
4. Flush
5. Straight
6. 3 of a kind
7. 2 Pair
8. 1 Pair
9. High card
2nd - Card Values
How high are the cards
used to make up the
hand?
3rd - Card Values
How high are the
remaining cards in the
hand?
Example:
Full House:
3 Of 1 value
2 Of another Value
Beats lower ranking hands
(like a straight). Loses
to higher-ranking hands.
(Straight flush).
If two full houses happen, compare the sets of 3, whichever has the higher
value wins. If those are equal, compare the pairs of two, whichever has the
higher value wins. If those are equal, then the hands are equal.
A lame approach
// A non-functional approach might involve defining a lot of functions that
// look something like this
/**
* Returns true if hand is full-house
*/
function isFullHouse(cards) {
var differentCards = [] ;
for (var x=0; x < cards.length; x++) {
differentCards[ valueOf( cards[x] ) ]++;
}
return (differentCards. indexOf(3) > 0) && (differentCards. indexOf(2) >
0);
}
function compareTwoFullHouses (fullhouse1, fullhouse2) {
...
Let's think about this...
What do poker hands have in common?
● 6 hands: Sets of Cards that are the same value.
● 2 hands: Cards that have consecutive value
● 2 hands: Cards that are all the same suit.
Or
● 8 hands: Counts of cards that share sameness on an attribute
● 2 hands: Cards that have consecutive value
Coming up with an algorithm
1. Take the hand. Extract relevant
attribute. In this case, it means turn
[ "3D", "3S", "6D", "2C", "2H"]
into :
[ 3, 3, 6, 2, 2]
2. Find groups of cards. Turn it
into
{3: 2, 6: 1, 2: 2} (meaning two threes, a six, and a pair of twos)
3. Compare this to the hand definition.
4. (For ties) Find a way to convey the second and third characteristics (in this
case, that 6 of diamonds).
A functional approach
[
["Full House", followsPattern(cards, [3,2], cardValues)],
["2 Pair", followsPattern(cards, [2,2,1], cardValues)],
["Flush", followsPattern(cards, [5], cardSuits)],
]
var followsPattern = function(hand, expected, callback) {
var values = FA(hand).map(callback); //Turn the input to an array of numbers
var groups = values.countBy(); //Get the counts of duplicates
if (! groups.values().hasAll(expected)) {
return false; //This hand is NOT of the expected type, no match
}
var sets = groups.pairs(); //Turn {2: 3, 8: 2} into [[2, 3], [8, 2]] for example
sets = sets.sortBy('x[1] + "" + x[0]');
//take advantage of alphabetical sort, sort by cardCount,
// then card Value alpha in a tie
return sets.pluck(0).join("");//pluck the first item, the cardValueAlpha
};
Example Helper Function
/**
* return true if every value in needle is in this array,
* at least as many times.
*/
FancyArray.prototype.hasAll = function(needle) {
var summed = this.countBy().meld(
FA(needle).countBy().mapObj( "a*-1"),
"a+b");
return summed.values().every( ">=0");
};
So... Is it really better?
Advantages:
● Less Code
● More Dry
● Easier to keep track of
● Easier to extend (say
make it work with
hold'em)
● A little faster to write
Disadvantages:
● Perhaps scary at first
● A little harder to
wrap your brain
around
● Could be off-putting
to collaborators who
know nothing about
the notation.
YES.
Is this really functional programming?
Isn't there more than this to functional programming?
A challenge has been leveraged at underscore, namely by Brian
Lonsdorf. In his talk, "Underscore, You're doing it wrong" in which he
challenged whether underscore really enabled functional
programming. In short he argued that underscore's notation impeded
currying and composition.
It's a fair criticism, and one that applies equally well to the
ecmascript 5 standard which put map in the array.prototype. Really,
you can't map to another map eloquently or do other advanced
functional programming things with the same grace. However, this
isn't a big issue for the vast majority of users.
How does it stack up?
● Avoids State
● Emphasizes use of functions
● Avoids side-effects
● Combines functions
● Solves problems conceptually
Call it whatever you want. The important thing is that you
get the ability to write good, reusable, abstracted code
easily. Don't optimize for an edge-case.
Thanks
Questions?
Links:
https://github.com/anfurny/fancy
http://blog.alexrohde.com/
Source Libraries:
http://underscorejs.org/
http://osteele.com/sources/javascript/functional/

More Related Content

What's hot

Core concepts-javascript
Core concepts-javascriptCore concepts-javascript
Core concepts-javascript
Prajwala Manchikatla
 
JavaScript Patterns
JavaScript PatternsJavaScript Patterns
JavaScript Patterns
Stoyan Stefanov
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
hwilming
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
Dragos Ionita
 
ECMAScript 6 and beyond
ECMAScript 6 and beyondECMAScript 6 and beyond
ECMAScript 6 and beyond
Francis Johny
 
Exhibition of Atrocity
Exhibition of AtrocityExhibition of Atrocity
Exhibition of Atrocity
Michael Pirnat
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1
Zaar Hai
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammers
Giovanni924
 
Testing for share
Testing for share Testing for share
Testing for share
Rajeev Mehta
 
あたかも自然言語を書くようにコーディングしてみる
あたかも自然言語を書くようにコーディングしてみるあたかも自然言語を書くようにコーディングしてみる
あたかも自然言語を書くようにコーディングしてみる
Kazuya Numata
 
C++ L09-Classes Part2
C++ L09-Classes Part2C++ L09-Classes Part2
C++ L09-Classes Part2
Mohammad Shaker
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
Donald Sipe
 
C++ L08-Classes Part1
C++ L08-Classes Part1C++ L08-Classes Part1
C++ L08-Classes Part1
Mohammad Shaker
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
Michael Pirnat
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
Ramesh Nair
 
(Parameterized) Roles
(Parameterized) Roles(Parameterized) Roles
(Parameterized) Roles
sartak
 
P6 OO vs Moose (&Moo)
P6 OO vs Moose (&Moo)P6 OO vs Moose (&Moo)
P6 OO vs Moose (&Moo)
lichtkind
 
Functional microscope - Lenses in C++
Functional microscope - Lenses in C++Functional microscope - Lenses in C++
Functional microscope - Lenses in C++
Alexander Granin
 
C++ L10-Inheritance
C++ L10-InheritanceC++ L10-Inheritance
C++ L10-Inheritance
Mohammad Shaker
 
Stamps - a better way to object composition
Stamps - a better way to object compositionStamps - a better way to object composition
Stamps - a better way to object composition
Vasyl Boroviak
 

What's hot (20)

Core concepts-javascript
Core concepts-javascriptCore concepts-javascript
Core concepts-javascript
 
JavaScript Patterns
JavaScript PatternsJavaScript Patterns
JavaScript Patterns
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
ECMAScript 6 and beyond
ECMAScript 6 and beyondECMAScript 6 and beyond
ECMAScript 6 and beyond
 
Exhibition of Atrocity
Exhibition of AtrocityExhibition of Atrocity
Exhibition of Atrocity
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammers
 
Testing for share
Testing for share Testing for share
Testing for share
 
あたかも自然言語を書くようにコーディングしてみる
あたかも自然言語を書くようにコーディングしてみるあたかも自然言語を書くようにコーディングしてみる
あたかも自然言語を書くようにコーディングしてみる
 
C++ L09-Classes Part2
C++ L09-Classes Part2C++ L09-Classes Part2
C++ L09-Classes Part2
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
C++ L08-Classes Part1
C++ L08-Classes Part1C++ L08-Classes Part1
C++ L08-Classes Part1
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
(Parameterized) Roles
(Parameterized) Roles(Parameterized) Roles
(Parameterized) Roles
 
P6 OO vs Moose (&Moo)
P6 OO vs Moose (&Moo)P6 OO vs Moose (&Moo)
P6 OO vs Moose (&Moo)
 
Functional microscope - Lenses in C++
Functional microscope - Lenses in C++Functional microscope - Lenses in C++
Functional microscope - Lenses in C++
 
C++ L10-Inheritance
C++ L10-InheritanceC++ L10-Inheritance
C++ L10-Inheritance
 
Stamps - a better way to object composition
Stamps - a better way to object compositionStamps - a better way to object composition
Stamps - a better way to object composition
 

Similar to Fancy talk

BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
Andrew Phillips
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Andrew Phillips
 
What can scala puzzlers teach us
What can scala puzzlers teach usWhat can scala puzzlers teach us
What can scala puzzlers teach us
Daniel Sobral
 
Java best practices
Java best practicesJava best practices
Java best practices
Ray Toal
 
Go Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional ProgrammingGo Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional Programming
Lex Sheehan
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
Pavlo Baron
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
Jimin Hsieh
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in ruby
Koen Handekyn
 
Scala ntnu
Scala ntnuScala ntnu
[Start] Scala
[Start] Scala[Start] Scala
[Start] Scala
佑介 九岡
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
David Furber
 
Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Real World Haskell: Lecture 1
Real World Haskell: Lecture 1
Bryan O'Sullivan
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie Iskander
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
Troy Miles
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
Sudharsan S
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
Skills Matter
 
Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
Christian Heilmann
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
climatewarrior
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in Python
Python Ireland
 

Similar to Fancy talk (20)

BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
 
What can scala puzzlers teach us
What can scala puzzlers teach usWhat can scala puzzlers teach us
What can scala puzzlers teach us
 
Java best practices
Java best practicesJava best practices
Java best practices
 
Go Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional ProgrammingGo Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional Programming
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in ruby
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
[Start] Scala
[Start] Scala[Start] Scala
[Start] Scala
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
 
Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Real World Haskell: Lecture 1
Real World Haskell: Lecture 1
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in Python
 

Recently uploaded

Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
David Brossard
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdfAI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
Techgropse Pvt.Ltd.
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 

Recently uploaded (20)

Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdfAI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 

Fancy talk

  • 1. Introducing ƒancy Writing functional javascript that can hit production
  • 2. Write performant, stable, readable, debuggable, and production worthy code quickly. In short, to make life easier. I won't invoke complex vocabulary, math, and theory; I don't need to. What is my goal here?
  • 3. What is functional programming? ● Avoids State ● Emphasizes application of functions ● Avoids side-effects ● Combines functions ● Solves problems conceptually (no loops)
  • 4. What is fancy? Fancy is a mashup: a. Underscore.js functions (Jeremy Ashkenas) b. Functional.js features (Oliver Steele) c. 1-off pseudo-arrays much like a jQuery collection d. And some other functions I felt were needed (chunk) FancyArray([1,2,3]).sortBy("%2"); >>> [2, 1, 3] a b c
  • 5. Wait, how do I use this? 1. Construct a FancyArray([foo, bar]) from any array. Construct a FancyObject({foo: bar}) from an object. 2. Call normal underscore functions on your FancyArray (or object). 3. When one of those calls would return an array, it instead returns a FancyArray, thus allowing chaining. When one of underscore's functions would have returned an object, it instead returns a FancyObject. However, unlike underscore's .chain method, these one-off objects act very much like normal arrays or objects.
  • 6. And- Also, any function that takes another function as an argument (like map) can take a string to represent that function as devised by Oliver Steele FancyArray([1,2,3]).map("*2") >> [2,4,6] FancyArray([1,2,3]).map("12/x") >> [12,6,4] FancyArray([1,2,3]).map("x,y->x+y") >> [1,3,5]
  • 7. Like this: var samplePeople = new FancyObject( { 0: {name: "Alice", age: 15, ranking: 3, team: 2}, 1: {name: "David", age: 25, ranking: 2, team: 1}, 2: {name: "Charlie", age: 32, ranking: 4, team: 1}, 3: {name: "Bob", age: 24, ranking: 1, team: 4} }); samplePeople.values().sortBy(".age").pluck("name"); >>>["Alice", "Bob", "David", "Charlie"] Returns a FancyArray Though you may not see from the chrome console output, this is still a FancyArray Functional.js style function
  • 8. How does that make my life easier? You can read your code left-to-right, like english It's now shorter than declarative, with less ugly nesting. No pollution of public scope or prototypes. var samplePeople = { ... }; // fancy - This is prettier FO(samplePeople).values().sortBy( ".age").pluck("name"); // plain underscore - Than that _.chain(samplePeople).values().sortBy( function(p) { return p.age; }).pluck( "name").value();
  • 9. Let's consider a sample problem ● Not fibonacci ● Not prime numbers ● Not foobar or fizzbuzz. Evaluating poker hands.
  • 10. How do poker hands work? 1st - Hand Types: 1. Straight Flush 2. 4 of a kind 3. Full-House 4. Flush 5. Straight 6. 3 of a kind 7. 2 Pair 8. 1 Pair 9. High card 2nd - Card Values How high are the cards used to make up the hand? 3rd - Card Values How high are the remaining cards in the hand?
  • 11. Example: Full House: 3 Of 1 value 2 Of another Value Beats lower ranking hands (like a straight). Loses to higher-ranking hands. (Straight flush). If two full houses happen, compare the sets of 3, whichever has the higher value wins. If those are equal, compare the pairs of two, whichever has the higher value wins. If those are equal, then the hands are equal.
  • 12. A lame approach // A non-functional approach might involve defining a lot of functions that // look something like this /** * Returns true if hand is full-house */ function isFullHouse(cards) { var differentCards = [] ; for (var x=0; x < cards.length; x++) { differentCards[ valueOf( cards[x] ) ]++; } return (differentCards. indexOf(3) > 0) && (differentCards. indexOf(2) > 0); } function compareTwoFullHouses (fullhouse1, fullhouse2) { ...
  • 13. Let's think about this... What do poker hands have in common? ● 6 hands: Sets of Cards that are the same value. ● 2 hands: Cards that have consecutive value ● 2 hands: Cards that are all the same suit. Or ● 8 hands: Counts of cards that share sameness on an attribute ● 2 hands: Cards that have consecutive value
  • 14. Coming up with an algorithm 1. Take the hand. Extract relevant attribute. In this case, it means turn [ "3D", "3S", "6D", "2C", "2H"] into : [ 3, 3, 6, 2, 2] 2. Find groups of cards. Turn it into {3: 2, 6: 1, 2: 2} (meaning two threes, a six, and a pair of twos) 3. Compare this to the hand definition. 4. (For ties) Find a way to convey the second and third characteristics (in this case, that 6 of diamonds).
  • 15. A functional approach [ ["Full House", followsPattern(cards, [3,2], cardValues)], ["2 Pair", followsPattern(cards, [2,2,1], cardValues)], ["Flush", followsPattern(cards, [5], cardSuits)], ] var followsPattern = function(hand, expected, callback) { var values = FA(hand).map(callback); //Turn the input to an array of numbers var groups = values.countBy(); //Get the counts of duplicates if (! groups.values().hasAll(expected)) { return false; //This hand is NOT of the expected type, no match } var sets = groups.pairs(); //Turn {2: 3, 8: 2} into [[2, 3], [8, 2]] for example sets = sets.sortBy('x[1] + "" + x[0]'); //take advantage of alphabetical sort, sort by cardCount, // then card Value alpha in a tie return sets.pluck(0).join("");//pluck the first item, the cardValueAlpha };
  • 16. Example Helper Function /** * return true if every value in needle is in this array, * at least as many times. */ FancyArray.prototype.hasAll = function(needle) { var summed = this.countBy().meld( FA(needle).countBy().mapObj( "a*-1"), "a+b"); return summed.values().every( ">=0"); };
  • 17. So... Is it really better? Advantages: ● Less Code ● More Dry ● Easier to keep track of ● Easier to extend (say make it work with hold'em) ● A little faster to write Disadvantages: ● Perhaps scary at first ● A little harder to wrap your brain around ● Could be off-putting to collaborators who know nothing about the notation.
  • 18. YES.
  • 19. Is this really functional programming? Isn't there more than this to functional programming? A challenge has been leveraged at underscore, namely by Brian Lonsdorf. In his talk, "Underscore, You're doing it wrong" in which he challenged whether underscore really enabled functional programming. In short he argued that underscore's notation impeded currying and composition. It's a fair criticism, and one that applies equally well to the ecmascript 5 standard which put map in the array.prototype. Really, you can't map to another map eloquently or do other advanced functional programming things with the same grace. However, this isn't a big issue for the vast majority of users.
  • 20. How does it stack up? ● Avoids State ● Emphasizes use of functions ● Avoids side-effects ● Combines functions ● Solves problems conceptually Call it whatever you want. The important thing is that you get the ability to write good, reusable, abstracted code easily. Don't optimize for an edge-case.