Idea
Object.at( O, index ); //returns O's index'th entry
Object.size( O ); //returns O's count of enumerable properties
Why?
Say you want to pick a random object entry. (Or the last inserted object entry.)
You have to:
- iterate over all the entries with
for...in
- or, allocate an entire new array with
Object.entries()
.
This is an unnecessary problem, because JS engines already have an addressable index of an object's entries.
You might think: Just use an Array
instead of an Object
.
But no! Picking a random entry from an array is easy. But now what if you want to pick an entry by a specific key? Arrays are expensive to search for key-value pairs, so you end up with the same inefficiency problem. :-/
Solution!
Object.at()
and Object.size()
, implemented as a built-in-functions, provide efficient non-linear, blind access, and efficient key-value searching.
This would be amazing! It combines the best of Object
with the best of Array
. Currently, Object
provides fast key-searching (when you know what you want, but not where it is), and Array
provides non-linear, blind access (when you don't know what you want, but you know where it is).
Adding at()
and size()
would marry the best of both worlds by allowing random, indexed access into a fast-searchable key/value structure. :-)
Polyfill
Note: I've included polyfill code below, but this polyfill code is not what I am proposing! Please do not hijack this thread to point out typos or best code practices!! I am proposing a built-in function that makes the code below unnecessary.
Here are two ways these functions' polyfills could be implemented, neither of which is practical or efficient compared to a built-in function.
Polyfill via iteration:
Object.at = ( O, index ) => {
let i = 0, entry = undefined;
for( const key in O ) {
if( i === index ) {
entry = [ key, O[ key ] ];
break;
}
++ i;
}
return entry;
}
Object.size = ( O ) => {
let i = 0;
for( const key in O ) {
++ i;
}
return i;
}
Polyfill via array-allocation:
Object.at = ( O, index ) => Object.entries( O )[ index ];
Object.size = ( O ) => Object.entries( O ).length;
These functions would benefit enormously from being built-ins, since JS engines already have indexed search into object entries, only unexposed.
(I would also like to add a symbol for iterators to allow the user to implement iterator-specific at()
and size()
functions, but lets keep it simple here.)