Destructuring

Description

Along with the Spread operator ( ), Destructuring would advance the language in enabling developers to reduce the boilerplate code currently necessary when dealing with passing arrays and structs/objects; particularly when doing so without mutating the original variable. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment for details on how this is implemented in JavaScript.

Simply put, destructuring means making a copy of individual items from an struct/object or an array and assigning them to a variable. For example:

1 2 3 4 5 6 function getPersonInfo( person ){ var place = {city: "New York", state: "NY"}; return { person, place }; } joe = {id: 1, firstName: "Joe", lastName: "Fusion" }; joeInfo = getPersonInfo( joe );

In the above example, getPersonInfo would return a struct with keys "person" and "place"; those keys would contain the structs defined for the respective variable. This would be in a sense a shorthand for:

return {person:duplicate(person), placelace};
(Notice the duplicate to illustrate the destructor should be creating copies, not passing references)

We should also be able to mix and match destructor with other values:

1 return{ person, place, ...someStruct, timestamp:now() }

see https://luceeserver.atlassian.net/browse/LDEV-2201 for "..." or "Spread" operator

Destructors should also be useful for plucking data out of a struct or array and into a variable as a copy. For example:

{ place, person } = getPersonInfo( joe );

Would result in two variables being created: place and person, and their values to be set to a copy (NOT A REFERENCE) of the variables with the same name provided from the right hand of the expression; getPersonInfo() in this case.

For structs, the keys inside the {} on the left hand side must have the same name as the keys you are destructuring on the right. For arrays, the values would be plucked out by position.

Samples with arrays:

1 2 3 4 5 function getAddressFromCSV( array line ){ // line = ["123 Main st.", "Pismo Beach", "San Luis Obispo", "CA"]; var [street, city, ,state] = line; return {street, city, state} }

The destructor in this case would extract the 1st, 2nd and 4th position in the array (Notice the blank 3rd position between city and state).

So, calling the above like so:

1 address = getAddress(["123 Main st.", "Pismo Beach", "San Luis Obispo", "CA"])

Would set address to:

1 2 3 4 5 { street: "123 Main st.", city: "Pismo Beach", state: "CA" }

This, as well as the Spread operator would make writing immutable functional style programs much more possible and would simplify the syntax and remove boilerplate for any style of coding.

Status

Assignee

Unassigned

Reporter

Abram Adams

Labels

None

Priority

New
Configure