Skip to content

Instantly share code, notes, and snippets.

@peter
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peter/5d48f4165c601adfd284 to your computer and use it in GitHub Desktop.
Save peter/5d48f4165c601adfd284 to your computer and use it in GitHub Desktop.
ES6 Uncensored
// 1. Swith two variables
// ES5
var temp = a;
a = b;
b = temp;
// ES6 - destructuring assignment
[b, a] = [a, b];
// 2. Find the biggest number in an array
// ES5
Math.max.apply(null, array);
// ES6 - using the spread operator to split an array up into arguments
Math.max(...array);
// 3. Sum the arguments
// ES5
var sum = function(/* numbers */) {
var asArray = [].slice.call(rguments);
return asArray.reduce(function(a, b) {
return a + b;
});
};
// ES6
let sum = (...numbers) =>
numbers.reduce((a, b) => a + b);
// 4. Remove the duplicates from an array
// ES5 - problem array keys are strings so 1 and "1" are coerced to the same thing
function unique(arr) {
var r = {};
arr.forEach(function(e) {
r[e] = 1;
});
return Object.keys(r);
}
// ES6
function unique(arr) {
return [...Set(arr)];
}
// 5. Generate the Fibonacci numbers
// ES5
// ...
// ES6
function fibonacci(size) {
var a = 0, b = 1, x = 2, r = [a, b];
while(x++ < size) {
[a, b] = [b, a+b];
r.push(b);
}
return r;
}
// ES6 - with generators
function fibonacci() {
var a = 0, b = 1;
while (true) {
[a, b] = [b, a+b];
yield b;
}
}
var generator = fibonacci();
generator.next(); // => 1
generator.next(); // => 2
// 6. Factorial
// ES5
// ES6
// 7. Sum the squares
// ES5
arr.map(function(number) {
return number*number;
}).reduce(function(a, b) {
return a + b;
});
// ES6 - array comprehensions
[for (x of array) x*x].reduce((a,b)=>a+b);
// 8. Module Pattern (ID Generator)
// ES5
var idGenerator = function(id) {
id || (id = 0);
return function() {
return id++;
};
};
var nextFrom1000 = idGenerator(1000);
nextFrom1000(); // => 1000
nextFrom1000(); // => 1001
// ES6 - default arguments
let idGenerator = (id=0)=> ()=> id++;
let nextFrom1000 = idGenerator(1000);
nextFrom1000(); // => 1000
nextFrom1000(); // => 1001
// Also - in ES6 there is an object short hand for when keys/values are the same: {key1, key2} becomes {key1: key1, key2: key2}
// 9.
// ES5
// ES6 - Destructuring and default argument values:
function echoABC({a=3, b=4, c=5}) {
console.log(a, b, c);
}
// 10.
// ES5
// ES6
// 11. Negative Array Indexes
var arr = makeSmartArray([1, 2, 3]);
arr[0];
arr[-1];
function makeSmartArray(arr) {
return Proxy(
arr,
{get: function(p, x) {
if (Number(x) >= 0) {
return p[x] ;
} else {
return p[p.length + Number(x)];
}
}}
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment