v2.0.3

Array and Object Extensions

Last updated


Negative-index access, aggregation, and existence checks added to Array.prototype and Object.prototype.

Array


Source: src/prototype/Array.ts
Method / PropertyDescription
arr.$sumSum of a numeric array via reduce
arr.$shuffleIn-place Fisher–Yates shuffle; returns this
arr.$mapA Map of value → index for every entry
arr._(value, index?)Negative-index-aware insert (splice); appends when index is omitted or out of range; an array value is spread in, undefined is ignored
arr.$(index)Negative-index-aware read; undefined when out of range
arr.$i(target)indexOf(target), returning undefined instead of -1
arr.$_(index)Negative-index-aware removal (splice)
arr.$$(target?)true if non-empty (no argument) or if target is present
arr.$req(body)Joins the captured Array.prototype (not the array instance) with /, so every call sends $req(body) to "/" resolved against location.origin

Object


Source: src/prototype/Object.ts (extends Object.prototype, so these apply to plain objects)
Method / PropertyDescription
obj.lengthObject.keys(this).length
obj.$keys / obj.$valuesObject.keys(this) / Object.values(this)
obj.$mapOwn enumerable entries as a Map
obj.forEach(cb)Array-like iteration: cb(key, value) over own enumerable properties
obj._(key, value, replace = true)Conditional setter for a non-empty string key and a defined value; only overwrites an existing key when replace is true
obj.$$(key?)hasOwnProperty(key) if key given, else this.length > 0

Example


Negative indices count from the end; obj._ with replace = false keeps the existing value.
  1. <script>
  2. const list = [10, 20, 30];
  3. console.log(list.$sum, list.$(-1), list.$i(20), list.$i(99));
  4. list._("x", -1);
  5. console.log(list);
  6. list.$_(0);
  7. console.log(list, list.$$(30));
  8. const dic = { a: 1 };
  9. dic._("a", 2, false);
  10. dic._("b", 3);
  11. console.log(dic, dic.length, dic.$keys, dic.$$("b"));
  12. </script>
Live preview · @pardnchiu/renderjs@2.0.3
中文