ECMAScript 7
Templates
Open ListCarousel
Slide CityPhoto Gallery
View GalleryNavbar Pages
View TabsSwipe list repositories item
Snniped list:
Gist GitHub
JSConsole
Everywhere.js
import {everywhere} from "./crow-tech";
everywhere(nest => {
nest.state.gossip = [];
});
function sendGossip(nest, message, exceptFor = null) {
nest.state.gossip.push(message);
for (let neighbor of nest.neighbors) {
if (neighbor == exceptFor) continue;
request(nest, neighbor, "gossip", message);
}
}
requestType("gossip", (nest, message, source) => {
if (nest.state.gossip.includes(message)) return;
console.log(`${nest.name} received gossip '${
message}' from ${source}`);
sendGossip(nest, message, source);
});
setTimeOut.js
try {
setTimeout(() => {
throw new Error("Woosh");
}, 20);
} catch (_) {
// This will not run
console.log("Caught!");
}
Promise_all
function Promise_all(promises) {
return new Promise((resolve, reject) => {
// Your code here.
});
}
// Test code.
Promise_all([]).then(array => {
console.log("This should be []:", array);
});
function soon(val) {
return new Promise(resolve => {
setTimeout(() => resolve(val), Math.random() * 500);
});
}
Promise_all([soon(1), soon(2), soon(3)]).then(array => {
console.log("This should be [1, 2, 3]:", array);
});
Promise_all([soon(1), Promise.reject("X"), soon(3)])
.then(array => {
console.log("We should not get here");
})
.catch(error => {
if (error != "X") {
console.log("Unexpected failure:", error);
}
});
Operator.js
{
type: "apply",
operator: {type: "word", name: ">"},
args: [
{type: "word", name: "x"},
{type: "value", value: 5}
]
}
BOOM!!!.js
let bombTimer = setTimeout(() => {
console.log("BOOM!");
}, 500);
if (Math.random() < 0.5) { // 50% chance
console.log("Defused.");
clearTimeout(bombTimer);
}
Tick.js
let ticks = 0;
let clock = setInterval(() => {
console.log("tick", ticks++);
if (ticks == 10) {
clearInterval(clock);
console.log("stop.");
}
}, 200);
F{context}
function Subject(){
this.observers = new ObserverList();
}
Subject.prototype.addObserver = function( observer ){
this.observers.add( observer );
};
Subject.prototype.removeObserver = function( observer ){
this.observers.removeAt( this.observers.indexOf( observer, 0 ) );
};
Subject.prototype.notify = function( context ){
var observerCount = this.observers.count();
for(var i=0; i < observerCount; i++){
this.observers.get(i).update( context );
}
};
{Object}
// Macbook decorator abstract decorator class
var MacbookDecorator = function( macbook ){
Interface.ensureImplements( macbook, Macbook );
this.macbook = macbook;
};
MacbookDecorator.prototype = {
addEngraving: function(){
return this.macbook.addEngraving();
},
addParallels: function(){
return this.macbook.addParallels();
},
add4GBRam: function(){
return this.macbook.add4GBRam();
},
add8GBRam:function(){
return this.macbook.add8GBRam();
},
addCase: function(){
return this.macbook.addCase();
},
getPrice: function(){
return this.macbook.getPrice();
}
};
ParentClassOrObject
Function.prototype.implementsFor = function( parentClassOrObject ){
if ( parentClassOrObject.constructor === Function )
{
// Normal Inheritance
this.prototype = new parentClassOrObject();
this.prototype.constructor = this;
this.prototype.parent = parentClassOrObject.prototype;
}
else
{
// Pure Virtual Inheritance
this.prototype = parentClassOrObject;
this.prototype.constructor = this;
this.prototype.parent = parentClassOrObject;
}
return this;
};
NewNumber.js
var myNumber = new Number('23');
var myNumberL = 23; // literal shorthand
var myString = new String('male');
var myStringL = 'male'; // literal shorthand
var myBoolean = new Boolean('true');
var myBooleanL = true; // literal shorthand
var myObject = new Object();
var myObjectL = {}; // literal shorthand
var myArray = new Array();
var myArrayL = []; // literal shorthand
var myFunction = new Function();
var myFunctionL = function() {}; // literal shorthand
var myDate = new Date();
var myRegExp = new RegExp('/./');
var myRegExpL = /./; // literal shorthand
var myError = new Error();
console.log( // all of these return true
myNumber.constructor === Number,
myNumberL.constructor === Number,
myString.constructor === String,
myStringL.constructor === String,
myBoolean.constructor === Boolean,
myBooleanL.constructor === Boolean,
myObject.constructor === Object,
myObjectL.constructor === Object,
myArray.constructor === Array,
myArrayL.constructor === Array,
myFunction.constructor === Function,
myFunctionL.constructor === Function,
myDate.constructor === Date,
myRegExp.constructor === RegExp,
myRegExpL.constructor === RegExp,
myError.constructor === Error
);
SetTimeOut
setTimeout( function timeoutHandler(){ // <-- Look, I have a
// name!
console.log( "I waited 1 second!" );
}, 1000 );
NewString.js
// this can be done with any of the native constructors that actual produce an object
var myString = new String();
var myNumber = new Number();
var myBoolean = new Boolean(true);
var myObject = new Object();
var myArray = new Array();
var myFunction = new Function('return 2+2');
var myRegExp = new RegExp('\bt[a-z]+\b');
myString.prop = 'test';
myNumber.prop = 'test';
myBoolean.prop = 'test';
myObject.prop = 'test';
myArray.prop = 'test';
myFunction.prop = 'test';
myRegExp.prop = 'test';
// logs 'test', 'test', 'test', 'test', 'test', 'test', 'test'
console.log
(myString.prop,myNumber.prop,myBoolean.prop,myObject.prop,myArray.prop,myFunction.prop,
myRegExp.prop);
// be aware: instance properties do not work with primitive/literal values
var myString = 'string';
var myNumber = 1;
var myBoolean = true;
myString.prop = true;
myNumber.prop = true;
myBoolean.prop = true;
// logs undefined, undefined, undefined
console.log(myString.prop, myNumber.prop, myBoolean.prop);
Timer.js
for (var i=1; i<=5; i++) {
(function(){
setTimeout( function timer(){
console.log( i );
}, i*1000 );
})();
}
defineGetter.js
/*
* Add a nonenumerable extend() method to Object.prototype.
* This method extends the object on which it is called by copying properties
* from the object passed as its argument. All property attributes are
* copied, not just the property value. All own properties (even non-
* enumerable ones) of the argument object are copied unless a property
* with the same name already exists in the target object.
*/
Object.defineProperty(Object.prototype,
"extend", // Define Object.prototype.extend
{
writable: true,
enumerable: false, // Make it nonenumerable
configurable: true,
value: function(o) { // Its value is this function
// Get all own props, even nonenumerable ones
var names = Object.getOwnPropertyNames(o);
// Loop through them
for(var i = 0; i < names.length; i++) {
// Skip props already in this object
if (names[i] in this) continue;
// Get property description from o
var desc = Object.getOwnPropertyDescriptor(o,names[i]);
// Use it to create property on this
Object.defineProperty(this, names[i], desc);
}
}
});
Array-Like.js
var a = {}; // Start with a regular empty object
// Add properties to make it "array-like"
var i = 0;
while(i < 10) {
a[i] = i * i;
i++;
}
a.length = i;
// Now iterate through it as if it were a real array
var total = 0;
for(var j = 0; j < a.length; j++)
total += a[j];
Range.js
Range.prototype = {
constructor: Range, // Explicitly set the constructor back-reference
includes: function(x) { return this.from <= x && x <= this.to; },
foreach: function(f) {
for(var x = Math.ceil(this.from); x <= this.to; x++) f(x);
},
toString: function() { return "(" + this.from + "..." + this.to + ")"; }
};
Obj-Key.js
var obj = { first: 'John', last: 'Doe' };
// Visit non-inherited enumerable keys
Object.keys(obj).forEach(function (key) {
console.log(key);
});
Row-Count.js
// Create the Tic-tac-toe board
var rows = [];
for (var rowCount=0; rowCount < 3; rowCount++) {
rows[rowCount] = [];
for (var colCount=0; colCount < 3; colCount++) {
rows[rowCount][colCount] = '.';
}
}
// Set an X in the upper right corner
rows[0][2] = 'X'; // [row][column]
// Print the board
rows.forEach(function (row) {
console.log(row.join(' '));
});
ProxyArray.js
let products = new Proxy({
browsers: ['Internet Explorer', 'Netscape']
},
{
get: function(obj, prop) {
// An extra property
if (prop === 'latestBrowser') {
return obj.browsers[obj.browsers.length - 1];
}
// The default behavior to return the value
return obj[prop];
},
set: function(obj, prop, value) {
// An extra property
if (prop === 'latestBrowser') {
obj.browsers.push(value);
return;
}
// Convert the value if it is not an array
if (typeof value === 'string') {
value = [value];
}
// The default behavior to store the value
obj[prop] = value;
}
});
console.log(products.browsers); // ['Internet Explorer', 'Netscape']
products.browsers = 'Firefox'; // pass a string (by mistake)
console.log(products.browsers); // ['Firefox'] <- no problem, the value is an array
products.latestBrowser = 'Chrome';
console.log(products.browsers); // ['Firefox', 'Chrome']
console.log(products.latestBrowser); // 'Chrome'
Reflect.set
// Objeto var obj = {}; Reflect.set(obj, 'prop', 'value'); // true obj.prop; // "value" // Arreglo var arr = ['duck', 'duck', 'duck']; Reflect.set(arr, 2, 'goose'); // true arr[2]; // "goose" // Puede truncar un arreglo. Reflect.set(arr, 'length', 1); // true arr; // ["duck"]; // Con solo un argumento, propertyKey y value son "undefined". var obj = {}; Reflect.set(obj); // true Reflect.getOwnPropertyDescriptor(obj, 'undefined'); // { value: undefined, writable: true, enumerable: true, configurable: true }
math.pow
Number.MAX_SAFE_INTEGER = Math.pow(2, 53)-1;
Number.MIN_SAFE_INTEGER = -Number.MAX_SAFE_INTEGER;