require('./app')
.config($stateProvider => {
$stateProvider.state('main', {
url: '/'
template: `
<div class="container">
<h1>Hello ES6!</h1>
</div>
`,
controller: 'MainCtrl',
resolve: {
users: User => User.fetchAll()
}
})
)}
.controller('MainCtrl', function ($scope, users) {
$scope.checkNumUsers = () => console.log(`There are ${ users.length } users!`;
});
/* writing a tag function
the first argument is an array of the string elements of the template
subsequent arguments are each of the template values
for this reason, it's easiest to use the spread operator!
*/
let city = "San Diego";
function tag (strings, ...values) {
console.log(strings) // [ 'Stay classy', '!' ]
console.log(values) // [ 'San Diego' ]
return [strings[0], ...values].join(', ') + strings[1];
}
// to use the tag, you just...well..."tag" it onto the front of the template string!
tag`Stay classy${city}!`; // Stay classy, San Diego!
// if you already have variables containing the data you want in your object...
let restaurants = [{ name: 'Bergn' }],
hotel = { name: 'Waldorf Astoria' },
attractions = [{ name: 'High Line' }];
// go ahead and directly assign them in the object literal!
const tripData = {
restaurants,
hotel,
attractions
};
tripData.restaurants.length // 1
tripData.hotel.name // 'Waldorf Astoria'
// we can compute key names however we want!
let randomNumber = Math.floor(Math.random() * 100); // calculates 42
const obj = {
[`property_num_${randomNumber}`]: randomNumber
};
console.log(obj.property_num_42); // 42
// An object with methods written right inside! Just like a class!
const StackProto = {
peek () {
return this.memory[this.pointer];
},
push (value) {
typeof value === 'undefined' ? null : this.memory[++this.pointer] = value;
return this;
},
pop () {
if (this.pointer <= -1) throw new Error('Empty stack');
return this.memory[--this.pointer];
}
}
function Stack () {
this.memory = [];
this.pointer = -1;
}
Stack.prototype = Object.assign(Stack.prototype, StackProto);
// swapping two values, the old way
function oldSwap (a, b) {
let temp = a;
a = b;
b = temp;
}
// performing a simple swap
function newSwap (a, b) {
[a, b] = [b, a];
}
// un-packaging an array into individual variables
function favoriteDogs () {
return ["Cooper", "Ben", "Patrick", "Cody"];
}
let [cooper, ben, patrick, cody] = favoriteDogs();
// this is the equivalent of saying:
// let cooper = favoriteDogs()[0];
// let ben = favoriteDogs()[1]
// etc....
console.log(cooper); // "Cooper"
'use strict';
// 'extract' values from objects
const { Router } = require('express');
const router = Router();
// equivalent to:
const Router = require('express').Router;
const router = Router();
// you can also extract in function definitions
const setUpSockets = ({io}) => io(80);
setUpSockets(require('socket.io');
// equivalent to:
function setUpSockets (socket) {
socket.io(80);
}
setUpSockets(require('socket.io');