Skip to content

Instantly share code, notes, and snippets.

@chaoticsmol
Created September 10, 2015 01:23
Show Gist options
  • Save chaoticsmol/79e27fd00f5388fabad7 to your computer and use it in GitHub Desktop.
Save chaoticsmol/79e27fd00f5388fabad7 to your computer and use it in GitHub Desktop.
Playing with some of the new ES6 features supported in JS as of Node.js v4.0
"use strict";
let fs = require('fs');
// ARROW FUNCTIONS!!!
console.log([1,2,3].map(x => x * x));
fs.readFile('./es6.js', (err, content) => console.log(content));
fs.readFile('./es6.js', (err, content) => {
return console.log(content);
});
// BLOCK VARIABLES
let x = 1;
if (x >= 0) {
let x = 2;
console.log(x); // 2
}
console.log(x); // 1
// CONST VALUES (technically had before?)
const VARIABLE = 12;
try {
VARIABLE = 13;
} catch (ex) {
console.log('Coudln\'t reassign to a constant!');
}
// CLASSES
// CLASS DECLARATIONS
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
shift(horizontal, vertical) {
this.x += horizontal;
this.y += vertical;
}
static distance(pt1, pt2) {
let dx = pt2.x - pt1.x;
let dy = pt2.y - pt1.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
let pt1 = new Point(0, 0);
console.log('Created point', pt1);
let pt2 = new Point(100, 15);
pt2.shift(0, -15);
console.log('Distance to', pt2, 'is', Point.distance(pt1, pt2));
// INHERITANCE
class Point3D extends Point {
constructor(x, y, z) {
super(x, y);
this.z = z;
}
shift(length, width, depth) {
super.shift(length, width);
this.z += depth;
}
static distance(pt1, pt2) {
let dx = pt2.x - pt1.x;
let dy = pt2.y - pt1.y;
let dz = pt2.z - pt1.z;
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}
}
let pt31 = new Point3D(1, 0, 1);
let pt32 = new Point3D(10, 32, -45);
pt32.shift(0, 0, -5);
console.log('Distance from', pt31, 'to', pt32, 'is', Point3D.distance(pt31, pt32));
// CLASS EXPRESSIONS
let Vector = class {
constructor(magnitude, direction) {
this.magnitude = magnitude;
this.direction = direction;
}
};
let velocity = new Vector(100/*mps*/, 45/*degrees*/);
console.log('Velocity', velocity);
// COLLECTIONS
// MAP
let m = new Map([
['a', 1],
['b', 1],
['c', 2],
['d', 3],
['e', 5]]);
m.set('f', 8);
let mystery_key = {}, mystery_value = 3301;
m.set(mystery_key, mystery_value);
let mystery = m.get(mystery_key);
console.log('Maps do key equality properly! m.get(mystery_key) =', mystery, 'but m.get({}) =', m.get({}));
console.log('Map contains');
/* DOESN'T WORK!!!
for (var [key, val] of m) {
console.log('key', key, 'val', val);
}
*/
// WEAKMAP
// like Map but only accepts Objects as keys
let obj = {};
let m2 = new WeakMap();
m2.set(obj, 'helloworld.c');
console.log('m2.get(obj) =', m2.get(obj));
try {
m2.set('hello', 'helloworld.js');
} catch (ex) {
console.log('Couldn\'t set a string key on a WeakMap');
}
// SET
let set = new Set([1,1,2,3,5,7]);
console.log('Set with a messed up fib sequence -- No dupes!');
for (var i of set) {
console.log(i);
}
set.delete(7);
set.add(8);
let nope = set.has(7);
console.log('Set has the mistaken 7 value?', nope);
// WEAKSET
// Works like WeakMap
// TYPED ARRAYS
let buffer = new ArrayBuffer(32);
console.log('Our new buffer has', buffer.byteLength, 'bytes!');
console.log('Is it a normal array?', Array.isArray(buffer));
// GENERATORS
function* fibSeq() { // Note that asterisk!
let a = 1, b = 1;
yield b; // Can yield from more than one spot.
while (1) {
yield b;
let c = b;
b = a + b;
a = c;
}
}
console.log('First ten elements of the fib sequence');
let fibGen = fibSeq();
for (let i = 0; i < 10; i++) {
console.log(fibGen.next().value);
}
// We can yield values coming from other generators!
function* coolNumbers() {
yield -1;
yield 0;
yield* fibSeq();
yield 'we will never ever ever get here';
}
console.log('Cool numbers');
let cool = coolNumbers();
for (let i = 0; i < 10; i++) {
console.log(cool.next().value);
}
// BINARY AND OCTAL LITERALS
let binaryValue = 0b1010;
let other = 0b0101;
let xored = binaryValue ^ other;
console.log('XORed binary values', xored);
let octal = 0O111; // Zero O <number>
console.log('Octal value', octal);
// ENHANCED OBJECT LITERALS
let coolObj = {
__proto__: {},
// Shorthand for ‘fibGen: fibGen’
fibGen,
// Methods
toString() {
// Super calls
return "d " + super.toString();
},
// Computed (dynamic) property names
[ 'prop_' + (() => 42)() ]: 42
};
console.log('Our impressively created object', coolObj);
// PROMISES (oh hell yes!)
function promiseToRead(filename) {
return new Promise(function (resolve, reject) {
fs.readFile(filename, (err, content) => {
if (err) {
reject(err);
} else {
resolve(content);
}
});
});
}
promiseToRead('./es6.js')
.then(c => console.log('File length', c.length))
.catch(e => console.log('ERROR!', e.message));
promiseToRead('./es6.js_GARBAGE')
.then(c => console.log('File length', c.length))
.catch(e => console.log('ERROR!', e.message));
// NEW STRING METHODS
console.log('Catalog starts with cat?', 'catalog'.startsWith('cat'));
console.log('Combat ends with bat?', 'combat'.endsWith('bat'));
console.log('ha'.repeat(10));
console.log('Reaper includes ape?', 'reaper'.includes('ape'));
// SYMBOLS
let s1 = Symbol('foo');
let s2 = Symbol('foo');
console.log('Symbols are unique entities, so Symbol("foo") == Symbol("foo") is', s1 == s2);
// TEMPLATE STRINGS
let node = 'Node.js';
let multiline = `Woah this is so cool
Holy shit
Too bad ${node} doesn't have proper syntax
highlghting much.`
console.log(multiline);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment