Skip to content

Instantly share code, notes, and snippets.

@dtothefp
Created February 11, 2016 15:45
Show Gist options
  • Save dtothefp/90b80cb11ecc79674087 to your computer and use it in GitHub Desktop.
Save dtothefp/90b80cb11ecc79674087 to your computer and use it in GitHub Desktop.
/*
* Objects
*/
const props = {
1: 1,
2: 2,
3: 3,
4: 4
}
const {a,b, ...rest} = props //a = 1, b = 2, rest = {3: 3, 4: 4}
const newProps = { //{a: 1, b: 2, c: 3, d: 4}
a,
b,
...rest //extends the object
}
const {a: first, b: second, ...more} = newProps //first = 1, second = 2, more = {c: 3, d: 4}
//late destructuring
let one, two;
const destructMeLate = {one: 1, two: 2}
;({one, two} = destructMeLate) //late destructuring, leading semi-only cause "hipster"
//use arrow function shortuct to make an array
const objFromProps = Object.keys(props).reduce((acc, num) => ({
...acc,
[num]: num * 2
}), {}) //{1: 2, 2: 4, 3: 6, 4: 8}
//use arrow function shortcut to make an object => could be done with .map
const arrFromProps = Object.keys(props).reduce((list, num) => ([
...list,
num * 2
]), []) //[2, 4, 6, 8]
//React
//<SomeComp first={first} second={second} {...more} />
//default values
const {blish = true, blosh = 'blah'} = {}
/*
* Arrays
*/
const arr = [1, 2, 3, 4]
const [arrFirst, arrSecond, ...remain] = arr //arrFirst = 1, arrSecond = 2, remain [3, 4]
const moreStuff = ['more', 'stuff']
//think Array.prototype.concat
const concatedArr = [...moreStuff, arrFirst, arrSecond] //['more', 'stuff', 1, 2]
const pushArr = []
//think Array.prototype.push.apply
pushArr.push(...['a', 'b', 'c'])
//pushArr = ['a', 'b', 'c']
pushArr.push(...[...arr, moreStuff])
//pushArr = ['a', 'b', 'c', 1, 2, 3, 4, ['more', 'stuff']]
//arrow function utility
const singleLineMap = arr.filter(num => num > 2).map(num => num * 2) //[6, 8]
//implicit return multi line
const multiLineMap = arr.filter(num =>
num > 2 //return cause no brackets and single line
).map(num =>
num * 2 //return cause no brackets and single line
) //[6, 8]
//default values
const [bleep = true, bloop = 'whatevs'] = []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment