• Stars
    star
    157
  • Rank 238,399 (Top 5 %)
  • Language
  • Created almost 10 years ago
  • Updated about 8 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

CoffeeScript Equivalents In ES6

CoffeeScript equivalents in ECMAScript6/ES2015

Inspiration from es6-equivalents-in-es5

Note: a few of these examples are taken from CoffeeScript's own website.

Topics

Statements as Expressions

CoffeeScript: cs-doc

grade = (student) ->
  unless student?
    throw new Error 'student is required'
  else if student.excellentWork
    'A+'
  else if student.okayStuff
    if student.triedHard then 'B' else 'B-'
  else
    'C'

eldest = if 24 > 21 then 'Liz' else 'Ike'

ES6 equivalent:

// There is no exact equivalent, but there are ternary expressions for common
// cases like above.
const grade = (student = new Error('student is required')) => {
   if (student.excellentWork) {
    return 'A+';
  } else if (student.okayStuff) {
    return student.triedHard ? 'B' : 'B-';
  } else {
    return 'C';
  }
}

let eldest = 24 > 21 ? 'Liz' : 'Ike';

Note: you might want to watch discussion on do-expressions if you are interested in this feature. Note that the code below may not reflect the proposal in its current state.

// With current do-expression proposal, stage 0
let grade = student => do {
  if (student == null) {
    throw new Error('student is required')
  } else if (student.excellentWork) {
    'A+';
  } else if (student.okayStuff) {
    student.triedHard ? 'B' : 'B-';
  } else {
    'C';
  }
}

Arrow Functions

CoffeeScript: cs-doc

readConfig = (file, parse) ->
  new Promise (resolve) ->
      fs.readFile file, 'utf8', (err, data) =>
        if err?
          reject err
        else
          resolve parse data

ES6 equivalent: es6-doc

function readConfig(file, parse) {
  return new Promise(resolve =>
    fs.readFile(file, 'utf8', (err, data) =>
      err != null ?
        reject(err) :
        resolve(parse(data)));
}

Splats

CoffeeScript: cs-doc

race = (winner, runners...) ->
    console.log winner, runners

race 'Bob', runnerList...

ES6 equivalent: es6-doc

let race = (winner, ...runners) =>
    console.log(winner, runners);

race('Bob', ...runners);

Array Comprehensions

CoffeeScript: cs-doc

numbers = [ 1, 4, 9 ];
(Math.sqrt num for num in numbers)
# -> [1, 2, 3]

ES6 equivalent:

let numbers = [ 1, 4, 9 ];
numbers.map(num => Math.sqrt(num));
// -> [1, 2, 3]

ES7 equivalent: es6-doc

let numbers = [ 1, 4, 9 ];
[for (num of numbers) Math.sqrt(num)];
// -> [1, 2, 3]

Default Params

CoffeeScript: cs-doc

log = (message, level='log') -> console[level](message)

ES6 equivalent: es6-doc

let log = (message, level = 'log') => console[level](message);

String interpolation / Template strings

CoffeeScript: cs-doc

container = 'mug'
liquid = 'hot chocolate'
console.log "Filling the #{container} with #{liquid}..."
# -> "Filling the mug with hot chocolate..."

ES6 equivalent: es6-doc

let container = 'mug'
   ,liquid = 'hot chocolate';
console.log(`Filling the ${container} with ${liquid}...`);
// -> "Filling the mug with hot chocolate..."

Lexical Scope and Variable safety.

CoffeeScript: cs-doc

inner = 10
value = 20

# literally an IIFE
do (inner = 5, value = 10) ->
  console.log inner # 5

console.log inner # 10

ES6 equivalent: es6-doc (let, const)

let inner = 10;
const value = 20;

// A simple block
{
  let inner = 5;
  
  // not an error, despite being a constant in the outer scope
  const value = 10;
  console.log(inner); // 5
}

console.log(inner); // 10

Function binding

CoffeeScript: cs-doc

hero =
  name: "Batman"
  alterEgo: "Bruce Wayne"
  enemies: ['Two-Face', 'Bane']
  printEnemies: ->
    @enemies.forEach((enemy) =>
      console.log @name + " fights " + enemy);

hero.printEnemies()
# -> "Batman fights Two-Face"
# -> "Batman fights Bane"

ES6 equivalent: es6-doc

let hero = {
  name: "Batman",
  alterEgo: "Bruce Wayne",
  enemies: ['Two-Face', 'Bane'],
  printEnemies() {
    this.enemies.forEach(enemy =>
      console.log(this.name + " fights " + enemy));
  }
};

hero.printEnemies();
// -> "Batman fights Two-Face"
// -> "Batman fights Bane"

Classes, Inheritance, and Super

CoffeeScript: cs-doc

class Person
  constructor: (@name) ->
    @movement = "walks"

  move: (meters) ->
    console.log "#{@name} #{@movement} #{meters}m."

class Hero extends Person
  constructor: (@name, @movement) ->

  move: ->
    super 500

clark = new Person "Clark Kent"
superman = new Hero "Superman", "flies"

clark.move(100)
# -> Clark Kent walks 100m.
superman.move()
# -> Superman flies 500m.

ES6 equivalent: es6-doc

class Person {
  constructor(name) {
    this.name = name;
    this.movement = "walks";
  }

  move(meters) {
    console.log(`${this.name} ${this.movement} ${meters}m.`);
  }
}

class Hero extends Person {
  constructor(name, movement) {
    this.name = name;
    this.movement = movement;
  }

  move() {
    super.move(500);
  }
}

let clark = new Person("Clark Kent");
let superman = new Hero("Superman", "flies");

clark.move(100);
// -> Clark Kent walks 100m.
superman.move();
// -> Superman flies 500m.

Destructuring Assignment

CoffeeScript: cs-doc

hero =
  name: "Spider-Man"
  alterEgo: "Peter Benjamin Parker"
  enemies: ["Electro", "Doctor Octopus"]

{name, alterEgo} = hero
# name = "Spider-Man"
# alterEgo = "Peter Benjamin Parker"

[head, tail...] = [1, 2, 3, 4, 5]
# head = 1
# tail = [2, 3, 4, 5]

ES6 equivalent: es6-doc

let hero = {
  name: "Spider-Man",
  alterEgo: "Peter Benjamin Parker",
  enemies: ["Electro", "Doctor Octopus"]
};

let {name, alterEgo} = hero;
// name = "Spider-Man"
// alterEgo = "Peter Benjamin Parker"

let [head, ...tail] = [1, 2, 3, 4, 5];
// head = 1
// tail = [2, 3, 4, 5]

Array Slicing

CoffeeScript: cs-doc

part1 = list[0..3]  # with end
part2 = list[0...3] # without end
part3 = list[..3]   # start defaults to 0
part4 = list[3..]   # end defaults to length

clone = list[..] # Clone the array
let part1 = list.slice(0, 3);
let part2 = list.slice(0, 4);
let part3 = list.slice(0, 3);
let part4 = list.slice(3);

// More than one way to clone an array
let clone;
clone = list.slice();
clone = list.concat();

Array Splicing

CoffeeScript: cs-doc

numbers[3..6] = [-3, -4, -5, -6]
numbers[3..6] = list

ES6 equivalent:

numbers.splice(3, 4, -3, -4, -5, -6)
[].splice.apply(numbers, [3, 4].concat(list))

Ranges

CoffeeScript: cs-doc

numbers = [0...5]
positives = [1...10]

ES6 equivalent:

let numbers = Array(5).map((_, i) => i);
let positives = Array(10).slice(1).map((_, i) => i);

// Or, you can make a custom range function (which is faster)
function range(start, end) {
  if (end == null) [start, end] = [0, start];
  const ret = [];
  while (start < end) ret.push(start++);
  return ret;
}

Chained Comparisons

CoffeeScript: cs-doc

cholesterol = 127

healthy = 60 < cholesterol < 200

ES6 equivalent:

let cholestrol = 127;

let healthy = 60 < cholestrol && cholestrol < 200;

Block Regular Expressions

CoffeeScript: cs-doc

OPERATOR = /// ^ (
  ?: [-=]>             # function
   | [-+*/%<>&|^!?=]=  # compound assign / compare
   | >>>=?             # zero-fill right shift
   | ([-+:])\1         # doubles
   | ([&|<>])\2=?      # logic / shift
   | \?\.              # soak access
   | \.{2,3}           # range or splat
) ///

ES6 equivalent:

// There isn't really any. This doesn't get the engine-related caching that
// regex literals often get.
let OPERATOR = new RegExp('^(' +
  '?:[-=]>' +             // function
   '|[-+*/%<>&|^!?=]=' +  // compound assign / compare
   '|>>>=?' +             // zero-fill right shift
   '|([-+:])\\1' +        // doubles
   '|([&|<>])\\2=?' +     // logic / shift
   '|\\?\\.' +            // soak access
   '|\\.{2,3}' +          // range or splat
')')

Operators and Aliases

CoffeeScript: cs-doc

  • True: true, yes, on
  • False: false, no, off
  • And: a && b, a and b
  • Or: a || b, a or b
  • Not: !a, not a
  • Equality: a == b, a is b
  • Inequality: a != b, a isnt b
  • Current Instance: @, this
  • Instance Property: @prop, this.prop
  • Contains Property: prop of object
  • Contains Entry: a in b
  • Exponentiation: x ** y
  • Floor Division: x // y
  • Always-positive Modulo: x %% y

ES6 Equivalents: es6-doc

  • True: true
  • False: false
  • And: a && b
  • Or: a || b
  • Not: !a
  • Equality: a === b
  • Inequality: a !== b
  • Current Instance: this
  • Instance Property: this.prop
  • Contains Property: prop in object
  • Contains Entry: a.indexOf(b) >= 0
    • For strings (and arrays in ES7) only: a.includes(b)
    • For iterables in ES6 (such as some DOM nodes): Array.from(a).indexOf(b) >= 0
  • Exponentiation: Math.exp(x, y)
    • ES7: x ** y
  • Always-positive Modulo: (a % b + b) % b

Generators

CoffeeScript: cs-doc

identity = (iter) ->
  yield from iter

range = lazyRange 10
range = identity range

ES6 equivalent: es6-doc

function *lazyRange(n) {
  for (let i = 0; i < n; i++) {
    yield i;
  }
}

function* identity(iter) {
  yield* iter
}

let range = lazyRange(10);
range = identity(range);

Loops and Iteration

CoffeeScript: cs-doc

isOkay = (entry) ->
  # ...

# numbers 0-9
console.log i for i in [0..10]

# evens 0-8
console.log i for i in [0..10] by 2

node = getFirst()
node = node.next while isOkay node

console.log i for i in list

console.log i for i in list when isOkay i

# own object properties
for own prop, value of object
  console.log prop
  console.log object[prop]

ES6 equivalent: es6-doc

function isOkay(entry) {
  // ...
}

// Standard `for` loops
for (let i = 0; i < 10; i++) {
  console.log(i);
}

for (let i = 0; i < 10; i += 2) {
  console.log(i);
}

let node = getFirst();
while (isOkay(node)) {
  node = node.next;
}

// `for ... of` loops
for (let i of list) {
  console.log(i);
}

for (let i of list) {
  if (isOkay(i)) {
    console.log(i);
  }
}

for (let prop of Object.keys(object)) {
  console.log(prop);
  console.log(object[prop]);
}

// Array methods (last three)
Array.from(list).forEach(i => console.log(i))

Array.from(list).filter(isOkay).forEach(i => console.log(i));

Object.keys(object).forEach(prop => {
  console.log(prop);
  console.log(object[prop]);
});

Switch Statements

switch day
  when "Mon" then go work
  when "Tue" then go relax
  when "Thu" then go iceFishing
  when "Fri", "Sat"
    if day is bingoDay
      go bingo
      go dancing
  when "Sun" then go church
  else go work

ES6 Equivalent: es6-doc

switch (day) {
case "Mon": go("work"); break;
case "Mon": go("work"); break;
case "Tue": go("relax"); break;
case "Thu": go("iceFishing"); break;
case "Fri": case "Sat":
  if (day === "bingoDay") {
    go("bingo");
    go("dancing");
  }
  break;
case "Sun": go("church"); break;
default: go("work");
}

Contributors

More Repositories

1

functional-programming-jargon

Jargon from the functional programming world in simple terms!
18,586
star
2

awesome-pwa

Awesome list of progressive web apps! (PR welcomed ;))
4,416
star
3

es-next

stage-0 to stage-4 ECMAscript proposals.
677
star
4

paws-on-es6

Minimalist examples of ES6 functionalities.
JavaScript
332
star
5

awesome-now

Awesome list of `now.sh` deployments.
238
star
6

node-nightly

node-nightly at your fingertips!
JavaScript
233
star
7

koa-rest

REST demo with koa.
JavaScript
218
star
8

jsfeatures.in

All javascript features under one hood!
HTML
104
star
9

cors-now

reverse proxy with CORS headers.
JavaScript
96
star
10

awesome-dev-domains

List of awesome `.dev` domains.
53
star
11

generator-pwa

Yeoman generator for a progressive webapp.
JavaScript
51
star
12

is-pwa

Detects if a given URL is a Progressive WebApp (PWA.)
JavaScript
46
star
13

nmotw.in

Node Module Of The Week
HTML
40
star
14

head-it

Easy interface for `head`
JavaScript
40
star
15

generator-atom

Yeoman generator for atom editor packages.
JavaScript
39
star
16

cds

Chrome DevSummit Notes
37
star
17

node-prepend-file

Prepend data to a file.
JavaScript
34
star
18

power-off

Cross OS power-off.
JavaScript
33
star
19

ollama-models

Repository of Ollama Models!
Python
30
star
20

interview-time

Prepare for your technical interviews!
JavaScript
29
star
21

futhark

Collection of all my old and new scripts written in bash, python, ruby and more
PHP
29
star
22

bangalore-startups

Ever growing list of startups in Bangalore.
JavaScript
28
star
23

config-hyperterm

Easily set/get `hyperterm` config.
JavaScript
28
star
24

es6-lab-setup

Setup your ES6 Lab.
JavaScript
27
star
25

ramda-repl

Ramdajs REPL.
JavaScript
27
star
26

curl-to-fetch

Parse curl commands and returns `fetch` API equivalent.
JavaScript
25
star
27

hello-falcor

A simple faclor.js example.
HTML
22
star
28

manifest-json

Creates manifest.json for your PWA.
JavaScript
22
star
29

why-babies-cry

A desperate attempt to list them all!
21
star
30

blns

Big List of Naughty Strings.
JavaScript
21
star
31

gulp-cleanhtml

remove unneeded whitespaces, line-breaks, comments, etc from the HTML.
JavaScript
19
star
32

atom-mdurl

Convert normal url to md style. My birthday gift for @sindresorhus using his own module ;)
CoffeeScript
19
star
33

greener

Fetches all your node modules and keeps them green, with greenkeeper.
JavaScript
19
star
34

grunt-usemin-example

Minimalist example of grunt-usemin.
JavaScript
18
star
35

quotes

My fav quotes.
HTML
18
star
36

algorithms

Implementations of most commonly used algorithms in various languages. Thanks a ton to the wiki's which provided pesudo codes
Java
17
star
37

graphql-demo

Simple graphql server app.
JavaScript
17
star
38

gulp-jstransform

Gulp plugin to transform ES6 to ES5.
JavaScript
16
star
39

video-in-view

Play/Pause video when in/out of the view.
JavaScript
16
star
40

algorithms-es6

Basic Algorithm Implementation with ES6.
16
star
41

p2pu

Scripting 101 on p2pu
Shell
16
star
42

react-mui-base

BaseComponent for react-material-ui
JavaScript
15
star
43

joel-test

Rate the quality of a software team!
JavaScript
14
star
44

haskell-rascal

Learning haskell with a rascal!
14
star
45

blood-donor

Donors for a blood type.
JavaScript
13
star
46

test-card

Credit, Debit and Prepaid cards for testing.
JavaScript
13
star
47

speech-synthesis

Speaks using the Web Speech API.
JavaScript
13
star
48

liked

I liked
12
star
49

xkcd-img

Custom Polymer element for displaying random images from XKCD!
HTML
12
star
50

video-bg

Custom polymer element to set a responsive video as your HTML background.
HTML
12
star
51

life-expectancy

Life expectancy of humans across the global.
JavaScript
12
star
52

is-iterable

Checks if a given object is iterable.
JavaScript
11
star
53

flat-xkcd

Exploring Flat Data Workflow
JavaScript
11
star
54

is-incognito

Detects incognito mode.
JavaScript
11
star
55

battery-status

Custom Polymer element for dispalying battery status.
HTML
11
star
56

node-yoda-said

Yoda quotes on CLI a trribute to Master Yoda!
JavaScript
11
star
57

react-suspense-sample

Async Image Loading with React Suspense
JavaScript
11
star
58

gulp-html2txt

gulp plugin to convert html file to txt.
JavaScript
10
star
59

node-rsj

rss as json
JavaScript
10
star
60

debug-yeoman-generator

Simple bash util script that helps you to debug yeoman generators.
Shell
10
star
61

is-mp3

Check if a Buffer/Uint8Array is MP3 file.
JavaScript
10
star
62

nw-wiki-app

A simple sample app to demo the usage of node-webkit.
JavaScript
10
star
63

tc39-members

TC39 members list.
10
star
64

github-upstreamer

Auto configure a remote for a fork!
JavaScript
10
star
65

fetch-task

fetch API as a Task.
JavaScript
10
star
66

rgbot

XMPP Gmail Bot in rb ; rb+gmail+bot => rgbot
Ruby
10
star
67

make-quote

Type a quote and get an image of the same.
CSS
9
star
68

get-hosts

`etc/hosts` as an array of objects.
JavaScript
9
star
69

orly-cover-bot

The source that is governing https://twitter.com/OreillyCover
JavaScript
9
star
70

gulp-html2jade

gulp plugin to convert HTML to Jade format.
JavaScript
9
star
71

gulp-html2jsx

Converts HTML to JSX for use with React.
JavaScript
9
star
72

react-currency-conversion

Component to convert currency on the current exchange rates.
JavaScript
9
star
73

xkcd-gem

XCKD ruby gem to get random img url or comic urls
Ruby
9
star
74

sanskrit-dict

Sanskrit dictionary.
JavaScript
8
star
75

node-octodex

Get random octodex images from github's octodex.
JavaScript
8
star
76

node-xkcd-img

xkcd-img module for node.js
JavaScript
8
star
77

time-taken

Get the execution time of a function.
JavaScript
8
star
78

local-time

Custom Polymer time element, to convert UTC to local time.
HTML
8
star
79

network-type

Get the network type.
JavaScript
8
star
80

node-systemize

Systemize your junkyard. (Organise your files.)
JavaScript
8
star
81

generator-amp

generator for AMP.
JavaScript
7
star
82

react-native-xkcd

Loads random XKCD comics (WIP)
Objective-C
7
star
83

gulp-hogan

gulp plugin to compile mustache templates
JavaScript
7
star
84

github-avatar-url

Get github's avatar URL either by `username` or `email`.
JavaScript
7
star
85

gandhi-quotes

Gandhi quotes on CLI a trribute to Gandhi!
JavaScript
7
star
86

GandhiSaid

Simple react-native app to get random quotes of Gandhi on each tap.
Objective-C
7
star
87

Map.prototype.toJSON

ES7 Map.prototype.toJSON polyfill.
JavaScript
7
star
88

gntr

Tree traversal with ES6 generator
JavaScript
7
star
89

inline-elements

Array of "inline elements" defined by the HTML specification.
JavaScript
7
star
90

exude

Execute the OS specific command.
JavaScript
7
star
91

node-lie-fs

Promise wrappers for Node's file system.
JavaScript
6
star
92

PaLM-CLI-Bot

CLI Chat bot using PaLM API
Python
6
star
93

crypto-jargon

Lingo from cryptocurrencies, trading, blockchain et.al. [WIP]
6
star
94

screen-type

Simple util to detect the screen-type.
JavaScript
6
star
95

grunt-html2jsx

Converts HTML to JSX for use with React.
JavaScript
6
star
96

is-flac

Check if a Buffer/Uint8Array is a FLAC file.
JavaScript
6
star
97

math-pad

Simple electron app for doing your math.
CSS
6
star
98

is-wav

Check if a Buffer/Uint8Array is a WAV file.
JavaScript
6
star
99

wikiquote-gem

Quote of the day from wikiquotes
Ruby
6
star
100

is-ogg

Check if a Buffer/Uint8Array is a OGG file.
JavaScript
6
star