Skip to content

Instantly share code, notes, and snippets.

View alexnm's full-sized avatar

Alex Moldovan alexnm

View GitHub Profile
@alexnm
alexnm / arrow-functions.js
Last active January 10, 2016 15:51
Exemplifying ES2015 sytanx
// Basic syntax examples
var add = ( a, b ) => a + b; // function( a, b ) { return a + b; }
var increment = a => a + 1; // function( a ) { return a + 1; }
var random = ( ) => Math.random( ) // function( ) { return Math.random( ); }
// Functional programming unleashed
var array = [ 'alice', 'bob', 'charles', 'dan', 'eugene', 'felicity' ];
var longNames = array.filter( name => name.length > 3 );
var longNamesIndexes = longNames.map( ( name, index ) => index );
var sumOfIndexes = longNamesIndexes.reduce( add );
if ( condition ) {
let x = 1;
const y = 2;
var z = 3;
x = 4;
y = 5;
z = 6;
console.log( x ); // 4
// A factory method which returns an object
const factory = ( ) => { a: 1, b: 2 }
const { a, b } = factory( ); // a = 1, b = 2
// A method that takes a Person object as a parameter and returns the full name
// firstName and lastName get destructured into variables inside the function
const fullName = ( { firstName, lastName } ) => firstName + ' ' + lastName;
const person = {
firstName: 'Alex',
lastName: 'M',
// Default parameters
const add = ( a, b = 1 ) => a + b;
add( 2, 4 ); // 6 - add
add( 3 ); // 4 - increment
// Rest parameters
const add = ( ...args ) => args.reduce( ( a, b ) => a + b );
add( 2, 4 ); // 6
add( 1, 2, 3, 4, 5 ); // 15
add( 5 ); // 5
function* fibonacci( ){
let n1 = 0;
let n2 = 1;
while ( true ) {
const current = n1;
n1 = n2;
n2 = current + n1;
yield current;
}
}
function* ( ) {
const user = yield getUser( ); // async api call
const cart = yield getShoppingCart( user ); // async api call
const items = yield getItems( user, cart ); // aync api call
}
class Rectangle extends Shape {
constructor( x, y, color ) {
super( color );
this.x = x;
this.y = y;
this.color = color
}
get length( ) {
@alexnm
alexnm / object-literal.js
Last active March 27, 2016 16:41
Example of object creation through object literal
const product = {
name: 'T-Shirt',
price: 9.99,
color: 'red',
size: 'M',
stock: 4,
updateStock: function( newStock ) {
this.stock += newStock;
}
};
@alexnm
alexnm / object-constructor.js
Last active March 27, 2016 16:59
Example for constructor based object creation
function Product( initialStock ) {
let stock = initialStock;
/* ... extra fields omitted for simplicity ... */
this.updateStock = function( newStock ) {
stock += newStock;
}
this.getStock = function( ) {
return stock;
@alexnm
alexnm / object-factory.js
Created March 27, 2016 17:15
Example of factory based object creation
function createProduct( initialStock ) {
let stock = initialStock;
return {
/* ... extra fields omitted for simplicity ... */
updateStock( newStock ) {
stock += newStock;
},
getStock( ) {
return stock;