Clean way to keep original variable and destruction at the same time

前端 未结 3 857
轮回少年
轮回少年 2020-12-03 17:36

Is there a cleaner way to do this (with anything that is at least an ES draft and has a babel plugin, i.e., ES6, ES7, etc.):

const { a, b } = result = doSome         


        
3条回答
  •  渐次进展
    2020-12-03 18:13

    Idea 1

    Create this helper function:

    function use(input, callback) {
        callback(input, input);
    }
    

    and use it like:

    use(doSomething(), (result, {a, b}) => {
        // Do something with result as a whole, or a and b as destructured properties.
    });
    

    For example:

    use ({a: "Hello", b: "World", c: "!"}, (result, {a, b}) => {
      console.log(result);
      console.log(a);
      console.log(b);
    });
    
    // generates
    // {a: "Hello", b: "World", c: "!"}
    // Hello
    // World
    

    They're not const, but they're scoped, for better or worse!


    Idea 2

    Combine array and object deconstruction. Create this helper function:

    const dup = input => [input, input];
    

    And then deconstruct away like so:

    const [result, {a, b}] = dup(doSomething());
    

    Now, your result, a, and b are all consts.

提交回复
热议问题