near-runtime-ts
near-runtime-ts copied to clipboard
Vector.toArray for casting
Looking at collections.Vector
there is no way to return the values in the vector to the outside world. In order to return the whole vector from the contract, I have something like
function toArray<T>(x: collections.Vector<T>): Array<T> {
const len = x.length;
const out = new Array<T>();
for(let i = 0; i < len; i++) { out.push(x[i]); }
return out;
}
However outside of the nearlib, I can't use generic types, and instead of patching the vector class myself, wanted to see if it could be added to the lib.
Another note: The type of the class can have [key: number]: T;
added to it, and then
x[0]
is typed correctly (right now there is a typescript warning).
Instead of casting entire vector to array, we should instead expose a getRange (or getSubarray) function, that takes (index, length) and returns an array of [index,index+length) elements. By default it can take index=0 and length=-1, which would return full vector.
Because a persistent vector may grow beyond smart contract ram, toArray may not fit into allocated memory.
for a name .slice
would be common in JS already, so I think .slice
would work?