ES6 destruction pretreatment

Problem

Destructuring functional arguments are a great feature in ES6. Suppose we want to accept functionwith a name that has a keyfObjecta

function f({ a }) {
    return a;
}

We have default values ​​for the case when the parameter was not provided to the function to avoid Type Error

function f({ a } = {}) {
    return a;
}

This will help in the following case.

const a = f(); // undefined

Although, he will fail on

const a = f(null); // TypeError: Cannot match against 'undefined' or 'null'.

You can see how Babel translates the function into ES5 here .

Possible solutions

. Python , JS , . , checkInputObject, , ( ). @

const f = checkInputObject(['a'])(({ a }) => a);

: @

@checkInputObject(['a'])
function f({ a }) {
    return a;
}

, ( )

function f(param) {
    if (!param) {
        return;
    }
    const { a } = param;
    return a;
}

, checkInputObject,

const fChecker = checkInputObject(['a']);
function f(param) {
    const { a } = fChecker(param);
    return a;
}

, . , undefined. ,

function f({a: [, c]) {
    return c;
}

undefined f().

- [] ?

: , , , . , .

+4
4

ES6 , , API, , .

fn(undefined) , , fn(null) , nully .

/ /, , :

function fn({ foo, bar}) { ... }

fn(processData(data));

function fn(data) {
  const { foo, bar } = processData(data);
  ...
}

fn(data);

, , processData , .

ECMAScript - , @, .

function processDataDecorator(target, key) {
  const origFn = target[key];
  return target[key] = (...args) => origFn.apply(target, processData(...args));
}

class Foo {
  constructor() {
    this.method = processDataDecorator(this, 'method');
  }

  method(data) {...}
}

class Bar {
  @processDataDecorator
  method(data) {...}
}

, ES5 Object.assign. , data undefined, null , :

function processData(data) {
  return Object.assign({ foo: ..., bar: ...}, data);
}
+1

try...catch :

function safe(f) {
   return function (...args) {
       try {
           return f(...args);
       } catch (e) {}; // return undefined
   };
}

function f({ a } = {}) {
    return a;
}

f = safe(f);
console.log(f(null)); // -> undefined
console.log(f( { a:3 } )); // -> 3
Hide result
+3

, , .

, , - , , , .

, . , , Flow, , , , .

javascript , , , , , .

"" , , ( arguments ), , , , , 1 , 1 , .

+2

, ?

, .

function f({a: [,c]}={a:[undefined,undefined]}) {
    return c;
}

f();
-3

Source: https://habr.com/ru/post/1678942/


All Articles