near-runtime-ts icon indicating copy to clipboard operation
near-runtime-ts copied to clipboard

Vector.toArray for casting

Open DanielRX opened this issue 5 years ago • 2 comments

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).

DanielRX avatar Aug 08 '19 12:08 DanielRX

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.

evgenykuzyakov avatar Aug 08 '19 18:08 evgenykuzyakov

for a name .slice would be common in JS already, so I think .slice would work?

DanielRX avatar Aug 08 '19 20:08 DanielRX