Skip to content

Instantly share code, notes, and snippets.

@amowu
Created July 22, 2016 06:47
Show Gist options
  • Select an option

  • Save amowu/abb0f0a3977eeb0b67d29ec615f8663a to your computer and use it in GitHub Desktop.

Select an option

Save amowu/abb0f0a3977eeb0b67d29ec615f8663a to your computer and use it in GitHub Desktop.
Six nifty ES6 tricks

forEach

const arr = ['a', 'b', 'c'];
// arr.forEach(function (elem, idx) {
//   console.log('index = ' + idx + ', element = ' + elem);
// });
for (const [idx, elem] of err.entries()) {
  console.log(`index = ${idx}, element = ${elem}`);
}
// output:
// index = 0, element = 'a'
// index = 1, element = 'b'
// index = 2, element = 'c'

length

// '💩'.length
// output: 2
[...'💩'].length
// output: 1

mixin

// Function simply returns its parameter
const Storage = Sup => class extends Sup {
  save (database) {...}
};
const Validate = Sup => class extends Sup {
  validate (shema) {...}
};
class Person {...}
class Employee extends Storage(Validate(Person)) {...}

required

/**
 * Called if a parameter is missing and
 * the default value is evaluated.
 */
function mandatory () {
  throw new Error('Missing parameter');
}
function required (mustBeProvided = mandatory()) {
  return mustBeProvided;
}
required();
// output: Error: Missing parameter
required('foo');
// output: 'foo'

swap

[a, b] = [b, a];

template

// const data = [{ first: 'Jane', last: 'Bond' }, { first: 'Lars', last: 'Croft' }];
const template = addrs => `
  <table>
  ${addrs.map(addr => `
    <tr><td>${addr.first}</td></tr>
    <tr><td>${addr.last}</td></tr>
  `).join('')}
  </table>
`;
// console.log(template(data));
// output:
// <table>
//   <tr><td>Jane</td></tr>
//   <tr><td>Bond</td></tr>
//   <tr><td>Lars</td></tr>
//   <tr><td>Croft</td></tr>
// </table>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment