عکس smmoosavi
ugly-lovely es6 syntax
موضوع‌ها
۱
فورک‌ها
۶
ستاره‌ها
۲۳
تاریخ ایجاد
۹ مهر ۱۳۹۵
آخرین بروزرسانی
نزدیک ۶ سال قبل
لایسنس
MIT License

uglovely-es6

ugly-lovely es6 syntax

basic:

a tempo up:

properties getter

input:

const {color} = this.props;

output:

var color = this.props.color;

pros

  • Avoid duplicate name
  • less code

deep properties getter

input:

// action is {type: 'add', payload: {value: 1}}

const {type, payload: {value}} = action;

output:

// action is { type: 'add', payload: { value: 1 } };

var type = action.type;
var value = action.payload.value;

pros

  • Avoid duplicate name
  • less code

object creation

input:

const color = 'red';
const size = 'small';
const o = {color, size};

output:

var color = 'red';
var size = 'small';
var o = { color: color, size: size };

pros

  • Avoid duplicate name
  • less code sometimes

cons

  • more code sometimes

pick

input:

// input is {size: 'large', color: 'red', text: 'es6'}
const {size, color} = input;
const output = {size, color};

output:

// input is {size: 'large', color: 'red', text: 'es6'}
var size = input.size;
var color = input.color;
var output = { size: size, color: color };

need help: is there any pure es6, one line, without name duplicated way?

// lodash way
_.pick(input, ['size', 'color']);

cons

  • duplicate name

jsx props setter

input:

const color = 'red';
<MyComponent {...{color}}/>;

equal to:

const color = 'red';
<MyComponent color={color}/>;

output:

const color = 'red';
React.createElement(MyComponent, { color: color });

pros

  • Avoid duplicate name
  • less code

conditional object creation

input:

const color = 'red';
const size = 'small';
const active = true; // or false

const o = {
    size,
    ...(active?{color}:{}),
}

equal logic:

const color = 'red';
const size = 'small';
const active = true; // or false

const o = {size};
if (active) {
    o.color = color;
}

output:

// ugly.

value:

// active = true
o = {size: 'small', color: 'red'}

// active = false
o = {size: 'small'}

pros

  • object creation is not flow of code
  • no mutation

cons

  • unfamiliar (yet)
  • maybe a little performance

conditional array creation

input:

const holyday = true // or false
const tasks = [
    'wake up',
    'lunch',
    ...(holyday?[]:['work']),
    'sleep',
];

value:

// holyday = true
tasks = ['wake up', 'lunch', 'sleep']

// holyday = false
tasks = ['wake up', 'lunch', 'work', 'sleep']

pros

  • object creation is not flow of code
  • no mutation

cons

  • unfamiliar (yet)
  • maybe a little performance