Last active
June 26, 2018 19:31
-
-
Save pmn4/eda16829166e190018cfc3716d25a4b3 to your computer and use it in GitHub Desktop.
Object.setPrototypeOf(newData, sourceData) instead of Object.assign({}, sourceData, newData)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // It happens all the time: you have some data, you want to update | |
| // a key without modifying the original object. You typically end | |
| // cloning the original with Object.assign({}, originalObject), | |
| // then adding your new data. This is probably pretty fast, even | |
| // for objects with many keys, but doesn't it seem unnecessary? | |
| function applyNewData(sourceData = { abc: 123, def: 456 }) { | |
| const newData = { abc: 789 }; | |
| // Previously, we'd write: | |
| // return Object.assign({}, sourceData, newData); | |
| // How about instead: | |
| return Object.setPrototypeOf(newData, sourceData); | |
| } | |
| /* ===== console ===== | |
| > applyNewData() | |
| < { abc: 789 } | |
| // but if you dig a little deeper: | |
| < { | |
| abc: 789, | |
| __proto__: { | |
| abc: 123, | |
| def: 456 | |
| } | |
| } | |
| > applyNewData().abc | |
| < 789 | |
| > applyNewData().def | |
| < 456 | |
| ===== console (end) ===== */ | |
| // ** On the bright side: ** | |
| // - the resulting object responds to `abc`, as we would expect, | |
| // but it also responds to `def` as the JS engine traverses the | |
| // prototype chain. | |
| // - creating the object is faster (it's a single operation: | |
| // assigning the prototype) and uses less memory | |
| // ** on the dark side: ** | |
| // - iterating over the object may have some unexpected results | |
| // - accessing the data introduces an extra step each time a | |
| // sourceData key is requested, as the JS engine first checks | |
| // for the key on the object itself, then on the prototype | |
| // - and then there's this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment