Skip to content

Instantly share code, notes, and snippets.

@MichalZalecki
Last active August 29, 2015 14:15
Show Gist options
  • Save MichalZalecki/e740c05ddf9e626c6394 to your computer and use it in GitHub Desktop.
Save MichalZalecki/e740c05ddf9e626c6394 to your computer and use it in GitHub Desktop.
ECMAScript 6 features
let square = x => x * x;
let triangleArea = (a, h) => a*h/2;
let triangleHeron = (a, b, c) => {
let p = (a + b + c)/2;
return Math.sqrt(p*(p-a)*(p-b)*(p-c));
};
let objectify = x => ({ value: x });
expect(square(13)).toEqual(169);
expect(triangleArea(4, 6)).toEqual(12);
expect(triangleHeron(3, 4, 5)).toEqual(6);
expect(objectify("foo")).toEqual({ value:"foo" });
let person = {
name: "Bob",
belongings: ["Car", "PC"],
getProperties: function () {
let properties = [];
this.belongings.forEach(function (thing) {
properties.push(this.name + " has " + thing);
});
return properties;
},
getProperties2: function () {
let properties = [];
// arrows share this with surrounding code
this.belongings.forEach((thing) => {
properties.push(this.name + " has " + thing);
});
return properties;
}
};
expect(() => person.getProperties())
.toThrow(new TypeError("Cannot read property 'name' of undefined"));
expect(person.getProperties2()).toEqual(["Bob has Car", "Bob has PC"]);
class Point {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
update(x = 0, y = 0) {
this.x = x;
this.y = y;
}
}
class Circle extends Point {
constructor(r, x, y) {
super(x, y);
this.r = r;
}
update(r, x, y) {
super.update(x, y);
this.r = r;
}
isPointIncluded(point) {
if (point.constructor != Point)
throw new Error("point must be an instance of Point");
return Math.pow(this.r, 2)+Math.pow(this.y, 2) >=
Math.pow(this.x-point.x, 2)+Math.pow(this.y-point.y, 2);
}
}
let c1 = new Circle(3);
expect(c1.isPointIncluded(new Point())).toEqual(true);
expect(c1.isPointIncluded(new Point(0, 3))).toEqual(true);
expect(c1.isPointIncluded(new Point(3, 3))).toEqual(false);
let c2 = new Circle(6, 2, 1);
expect(c2.isPointIncluded(new Point(2, 7))).toEqual(true);
expect(c2.isPointIncluded(new Point(3, -1))).toEqual(true);
expect(c2.isPointIncluded(new Point(6, 6))).toEqual(false);
c2.update(6, 2, 2);
expect(c2.isPointIncluded(new Point(6, 6))).toEqual(true);
const x = 1;
const y = {x: 1};
const z = {x: 1};
x = 2; // error
y = {x: 2}; // error
z.x = 2;
// overwriting fails
expect(x).toEqual(1);
expect(y).toEqual({x: 1});
// modifying works, properties are not protected
expect(z).toEqual({x: 2});
function f(list, indexA = 0, indexB = list.length) {
return [list, indexA, indexB];
}
expect(f([1, 2, 3])).toEqual([[1, 2, 3], 0, 3]);
expect(f([1, 2, 3], 1)).toEqual([[1, 2, 3], 1, 3]);
expect(f([1, 2, 3], 1, 2)).toEqual([[1, 2, 3], 1, 2]);
let [a, , [b, c]] = [1, 2, [3, 4]];
expect(a).toEqual(1);
expect(b).toEqual(3);
expect(c).toEqual(4);
let {firstName, lastName: surname, info: {age, driver}} =
{firstName: "Foo", lastName: "Bar", info: {age: 20, driver: true}};
expect(firstName).toEqual("Foo");
expect(surname).toEqual("Bar");
expect(age).toEqual(20);
expect(driver).toEqual(true);
function greet(name) {
return "Hello " + name;
}
let x = 2;
let obj = {
// Computed property names
[x*2]: "Computed Property Name",
// __proto__
__proto__: {
hi: function () { return "Hi!" },
by: function () { return "By!" }
},
// object initializer shorthand (greet: greet)
greet,
cheers(name) {
return "Cheers " + name;
}
// @TODO making super calls
};
expect(obj[4]).toEqual("Computed Property Name");
expect(obj.hi()).toEqual("Hi!");
expect(obj.by()).toEqual("By!");
expect(obj.greet("Bob")).toEqual("Hello Bob");
expect(obj.cheers("Bob")).toEqual("Cheers Bob");
function* foo() {
let i = 0;
yield ++i;
yield ++i;
yield ++i;
}
let seq = foo();
expect(seq.next().value).toEqual(1);
expect(seq.next().value).toEqual(2);
expect(seq.next().value).toEqual(3);
function* flatten(t, n = 0) {
if (t[n]) {
if (Array.isArray(t[n]))
yield* flatten(t[n])
else
yield t[n];
yield* flatten(t, n + 1);
}
}
let nums = [];
for (let n of flatten([10, 11, 12, [13, 14, [15, 16]], 17])) {
nums.push(n);
}
expect(nums).toEqual([10, 11, 12, 13, 14, 15, 16, 17]);
// The idea comes from http://youtu.be/s-BwEk-Y4kg?t=14m42s
function* powGenerator() {
return Math.pow(yield "a", yield "b");
}
let g = powGenerator();
expect(g.next().value).toEqual("a");
expect(g.next(10).value).toEqual("b");
expect(g.next(2).value).toEqual(100);
function fibonacci(i) {
return {
[Symbol.iterator]() {
let pre = -1, cur = 1;
return {
next() {
[pre, cur] = [cur, pre + cur];
return {done: !(i--), value: cur};
}
}
}
}
}
let fib = [];
for (let n of fibonacci(10)) {
fib.push(n);
}
expect(fib).toEqual([0, 1, 1, 2, 3, 5, 8, 13, 21, 34]);
expect(() => {
if (true) {
var x = 1;
}
expect(x).toEqual(1);
}).not.toThrowError();
expect(() => {
if (true) {
let x = 1;
}
expect(x).toEqual(1);
}).toThrowError("x is not defined");
(function() {
let funcs = [];
for (var i of [4, 5, 6]) {
funcs.push(function() { return i; });
}
expect([funcs[0](), funcs[1](), funcs[2]()]).toEqual([6, 6, 6])
})();
(function() {
let funcs = [];
for (let i of [4, 5, 6]) {
funcs.push(function() { return i; });
}
expect([funcs[0](), funcs[1](), funcs[2]()]).toEqual([4, 5, 6])
})();
let m = new Map([["name", "Foo"], ["surname","Bar"]]);
m.set("age", 10).set("age", 20).set(false, "Foo");
expect(m.size).toEqual(4);
expect(m.has("name")).toEqual(true);
expect(m.has(false)).toEqual(true);
expect(m.has("address")).toEqual(false);
let mapIter = m.entries();
expect(mapIter.next().value).toEqual(["name", "Foo"]);
expect(mapIter.next().value).toEqual(["surname", "Bar"]);
expect(mapIter.next().value).toEqual(["age", 20]);
expect(mapIter.next().value).toEqual([false, "Foo"]);
expect(mapIter.next().value).toBeUndefined();
expect(m.delete("name")).toEqual(true);
expect(m.has("name")).toEqual(false);
expect(m.size).toEqual(3);
m.clear();
expect(m.size).toEqual(0);
<script>
System.import('modules/math').then((m) => {
expect("2π = " + m.sum(m.pi, m.pi)).toEqual("2π = 6.283186");
});
System.import('modules/person').then((m) => {
expect("I'm " + m.name + " " + m.surname).toEqual("I'm Foo Bar");
});
</script>
// modules/math.js
export function sum(x, y) {
return x + y;
}
export const pi = 3.141593;
// modules/person.js
export let name = "Foo";
export let surname = "Bar";
// modules/awesome.js
export default class {
constructor() {
this._status = "awesome";
}
hoItIs() {
return this._status;
}
}
// modules.js
import {sum, pi} from "./modules/math";
import * as buddy from "./modules/person";
import Awesome from "./modules/awesome";
expect(sum(2, 3)).toEqual(5);
expect(pi).toEqual(3.141593);
pi = 22/7; // error: "pi" is read-only
expect(buddy).toEqual(jasmine.any(Object));
expect(buddy.name).toEqual("Foo");
expect(buddy.surname).toEqual("Bar");
expect((new Awesome).hoItIs()).toEqual("awesome");
expect([
0b111,
0b11110000,
0b00001111
]).toEqual([
7,
240,
15
]);
expect([
0o7,
0o360,
0o17
]).toEqual([
7,
240,
15
]);
function promiseMaker(condition, timeout = 2000) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (condition) {
resolve("Success!");
} else {
reject(new Error("Something went wrong!"));
}
}, timeout);
});
}
promiseMaker(true)
.then((data) => {
expect(data).toEqual("Success!");
});
promiseMaker(false, 3000)
.catch((err) => {
expect(err).toEqual(new Error("Something went wrong!"));
});
var address = {
'Marie Lynch': 'mlynch2@state.tx.us',
'Ryan Bradley': 'rbradley3@com.com' };
var handler = {
set: (target, property, value, receiver) => {
if (!value.match(/^\S+@\S+\.\S+$/))
throw new TypeError(`${value} is invalid email!`);
target[property] = value;
return true;
},
get: (target, property, receiver) => {
return property in target ?
target[property] : "Not Found"; }
};
var addressBook = new Proxy(address, handler);
addressBook['Joseph Fields'] = 'jfields9@fedbur.com';
expect(() => { addressBook['Kathryn Lewis'] = 'klewis.com' }).
toThrow(new TypeError("klewis.com is invalid email!"));
expect(addressBook['Marie Lynch']).toEqual("mlynch2@state.tx.us");
expect(addressBook['Joseph Fields']).toEqual("jfields9@fedbur.com");
expect(addressBook['Kathryn Lewis']).toEqual("Not Found");
function buy(where, ...items) {
return "I'm going to " + where + " to buy "
+ items.length + " items: "
+ items.slice(0, -1).join(", ")
+ " and " + items.slice(-1) + ".";
}
expect(buy("the mall", "jacket", "bag", "sweets", "headphones"))
.toEqual("I'm going to the mall to buy 4 items: "
+ "jacket, bag, sweets and headphones.");
let s = new Set(["Foo", "Bar"]);
s.add(false).add(123).add("Bar");
expect(s.size).toEqual(4);
expect(s.has("Bar")).toBe(true);
expect(s.has(123)).toBe(true);
expect(s.has(true)).toBe(false);
let setIter2 = s.values();
expect(setIter2.next().value).toEqual("Foo");
expect(setIter2.next().value).toEqual("Bar");
expect(setIter2.next().value).toEqual(false);
expect(setIter2.next().value).toEqual(123);
expect(setIter2.next().value).toBeUndefined();
expect(s.delete("Bar")).toEqual(true);
expect(s.has("Bar")).toEqual(false);
expect(s.size).toEqual(3);
s.clear();
expect(s.size).toEqual(0);
function send(what, where, toWhom) {
return "I'm sending " + what + " to " + toWhom
+ " who is in " + where + ".";
}
function send_with_default(what, where, toWhom = "Santa") {
return "I'm sending " + what + " to " + toWhom
+ " who is in " + where + ".";
}
expect(send(...["the letter", "Poland", "Mike"]))
.toEqual("I'm sending the letter to Mike who is in Poland.");
expect(send_with_default(...["the letter", "Lapland"]))
.toEqual("I'm sending the letter to Santa who is in Lapland.");
let s = Symbol("foo");
expect(s).not.toEqual(Symbol("foo"));
expect(typeof s).toEqual("symbol");
let s2 = Symbol.for("foo");
expect(s).not.toEqual(s2);
expect(s2).toEqual(Symbol.for("foo"));
expect(Symbol.keyFor(s2)).toEqual("foo");
expect(Symbol("bar")).not.toBe(Symbol("bar"));
expect(Symbol.for("bar")).toBe(Symbol.for("bar"));
function Safe(secretData) {
let s = Symbol("secret symbol");
this[s] = secretData;
}
let obj = new Safe("secret");
expect(obj["secret symbol"]).toBeUndefined();
expect(obj[Symbol("secret symbol")]).toBeUndefined();
expect(Object.getOwnPropertySymbols(obj)).toEqual(jasmine.any(Array));
expect(obj[Object.getOwnPropertySymbols(obj)[0]])
.toEqual("secret");
let name = "Foo";
let surname = "Bar";
let email = "foo@example.com";
expect(`${name} ${surname}`).toEqual("Foo Bar");
let name = "Foo";
let surname = "Bar";
let email = "foo@example.com";
function vCard(strs, ...values) {
let card = {};
let regExp = /[\t ]*([a-zA-Z@\. ]+): /;
for (let str of strs) {
if (regExp.test(str)){
card[str.match(regExp)[1]] = values.shift();
}
}
return card;
}
expect(
vCard`First name: ${name}
Last name: ${surname}
Email: ${email}`
).toEqual({
"First name": "Foo",
"Last name": "Bar",
Email: "foo@example.com"
});
let wm = new WeakMap(),
o1 = {},
o2 = function () {},
o3 = Symbol("foo"),
o4 = window;
wm.set(o1, 123);
wm.set(o2, "FooBar");
wm.set(o3, undefined);
wm.set(1, "Baz"); // Invalid value used as weak map key
expect(wm.get(o1)).toEqual(123);
expect(wm.get(o2)).toEqual("FooBar");
expect(wm.get(o3)).toBeUndefined();
expect(wm.get(o4)).toBeUndefined();
expect(wm.has(o1)).toEqual(true);
expect(wm.has(o2)).toEqual(true);
expect(wm.has(o3)).toEqual(true);
expect(wm.has(o4)).toEqual(false);
wm.delete(o1);
expect(wm.has(o1)).toEqual(false);
let ws = new WeakSet(),
o1 = {},
o2 = function () {},
o3 = window;
ws.add(o1);
ws.add(o2);
expect(ws.has(o1)).toEqual(true);
expect(ws.has(o2)).toEqual(true);
expect(ws.has(o3)).toEqual(false);
ws.delete(o1);
ws.delete(o2);
expect(ws.has(o1)).toEqual(false);
expect(ws.has(o2)).toEqual(false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment