Extending object with splat and do

97 Views Asked by At

Minor thing but wondering if someone can suggest a better syntax to extend an existing object using a splat, but without using curly braces? My main purpose is to keep indented style while passing the extended object to a function. This has the correct behavior:

base-obj =
  old-prop: \value

do-something {
  ...base-obj
  extended-prop: \value
}

But can the curly braces be eliminated somehow? 'Do' doesn't work:

old-obj =
  old-prop: \value

do-something do
  ...old-obj
  new-prop: \value

  # do-something will only see new-prop
3

There are 3 best solutions below

4
On

I found <<< which will get the job done but in a somewhat roundabout way:

do-something {} <<< base-obj <<<
  extended-prop1: \value1
  extended-prop2: \value2

Update: modified to prevent side-effect change to base-obj, based on @homam's suggestion.

2
On

Maybe what you want is with:

do-something base-obj with do
  extended-prop: \value

From LiveScript 1.3.1 operators' docs:

The infix with (aka the cloneport) combines the clone and property copy operators for easy object creation. It is equivalent to ^^obj <<< obj2. Remember that the clone operator creates a prototypical clone, and prototypes are not serialized in JSON.

0
On

Another way, using do:

# new object can overwrite old-obj
do-something do
  old-obj <<<
    new-prop: \value
    another: \content


# old-obj can overwrite new object
do-something do
  do
    new-prop: \value
    another: \content
  <<< old-obj