Welcome to the Onshape forum! Ask questions and join in the discussions about everything Onshape.

First time visiting? Here are some places to start:
  1. Looking for a certain topic? Check out the categories filter or use Search (upper right).
  2. Need support? Ask a question to our Community Support category.
  3. Please submit support tickets for bugs but you can request improvements in the Product Feedback category.
  4. Be respectful, on topic and if you see a problem, Flag it.

If you would like to contact our Community Manager personally, feel free to send a private message or an email.

Adding Maps

Brad_GoodmanBrad_Goodman Member Posts: 38 ✭✭
Is there a way to "add" maps? Or to easily use one map as a the "basis" for another - i.e. I have one map that defines a bunch of generic attributes - and I want to use that - or pass it with some other definitions?

I know I can make a [deep] copy of the original, then add new stuff to the copy - then pass this - but it just make my code a bit messier.

For example, I'd like to be able to:

var params={"depth":10,"shape":"square" ... etc etc etc... };<br>MakeMy Thing(params + {"x":10,"y":10});<br>MakeMy Thing(params + {"x":20,"y":20});
...or ...
MakeMy Thing(mapUnion(params,{"x":10,"y":10}));<br>MakeMy Thing(mapUnion(params ,{"x":20,"y":20}));
So then I thought I could make my own "mapUnion" (above) ... but does something like that exist???
Tagged:

Comments

  • kevin_o_toole_1kevin_o_toole_1 Onshape Employees, Developers, HDM Posts: 565
    mergeMaps is what you're looking for.

    The values of the second argument will override the first argument ("defaults") if the same key exists, so the order of your mapUnion function is already correct :smile:
  • kevin_o_toole_1kevin_o_toole_1 Onshape Employees, Developers, HDM Posts: 565
    edited January 2020
    You also commented about "deep copying", so it's worth mentioning: In FS, maps are value types which have incremental copy-on-write behaviors to save time and memory.

    So the code
    const hugeMap = getData();
    var modified = hugeMap;
    modified.x = 10;
    modified.y = 20;
    and the code
    const hugeMap = getData();
    const modified = mergeMaps(hugeMap, {
        "x" : 10,
        "y" : 20,
    });
    both have the same behavior: Changes to one map will not be reflected in the other map. From the perspective of the programmer, it behaves exactly like a deep copy has occurred on line 2 of both snippets (in every way except for speed and memory usage), and that none of the memory is shared. However, in reality, a full deep copy never happened, and most of the that memory is still shared under the hood (until it is changed, i.e. copy-on-write). This optimization is built into the FeatureScript language, not any explicitly written FS code.

    If you ever don't want the copy-like behavior and do want a shared reference to common data, use a box.
Sign In or Register to comment.