function defaultExample(count = 1) {
console.log(count);
}
defaultExample(); // 1
function restExample(x, ...y){
console.log(y);
}
restExample(1, 2, 3, 5, 8); // [2, 3, 5, 8]
function spread(x,y,z){
console.log(x,y,z);
}
spread(...['curly', 'moe', 'larry']); // curly moe larry
function factorial(n, acc = 1) {
'use strict';
if (n <= 1) return acc;
return factorial(n - 1, n * acc);
}
// Stack overflow in most implementations today,
// but safe on arbitrary inputs in eS6
factorial(100000)
var p = Proxy.create({
get: function(proxy, name) {
return 'Hello, Meetup.js';
}
});
console.log(p.none) // 'Hello, Meetup.js'
var userProxy = Proxy(user, {
get: function(target, name) {
return name in target ? target[name] : counter++;
}
});
new Promise(function (fn){
fn(1);
}).then(function (n){
return n + 5;
}).then(function (n){
console.log(n); // 6
});
Good ol' fashion:
var FS = require("fs");
var readJsonWithNodebacks = function (path, nodeback) {
FS.readFile(path, "utf-8", function (error, content) {
var result;
if (error) {
return nodeback(error);
}
try {
result = JSON.parse(result);
} catch (error) {
return nodeback(error);
}
nodeback(null, result);
});
}
var FS = require("q-io/fs");
function readJsonPromise(path) {
return FS.read(path).then(JSON.parse);
}
function* fibonacci() {
let [prev, curr] = [0, 1];
for (;;) {
[prev, curr] = [curr, prev + curr];
yield curr;
}
}
let seq = fibonacci();
print(seq.next()); // 1
print(seq.next()); // 2
print(seq.next()); // 3
You could also send values to an iterator:
function* fibonacci() { let [prev, curr] = [0, 1]; for (;;) { [prev, curr] = [curr, prev + curr]; let input = yield curr; if(input) [prev, curr] = [0, 1]; } } let seq = fibonacci(); console.log(seq.next()); // 1 console.log(seq.next()); // 2
console.log(seq.next()); // 3
console.log(seq.next(1)); // 1
Generators could also be combined with other control flow features like Promises[1], look at the following code:
function get(filename){
return readJSON('left.json').then(function (left){
return readJSON('right.json').then(function (right){
return {left: left, right: right};
});
});
}
var get = Q.async(function *(){
var left = yield readJSON('left.json');
var right = yield readJSON('right.json');
return {left: left, right: right};
});