-
Notifications
You must be signed in to change notification settings - Fork 1
Home
comerc edited this page Dec 3, 2018
·
9 revisions
function hello() { console.log("Hello World") }
defmodule HelloWorld do
def hello do
IO.puts "Hello World"
end
end
These are now called arrow Functions in Javascript. Example with Array.Map
let numbers = [1 , 2, 3]
let double = numbers.map( number => number * 2 )
console.log(double)
numbers = [1, 2, 3]
double = Enum.map( numbers , fn(number) -> number * 2 end )
IO.inspect double
## Another way to write Anonymous Functions
numbers = [1, 2, 3]
double = Enum.map( numbers , &(&1 * 2 ))
IO.inspect double
Elixir has pretty powerful pattern matching and can be used in Function Signatures and Case Statements. Javascript has something similarish with ES6, Object Destructuring
const { id: userId } = { id: 'xxxx-xxxxx', name: 'John Doe' };
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(a); // 10
console.log(b); // 20
console.log(rest); // [30, 40, 50]
// Following Elixirs patter we can write a Recursive function by Destructuring using [head , ...tail]
[head, ...tail ] = [10, 20, 30, 40, 50];
user = %{name: "Tom", age: 23}
%{name: username} = user
[head | tail] = [1, 2, 3]
customer = { name: 'John Doe',
address: '255 Wellington Street West',
city: 'Toronto',
hobbies: [ 'cooking', 'fishing', 'photography' ] }
// Destructuring in JS
{name: customer_name} = customer
// Shorthand Syntax
{name} = customer
//Access
console.log(customer.name)
customer = %{ name: "John Doe"
address: "255 Wellington Street West",
city: "Toronto",
hobbies: ["cooking", "fishing", "photography"]
}
# Pattern Match - map
%{ name: customer_name } = customer
#Access
IO.puts customer[:address]
IO.puts customer.address
for( let value of my_list ){
console.log(value*value)
}
//4
//16
//36
my_list = [2, 4, 6]
#[2, 4, 6]
for value <- my_list, do: value * value
#[4, 16, 36]