How to handle nested default parameters when objects are destroyed?

I am trying to figure out if it is possible to handle several levels of default parameters with destructuring. Since this is not easy to explain in words, here is a step by step example ...


1 - Dismantling a flat object with default parameters

Restructuring this object is very simple:

let obj = {
  foo: 'Foo',
  bar: 'Bar'
};

C {foo = 'Foo', bar = 'Bar'} = {}in the function signature, the object will be created if there is no argument passed when the function was called. If the object is passed, but some reference properties undefined, they will be replaced with their default values. This code works fine:

function fn1({foo = 'Foo', bar = 'Bar'} = {}) {
  console.log(foo, bar);
}

// OK
fn1(); // Foo Bar
fn1({foo: 'Quux'}); // Quux Bar
fn1({bar: 'Quux'}); // Foo Quux
fn1({foo: 'Quux', bar: 'Quux'}); // Quux Quux
Run codeHide result

2 - Restructuring nested objects with shallow default settings

Destructuring this object is more difficult:

let obj = {
  foo: 'Foo',
  bar: {
    quux: 'Quux',
    corge: 'Corge'
  }
};

{foo = 'Foo', bar = 'Bar'} = {} , {foo = 'Foo', bar = {quux: 'Quux', corge: 'Corge'}} = {} . , , (foo bar). , undefined (foo bar) .

, bar (quux corge) " ". , quux corge undefined, , bar :

function fn2({foo = 'Foo', bar = {quux: 'Quux', corge: 'Corge'}} = {}) {
  console.log(foo, bar.quux, bar.corge);
}

// OK
fn2(); // Foo Quux Corge
fn2({foo: 'Quux'}); // Quux Quux Corge

// Oops!
fn2({bar: {quux: 'Baz'}}); // Foo Baz undefined
fn2({foo: 'Quux', bar: {corge: 'Baz'}}); // Quux undefined Baz
Hide result

3 -

, " ". , :

function fn3({foo = 'Foo', bar = ({quux = 'Quux', corge = 'Corge'} = {})} = {}) {
  console.log(foo, bar.quux, bar.corge);
}

// Oops!
fn3(); // Foo undefined undefined
fn3({foo: 'Quux'}); // Quux undefined undefined
fn3({bar: {quux: 'Baz'}}); // Foo Baz undefined
fn3({foo: 'Quux', bar: {corge: 'Baz'}}); // Quux undefined Baz
Hide result

, ES6. , ?

+4
1

{ … , propertyName: target = defaultInitialiser, … }

( , ).

target , , . , (3) , (1) - :

function fn3({foo = 'Foo', bar: {quux = 'Quux', corge = 'Corge'} = {}} = {}) {
  console.log(foo, quux, corge);
}

, bar. bar ,

function fn3({foo = 'Foo', bar, bar: {quux = 'Quux', corge = 'Corge'} = {}} = {}) {
  console.log(foo, bar, quux, corge);
}
+2

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


All Articles