/javascript-vs-elixir

🌪 Quick comparison between js and elixir codes

Primary LanguageElixirMIT LicenseMIT

📌 Unordered random list of transpiles for JavaScript and Elixir

JS TO ELIXIR

Table of contents

Map

Filter

Reduce

Every

Some

Each

Sort

Unique by

Size of list

List concat

Split by regex

String replace all

String interpolation

Map

[1, 2, 3].map(x => x * 2) // -> [ 2, 4, 6 ]
Enum.map([1, 2, 3], fn(x) -> x * 2 end)

Filter

[1, 2, 3, 4].filter(x => x % 2) // -> [ 1, 3 ]
Enum.filter([1, 2, 3, 4], fn(x) -> rem(x, 2) != 0 end)

Reduce

["A", "B", "C"].reduce((x, acc) => x + acc) // -> 'ABC'
Enum.reduce(["A", "B", "C"], fn(x, acc) -> acc <> x end)

Every

[11, 13, 15].every(x => x > 10) // -> true
Enum.all?([11, 13, 15], fn(x) -> x > 10 end)

Some

["Apple", "Microsoft"].some(x => x.length > 6) // -> true
Enum.any?(["Apple", "Microsoft"], fn(x) -> String.length(x) > 6 end)

Each

["Fish", "Fisherman", "Phising"].forEach(x => console.log(x)) // -> Fish ...
Enum.each(["Fish", "Fisherman", "Phising"], fn(x) -> IO.puts x end)

Sort

[2, 2, 4, 6].sort((a, b) => b - a) // -> [ 6, 4, 2, 2 ]
Enum.sort([2, 2, 4, 6], fn(a, b) -> a > b end)

# Alternative
Enum.sort([2, 2, 4, 6], :desc)

Unique by

[...new Set([1, 1, 2, 2, 3])] // -> [ 1, 2, 3 ]
Enum.uniq_by([1, 1, 2, 2, 3], fn(x) -> x end)
Advacned

In Elixir, compare function helps normalizing objects easliy.

Enum.uniq_by([a: {:tea, 2}, b: {:tea, 2}, c: {:coffee, 1}], fn {_, y} -> y end)

# -> [a: {:tea, 2}, c: {:coffee, 1}]

Don't want to write this code in JavaScript :(

Size of list

[1, 2].length // -> 2
Enum.count([1, 2])

List concat

[...[1, 2], ...[3, 4]] // -> [ 1, 2, 3, 4 ]
[1, 2] ++ [3, 4]

Split by regex

"100_000_000".split(/_/) // -> [ '100', '000', '000' ]
Regex.split(~r/_/, "100_000_000")

String replace all

"Helloooo".replace(/o/g, "a") // -> 'Hellaaaa'
String.replace("Helloooo", "o", "a")

String interpolation

`It is ${1 + 2} of the clock` // -> 'It is 3 of the clock'
"It is #{1 + 2} of the clock"