Comparison of CoffeeScript with JavaScript, Python and Ruby grammar

I write it like that in Python and Ruby, but I write it down as I think of CoffeeScript.

--Added JavaScript

comment

# comment
# comment
// comment
# comment

Comments that span multiple lines

Python doesn't have multi-line comments, so use a string instead

'''
comment
'''

"""
comment
"""
=begin
comment
=end
/*
comment
*/
###
comment
###

Embedding characters

>>> width = 100
>>> "{0}px".format(width)
"100px"
>>> "%dpx" % width
"100px"
width = 100
p "#{width}px"
# => 100px
width = 100;
console.log("" + width + "px");

Similar to Ruby

width = 100
console.log "#{width}px"
# 100px

A string that spans multiple lines

>>> a = '''a
... b'''
"a\nb"
a = 'a
b'
# => "a\nb"
a = 'a\
      b';
// "a\n     b"
a = 'a
b'
# "ab"

Associative array

d = {'a': 0, 'b': 2}
d = {:a => 0, :b => 2}
d = {a: 0, b: 2}
d = a: 0, b: 2
d = {a: 0, b: 2} #OK
#If it spans multiple lines`,`Can be omitted
d =
  a: 0  #You can also add comments along the way
  b: 2
d = {
  a: 0
  b: 2
}

Array

l = [1, 3, 5]
l = [1, 3, 5]
l = [1, 3, 5]
l = [1, 3, 5]
#If it spans multiple lines`,`Can be omitted
l = [
  1
  3
  5
]

Contiguous array

>>> range(5)
[0, 1, 2, 3, 4]
>>> range(5, 0, -1)
[5, 4, 3, 2, 1]
>>> range(2, 5)
[2, 3, 4]
[0...5]
# [0, 1, 2, 3, 4]
[0..4]
# [0, 1, 2, 3, 4]

[4...-1]
# [4, 3, 2, 1, 0]
[4..0]
# [4, 3, 2, 1, 0]

[2...5]
# [2, 3, 4]
[2..4]
# [2, 3, 4]

Access to the array

>>> l = range(10)
>>> l[1]
1
>>> l[2:4]
[2, 3]
>>> l[2:]
[2, 3, 4, 5, 6, 7, 8, 9]
>>> l[:4]
[0, 1, 2, 3]
>>> l[::3]
[0, 3, 6, 9]
>>> l[-1]
9
>>> l[3:6] = [6, 8, 9]
>>> l
[0, 1, 2, 6, 8, 9, 6, 7, 8, 9]
l = [0...10]
l[1]
# 1
l[2...4]
# [2, 3]
l[2...]
# [2, 3, 4, 5, 6, 7, 8, 9]
l[...4]
# [0, 1, 2, 3]
i for i in l by 3
# [0, 3, 6, 9]
l[l.length-1]]
# 9
l[3...6] = [6, 8, 9]
# [0, 1, 2, 6, 8, 9, 6, 7, 8, 9]

List comprehension

Simple case

>>> l = ['a', 'b', 'c']
>>> [v for v in l]
['a', 'b', 'c']
>>> [(i, v) for i, v in enumerate(l)]
[(0, 'a'), (1, 'b'), (2, 'c')]
>>> d = {'a': 0, 'b': 1, 'c': 2}
>>> [k for k in d]
['a', 'b', 'c']
>>> [(k, v) for k, v in d.items()]
[('a', 0), ('b', 1), ('c', 2)]
l = ['a', 'b', 'c']
v for v in l
# ['a', 'b', 'c']
[v for v in l]
# [ ['a', 'b', 'c'] ]
[i, v] for i, v in l
# [[0, 'a'], [1, 'b'], [2, 'c']]
d = a: 0, b: 1, c: 2
k for k of d
# ['a', 'b', 'c']
[k, v] for k, v of d
# [['a', 0], ['b', 1], ['c', 2]]

Filtering using list comprehension

>>> [i for i in range(10) if i % 3 == 0]
[0, 3, 6, 9]
i for i in [0...10] when i % 3 is 0
# [0, 3, 6, 9]

CoffeeScript list comprehensions can be more varied

>>> for i in range(5)
...     print i
0
1
2
3
4
console.log i for i in [0...5]
# 0
# 1
# 2
# 3
# 4

function

def func(arg, *args):
    pass
def func(arg, *args)
end
var func = function(arg) {
  var args = 2 <= arguments.length ? Array.prototype.slice.call(arguments, 1) : []
}
func = (arg, args...) ->

Function call

Python requires () to call function

>>> def foo(): return 'foo'
>>> foo
<function __main.foo>
>>> foo()
'foo'

No Ruby required

def foo
  'foo'
end
p foo
# => foo
def bar(x)
  x
end
p bar 'bar'
# => bar

JavaScript is not required when instantiating. Required for normal calls

var foo = function() {return 'foo'};
console.log(typeof foo);
// 'function'
console.log(foo());
// 'foo'
f = new foo;
console.log(f.construoctor === foo);
// true

CoffeeScript requires () if no arguments are passed, not required if there are arguments

foo = -> 'foo'
console.log typeof foo
# 'function'
console.log foo()
# foo
bar = (x) -> x
console.log foo 'bar'
# bar

Function return value

return is required for Python and JavaScript. If not, None is returned for Python, and ʻundefined` is returned for JavaScript.

>>> def bar(): 'bar'
>>> bar() is None
True
var bar = function() { 'bar' };
console.log(bar === undefined);
// true

In Ruby and CoffeeScript, the last statement is return.

def bar
  'bar'
end
bar
# => 'bar'
bar = -> 'bar'
bar()
# 'bar'

class

>>> class Klass(object):
...     def __init__(self, name):
...         self.name = name
>>> k = Klass('hoge')
>>> k.name
"hoge"
class Klass
  attr "name"
  def initialize(name)
    @name = name
  end
end
k = Klass.new 'hoge'
p k.name
# => hoge
function Klass(name) {
  this.name = name;
}
var k = new Klass('hoge');
console.log(k.name);
// hoge
class Klass
  constructor: (name) ->
    @name = name
k = new Klass 'hoge'
console.log k.name
# hoge

Inheritance

>>> class Parent(object):
...     def foo(self):
...         print 'parent'
>>> class Child(Parent):
...     def foo(self):
...         super(Child, self).foo()
...         print 'child'
>>> c = Child()
>>> c.foo()
parent
child
class Parent
  def foo
    p 'parent'
  end
end
class Child < Parent
  def foo
    super
    p 'child'
  end
end
c = Child.new
c.foo
# => parent
# => child
function Parent() {}
Parent.prototype.foo = function () { console.log('parent'); };
function Child() {}
Child.prototype = new Parent;
Child.prototype.foo = function () {
  Parent.prototype.foo.call(this);
  console.log('child');
}
var c = new Child;
c.foo();
// parent
// child
class Parent
  foo: ->
    console.log 'parent'
class Child extend 
  foo: ->
    super
    console.log 'child'
c = new Child
c.foo()
# parent
# child

Mixin

module Fooable
  def foo
    p 'foo'
  end
end
class Klass
  include Fooable
end
k = Klass.new
k.foo
# => 'foo
# https://gist.github.com/993415
class Mixin
  augment: (t) ->
    (t[n] = m unless n == 'augment' or !this[n].prototype?) for n, m of this
class Fooable extends Mixin
  foo: ->
    console.log 'foo'
class Klass
  constructor: ->
    Fooable::augment @
k = new Klass
k.foo()
# foo

Recommended Posts

Comparison of CoffeeScript with JavaScript, Python and Ruby grammar
Comparison of Python and Ruby (Environment / Grammar / Literal)
Version control of Node, Ruby and Python with anyenv
Java and Python basic grammar comparison
Scraping with Node, Ruby and Python
Coexistence of Python2 and 3 with CircleCI (1.0)
I compared the speed of Hash with Topaz, Ruby and Python
Speed comparison of Wiktionary full text processing with F # and Python
(Java, JavaScript, Python) Comparison of string processing
Linking python and JavaScript with jupyter notebook
Encrypt with Ruby (Rails) and decrypt with Python
Easy web scraping with Python and Ruby
Comparison of matrix transpose speeds with Python
Correspondence summary of array operation of ruby and python
Instant method grammar for Python and Ruby (studying)
Performance comparison of face detector with Python + OpenCV
Specifying the range of ruby and python arrays
Implementation of TRIE tree with Python and LOUDS
Comparison of R and Python writing (Euclidean algorithm)
Continuation of multi-platform development with Electron and Python
Example of reading and writing CSV with Python
Ruby, Python and map
Python and Ruby split
Solve with Ruby and Python AtCoder ABC084 D Cumulative sum of prime numbers
[Ruby vs Python] Benchmark comparison between Rails and Flask
Visualize the range of interpolation and extrapolation with python
A quick comparison of Python and node.js test libraries
Comparison table of frequently used processes of Python and Clojure
Programming with Python and Tkinter
Encryption and decryption with Python
Python and hardware-Using RS232C with Python-
Python on Ruby and angry Ruby on Python
Python and ruby slice memo
Python installation and basic grammar
Zundokokiyoshi with python / ruby / Lua
Ruby and Python syntax ~ branch ~
python with pyenv and venv
Python 3 sorted and comparison functions
Comparison of Apex and Lamvery
Source installation and installation of Python
Python (Python 3.7.7) installation and basic grammar
Works with Python and R
Solving with Ruby and Python AtCoder ARC 059 C Least Squares
Five languages basic grammar comparison (C #, Java, Python, Ruby, Kotlin)
Solving with Ruby and Python AtCoder ABC178 D Dynamic programming
Learn "English grammar" instead of Python and AI related English words. .. ..
Perform isocurrent analysis of open channels with Python and matplotlib
Solving with Ruby and Python AtCoder ABC151 D Breadth-first search
I wrote the basic grammar of Python with Jupyter Lab
Solving with Ruby and Python AtCoder AISING2020 D Iterative Squares
Get rid of dirty data with Python and regular expressions
Solving with Ruby, Perl, Java and Python AtCoder ATC 002 A
Summary of Hash (Dictionary) operation support for Ruby and Python
Comparison of how to use higher-order functions in Python 2 and 3
Solving with Ruby and Python AtCoder ABC011 C Dynamic programming
Solving with Ruby and Python AtCoder ABC153 E Dynamic programming
Solving with Ruby, Perl, Java and Python AtCoder ATC 002 B
Solving with Ruby and Python AtCoder ABC138 D Adjacency list
Sample of HTTP GET and JSON parsing with python of pepper
Play with the password mechanism of GitHub Webhook and Python
AtCoder JSC2019 Qual B to solve with Ruby and Python Inverse element of arithmetic progression