msgpackr 1.9.3 → 1.9.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/node.cjs CHANGED
@@ -1640,8 +1640,13 @@ class Packr extends Unpackr {
1640
1640
  if (Array.isArray(value)) {
1641
1641
  packArray(value);
1642
1642
  } else {
1643
- if (value.toJSON) // use this as an alternate mechanism for expressing how to serialize
1644
- return pack(value.toJSON());
1643
+ // use this as an alternate mechanism for expressing how to serialize
1644
+ if (value.toJSON) {
1645
+ const json = value.toJSON();
1646
+ // if for some reason value.toJSON returns itself it'll loop forever
1647
+ if (json !== value)
1648
+ return pack(json)
1649
+ }
1645
1650
 
1646
1651
  // if there is a writeFunction, use it, otherwise just encode as undefined
1647
1652
  if (type === 'function')
@@ -1686,7 +1691,7 @@ class Packr extends Unpackr {
1686
1691
  }
1687
1692
  };
1688
1693
 
1689
- const writePlainObject = this.variableMapSize ? (object) => {
1694
+ const writePlainObject = (this.variableMapSize || this.coercibleKeyAsNumber) ? (object) => {
1690
1695
  // this method is slightly slower, but generates "preferred serialization" (optimally small for smaller objects)
1691
1696
  let keys = Object.keys(object);
1692
1697
  let length = keys.length;
@@ -1702,9 +1707,19 @@ class Packr extends Unpackr {
1702
1707
  position += 4;
1703
1708
  }
1704
1709
  let key;
1705
- for (let i = 0; i < length; i++) {
1706
- pack(key = keys[i]);
1707
- pack(object[key]);
1710
+ if (this.coercibleKeyAsNumber) {
1711
+ for (let i = 0; i < length; i++) {
1712
+ key = keys[i];
1713
+ let num = Number(key);
1714
+ pack(isNaN(num) ? key : num);
1715
+ pack(object[key]);
1716
+ }
1717
+
1718
+ } else {
1719
+ for (let i = 0; i < length; i++) {
1720
+ pack(key = keys[i]);
1721
+ pack(object[key]);
1722
+ }
1708
1723
  }
1709
1724
  } :
1710
1725
  (object, safePrototype) => {