SlideShare a Scribd company logo
Real Life CoffeeScript
What is CoffeeScript?
   CS is a language that compiles into
   JavaScript (like HAML and SASS)

  Not a superset of JS (not like SCSS)

Not a JS framework (not a replacement for
                jQuery)
From the maker
CoffeeScript is a little language that compiles into JavaScript. Underneath all of those
embarrassing braces and semicolons, JavaScript has always had a gorgeous object
model at its heart. CoffeeScript is an attempt to expose the good parts of JavaScript
in a simple way. - Josh Ashkenas
Why all the fuss?
CS will be a standard part of Rails 3.1 (along
                 with SASS)

        It makes JS more like Ruby!

 CS is an npm package, hence a gateway
      drug to Node.js and Socket.IO
Why use CS?
 compiles to lint-free JS, nothing fancy

easy to write "good parts javascript" that
               looks clean

  makes good practices less tedious

HAML and SASS are awesome and now
        you're using those...
What are the features?
Easy variable declaration (lexical scoping)

   Easy class inheritance and binding

   Easy instance variables @name =>
               this.name

       Implicit return from functions

         "String #{interpolation}"
Semantic Shortcuts
      -> and => instead of function(){}

execute() if that is thing1 and that isnt thing2

         and/or/not instead of &&/||/!

            that = thing1 or thing2

                that or= thing3
Conditionals
 if condition? (no parantheses, ? is .nil? not
                   .blank?)

   if condition?() to evaluate if a function
                 returns null

throwAFit() unless @name in ["Paul", "John"]
How much more?
      list traversal: for result in results

return (transform result for result in results)

        switch/when/else instead of
            switch/case/default

        yes/no, on/off for true/false
Show me some code!
Some ugly JavaScript
var sortFunction = function(a,b) {
    if (typeof(a[sort_col]) === 'number') {
        // numeric sort
        if (sort_dir === 'up') return (a[sort_col] - b[sort_col]);
        else                   return (b[sort_col] - a[sort_col]);
    } else {
        // string sort
        var aName = a[sort_col].toLowerCase(), bName = b[sort_col].toLowerCase();
        if (sort_dir === 'up') return (aName > bName);
        else return (bName > aName);
    }
}

this.getResults = function(){
    // here is the place to apply filter
    var results = parent.results;
    if (filter_text) {
        results = $.makeArray($.map(results, function(result, i){
             var haystack = [result.name, result.brands, result.address, result.city].join(', ')
             return (haystack.indexOf(filter_text) != -1) ? result : null;
        }));
    }
    if (sort_col && sort_dir) {
        results = results.sort(sortFunction);
    }
    return results;
}
class Results
    setSort: (col, dir) ->
        if col? and dir?
            results = _(@results).sortBy (result) -> result[col]
            @results = if dir is 'down' then results.reverse() else results
    setFilter: (filter) ->
        if filter?
            matching = (needle) ->
                haystack = _.join needle.name, needle.brand_list, needle.address, needle.city
                _(haystack).includes(needle)
            @results = _.select @results, matching
standard jQuery with object binding
$('#view_as_table').click => @.setViewType('Table', true)
$('#view_as_thumbs').click => @.setViewType('Thumb', true)
$('#view_as_list').click   => @.setViewType('List', true)
Big Long jQuery Call
var makeSortable = function(){
    $('#widgets .col').sortable({
        items: 'div.widget',
        dropOnEmpty: true,
        handle: '.header h3',
        appendTo: 'body',
        connectWith: '.col',
        ...
    });
makeSortable = ->
    $('#widgets .col').sortable
        items: 'div.widget'
        dropOnEmpty: yes
        handle: '.header h3'
        appendTo: 'body'
        connectWith: '.col'
        revert: yes
        cursor: 'move'
        placeholder: 'drag-over'
        stop: updateWidgetOrder
class JKT.GoogleLoader
    constructor: (callback) ->
        @callback = callback
        if google? then @loadComponent() else @loadGoogle()
    loadComponent: -> return
    loadGoogle: () ->
        script = document.createElement "script"
        script.src = "http://www.google.com/jsapi?key=#{JKT.google_api_key}&sensor=false"
        script.type = "text/javascript"
        if script.attachEvent? # IE
             script.attachEvent 'onreadystatechange', =>
                 if script.readyState in ['loaded', 'complete']
                     @loadComponent()
        else
             script.onload = => @loadComponent()
        document.getElementsByTagName("head")[0].appendChild(script)

class JKT.MapLoader extends JKT.GoogleLoader
    loadComponent: ->
        google.load 'maps', '3',
            other_params: "sensor=false"
            callback: @callback
        return
super Is Super
class JKT.Search.TableRenderer
    constructor: (results) -> @results = results
    render: ->
        $('#results').html $('#listing_grid').render [{foo:"bar"}]
        $('#results tbody').html $('#listing_grid_row').render(@results)

class JKT.Search.MapRenderer extends JKT.Search.TableRenderer
    render: ->
        super
        if @results.length <= 300
            $('#results tbody tr').each ->
                ...
class Results
    ...
    paginate: (start, end) ->
        if start? and end?
            @results = @results[start..end]
    toSentence: ->
        size = _.size(@results) or 0
        if size is 1 then "1 result" else 
            "#{size} results"

    enoughForMap: -> _.size(@results) < 300
    any         : -> _.isArray(@results) and _.any(@results)
Sources of resistance?
I already know JavaScript
          Kudos to you. I do too.

      Not a substitute for knowing JS.

Your own JS isn't as clean as the compiled
                    JS

Unless your last name is Resig or Crockford
It looks weird.
 It's the bastard child of Ruby and Python.

Once you get used to it, it's the JS that looks
                 whack.
I don't write JS, I write
        jQuery.
  No you write JS using jQuery.

        I use jQuery too.

 CS makes your jQuery cleaner.
Sugar Allergies
 Are you allergic to "syntactic sugar"?

        CS is more than that.

We need a better name because we all
     know sugar is bad for you.

        Line Noise Reduction
Sugar = Noise Reduction
Bad line noise highly affects the readability of our code. It is true we get used to them,
but once you remove it, there's no way back. - Jose Valim
Indentation Allergies
                  "I like my curly braces"

          CS uses Pythonic whitespace

         You get used to it - cost/benefit

      I really don't understand why using indentation level for blocks is so
  controversial. You do indentation anyway; you don't want to violate OAOO; it
 avoids hard-to-spot errors where indentation and begin/end or {/} differ; it looks
 cleaner; there's no way to have unmatched braces; and I never get indentation
  wrong, but sometimes I do have to count braces. In other words, don't let this
issue stop you from trying out Python; indentation-denoted blocks are very easy
                        to get used to. -- Falk Bruegmann
Firebug Will Break
You lose the correspondence between your
     code and line numbers in Firebug

           There is no FireCoffee

Use small coffee files to get approximate line
              correspondence

The compiled JS is not magical - you can still
                  read it
What about syntax
     highlighting?
    No plugin for Eclipse/Aptana

Use TextMate, jEdit, gEdit, vim, emacs

    The TextMate bundle is great!
Maybe on the next project
Unless your current project is almost done
     and will never be maintained...

Porting that project is just what you need to
                  learn CS.

  It's not "all or nothing": one file at a time

If you don't like it you can keep the change.
Where do I start?
Don't just dive in or you'll be coding before
                 you're ready

    Read the CS overview a few times
(http://jashkenas.github.com/coffee-script)

   Install CS and the TextMate bundle

         Port a project's JS to CS

        Write some new CS code
Ad

More Related Content

What's hot (19)

Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
Stoyan Stefanov
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
adamcookeuk
 
Moose - YAPC::NA 2012
Moose - YAPC::NA 2012Moose - YAPC::NA 2012
Moose - YAPC::NA 2012
xSawyer
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming Language
Duda Dornelles
 
Dan Shappir "JavaScript Riddles For Fun And Profit"
Dan Shappir "JavaScript Riddles For Fun And Profit"Dan Shappir "JavaScript Riddles For Fun And Profit"
Dan Shappir "JavaScript Riddles For Fun And Profit"
Fwdays
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascript
mpnkhan
 
Understanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG JuneUnderstanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG June
Deepu S Nath
 
Factory Girl
Factory GirlFactory Girl
Factory Girl
Gabe Evans
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Scala vs Ruby
Rémy-Christophe Schermesser
 
Introduction to es6
Introduction to es6Introduction to es6
Introduction to es6
NexThoughts Technologies
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.Vim
Lin Yo-An
 
Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]
Aaron Gustafson
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
Pham Huy Tung
 
Moose
MooseMoose
Moose
John Napiorkowski
 
Programming Language Swift Overview
Programming Language Swift OverviewProgramming Language Swift Overview
Programming Language Swift Overview
Kaz Yoshikawa
 
Ruby on Rails for beginners
Ruby on Rails for beginnersRuby on Rails for beginners
Ruby on Rails for beginners
Vysakh Sreenivasan
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In Perl
Kang-min Liu
 
Jquery 1
Jquery 1Jquery 1
Jquery 1
Manish Kumar Singh
 
Backbone js
Backbone jsBackbone js
Backbone js
rstankov
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
Stoyan Stefanov
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
adamcookeuk
 
Moose - YAPC::NA 2012
Moose - YAPC::NA 2012Moose - YAPC::NA 2012
Moose - YAPC::NA 2012
xSawyer
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming Language
Duda Dornelles
 
Dan Shappir "JavaScript Riddles For Fun And Profit"
Dan Shappir "JavaScript Riddles For Fun And Profit"Dan Shappir "JavaScript Riddles For Fun And Profit"
Dan Shappir "JavaScript Riddles For Fun And Profit"
Fwdays
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascript
mpnkhan
 
Understanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG JuneUnderstanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG June
Deepu S Nath
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.Vim
Lin Yo-An
 
Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]
Aaron Gustafson
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
Pham Huy Tung
 
Programming Language Swift Overview
Programming Language Swift OverviewProgramming Language Swift Overview
Programming Language Swift Overview
Kaz Yoshikawa
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In Perl
Kang-min Liu
 
Backbone js
Backbone jsBackbone js
Backbone js
rstankov
 

Similar to Real life-coffeescript (20)

Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and JasmineRails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Raimonds Simanovskis
 
Wakanday JS201 Best Practices
Wakanday JS201 Best PracticesWakanday JS201 Best Practices
Wakanday JS201 Best Practices
Juergen Fesslmeier
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Paulo Ragonha
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
David Padbury
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
Núcleo de Electrónica e Informática da Universidade do Algarve
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
Rasan Samarasinghe
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie Iskander
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
Doug Jones
 
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
 
js notes apni kaksha ahsgsggdgsgsgsgsgsgsgs
js notes apni kaksha ahsgsggdgsgsgsgsgsgsgsjs notes apni kaksha ahsgsggdgsgsgsgsgsgsgs
js notes apni kaksha ahsgsggdgsgsgsgsgsgsgs
codeverse48
 
Einführung in TypeScript
Einführung in TypeScriptEinführung in TypeScript
Einführung in TypeScript
Demian Holderegger
 
SQL -PHP Tutorial
SQL -PHP TutorialSQL -PHP Tutorial
SQL -PHP Tutorial
Information Technology
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
Information Technology
 
Lettering js
Lettering jsLettering js
Lettering js
davatron5000
 
Scala introduction
Scala introductionScala introduction
Scala introduction
Alf Kristian Støyle
 
Refactoring
RefactoringRefactoring
Refactoring
Amir Barylko
 
Uses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsUses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & Stubs
PatchSpace Ltd
 
Polyglot Programming in the JVM
Polyglot Programming in the JVMPolyglot Programming in the JVM
Polyglot Programming in the JVM
Andres Almiray
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
Mark
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
Domenic Denicola
 
Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and JasmineRails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Raimonds Simanovskis
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Paulo Ragonha
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
David Padbury
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
Rasan Samarasinghe
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie Iskander
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
Doug Jones
 
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
 
js notes apni kaksha ahsgsggdgsgsgsgsgsgsgs
js notes apni kaksha ahsgsggdgsgsgsgsgsgsgsjs notes apni kaksha ahsgsggdgsgsgsgsgsgsgs
js notes apni kaksha ahsgsggdgsgsgsgsgsgsgs
codeverse48
 
Uses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsUses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & Stubs
PatchSpace Ltd
 
Polyglot Programming in the JVM
Polyglot Programming in the JVMPolyglot Programming in the JVM
Polyglot Programming in the JVM
Andres Almiray
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
Mark
 
Ad

Recently uploaded (20)

Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Ad

Real life-coffeescript

  • 2. What is CoffeeScript? CS is a language that compiles into JavaScript (like HAML and SASS) Not a superset of JS (not like SCSS) Not a JS framework (not a replacement for jQuery)
  • 3. From the maker CoffeeScript is a little language that compiles into JavaScript. Underneath all of those embarrassing braces and semicolons, JavaScript has always had a gorgeous object model at its heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way. - Josh Ashkenas
  • 4. Why all the fuss? CS will be a standard part of Rails 3.1 (along with SASS) It makes JS more like Ruby! CS is an npm package, hence a gateway drug to Node.js and Socket.IO
  • 5. Why use CS? compiles to lint-free JS, nothing fancy easy to write "good parts javascript" that looks clean makes good practices less tedious HAML and SASS are awesome and now you're using those...
  • 6. What are the features? Easy variable declaration (lexical scoping) Easy class inheritance and binding Easy instance variables @name => this.name Implicit return from functions "String #{interpolation}"
  • 7. Semantic Shortcuts -> and => instead of function(){} execute() if that is thing1 and that isnt thing2 and/or/not instead of &&/||/! that = thing1 or thing2 that or= thing3
  • 8. Conditionals if condition? (no parantheses, ? is .nil? not .blank?) if condition?() to evaluate if a function returns null throwAFit() unless @name in ["Paul", "John"]
  • 9. How much more? list traversal: for result in results return (transform result for result in results) switch/when/else instead of switch/case/default yes/no, on/off for true/false
  • 10. Show me some code!
  • 11. Some ugly JavaScript var sortFunction = function(a,b) { if (typeof(a[sort_col]) === 'number') { // numeric sort if (sort_dir === 'up') return (a[sort_col] - b[sort_col]); else return (b[sort_col] - a[sort_col]); } else { // string sort var aName = a[sort_col].toLowerCase(), bName = b[sort_col].toLowerCase(); if (sort_dir === 'up') return (aName > bName); else return (bName > aName); } } this.getResults = function(){ // here is the place to apply filter var results = parent.results; if (filter_text) { results = $.makeArray($.map(results, function(result, i){ var haystack = [result.name, result.brands, result.address, result.city].join(', ') return (haystack.indexOf(filter_text) != -1) ? result : null; })); } if (sort_col && sort_dir) { results = results.sort(sortFunction); } return results; }
  • 12. class Results setSort: (col, dir) -> if col? and dir? results = _(@results).sortBy (result) -> result[col] @results = if dir is 'down' then results.reverse() else results setFilter: (filter) -> if filter? matching = (needle) -> haystack = _.join needle.name, needle.brand_list, needle.address, needle.city _(haystack).includes(needle) @results = _.select @results, matching
  • 13. standard jQuery with object binding $('#view_as_table').click => @.setViewType('Table', true) $('#view_as_thumbs').click => @.setViewType('Thumb', true) $('#view_as_list').click => @.setViewType('List', true)
  • 14. Big Long jQuery Call var makeSortable = function(){ $('#widgets .col').sortable({ items: 'div.widget', dropOnEmpty: true, handle: '.header h3', appendTo: 'body', connectWith: '.col', ... }); makeSortable = -> $('#widgets .col').sortable items: 'div.widget' dropOnEmpty: yes handle: '.header h3' appendTo: 'body' connectWith: '.col' revert: yes cursor: 'move' placeholder: 'drag-over' stop: updateWidgetOrder
  • 15. class JKT.GoogleLoader constructor: (callback) -> @callback = callback if google? then @loadComponent() else @loadGoogle() loadComponent: -> return loadGoogle: () -> script = document.createElement "script" script.src = "http://www.google.com/jsapi?key=#{JKT.google_api_key}&sensor=false" script.type = "text/javascript" if script.attachEvent? # IE script.attachEvent 'onreadystatechange', => if script.readyState in ['loaded', 'complete'] @loadComponent() else script.onload = => @loadComponent() document.getElementsByTagName("head")[0].appendChild(script) class JKT.MapLoader extends JKT.GoogleLoader loadComponent: -> google.load 'maps', '3', other_params: "sensor=false" callback: @callback return
  • 16. super Is Super class JKT.Search.TableRenderer constructor: (results) -> @results = results render: -> $('#results').html $('#listing_grid').render [{foo:"bar"}] $('#results tbody').html $('#listing_grid_row').render(@results) class JKT.Search.MapRenderer extends JKT.Search.TableRenderer render: -> super if @results.length <= 300 $('#results tbody tr').each -> ...
  • 17. class Results ... paginate: (start, end) -> if start? and end? @results = @results[start..end] toSentence: -> size = _.size(@results) or 0 if size is 1 then "1 result" else "#{size} results" enoughForMap: -> _.size(@results) < 300 any : -> _.isArray(@results) and _.any(@results)
  • 19. I already know JavaScript Kudos to you. I do too. Not a substitute for knowing JS. Your own JS isn't as clean as the compiled JS Unless your last name is Resig or Crockford
  • 20. It looks weird. It's the bastard child of Ruby and Python. Once you get used to it, it's the JS that looks whack.
  • 21. I don't write JS, I write jQuery. No you write JS using jQuery. I use jQuery too. CS makes your jQuery cleaner.
  • 22. Sugar Allergies Are you allergic to "syntactic sugar"? CS is more than that. We need a better name because we all know sugar is bad for you. Line Noise Reduction
  • 23. Sugar = Noise Reduction Bad line noise highly affects the readability of our code. It is true we get used to them, but once you remove it, there's no way back. - Jose Valim
  • 24. Indentation Allergies "I like my curly braces" CS uses Pythonic whitespace You get used to it - cost/benefit I really don't understand why using indentation level for blocks is so controversial. You do indentation anyway; you don't want to violate OAOO; it avoids hard-to-spot errors where indentation and begin/end or {/} differ; it looks cleaner; there's no way to have unmatched braces; and I never get indentation wrong, but sometimes I do have to count braces. In other words, don't let this issue stop you from trying out Python; indentation-denoted blocks are very easy to get used to. -- Falk Bruegmann
  • 25. Firebug Will Break You lose the correspondence between your code and line numbers in Firebug There is no FireCoffee Use small coffee files to get approximate line correspondence The compiled JS is not magical - you can still read it
  • 26. What about syntax highlighting? No plugin for Eclipse/Aptana Use TextMate, jEdit, gEdit, vim, emacs The TextMate bundle is great!
  • 27. Maybe on the next project Unless your current project is almost done and will never be maintained... Porting that project is just what you need to learn CS. It's not "all or nothing": one file at a time If you don't like it you can keep the change.
  • 28. Where do I start? Don't just dive in or you'll be coding before you're ready Read the CS overview a few times (http://jashkenas.github.com/coffee-script) Install CS and the TextMate bundle Port a project's JS to CS Write some new CS code