Skip to content

Commit

Permalink
Added deep convertion to Result for toObject and toArray (#4681).
Browse files Browse the repository at this point in the history
  • Loading branch information
ricmoo committed Apr 10, 2024
1 parent 12772e9 commit 03bfe2a
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions src.ts/abi/coders/abstract-coder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,35 +130,45 @@ export class Result extends Array<any> {
}

/**
* Returns the Result as a normal Array.
* Returns the Result as a normal Array. If %%deep%%, any children
* which are Result objects are also converted to a normal Array.
*
* This will throw if there are any outstanding deferred
* errors.
*/
toArray(): Array<any> {
toArray(deep?: boolean): Array<any> {
const result: Array<any> = [ ];
this.forEach((item, index) => {
if (item instanceof Error) { throwError(`index ${ index }`, item); }
if (deep && item instanceof Result) {
item = item.toArray(deep);
}
result.push(item);
});
return result;
}

/**
* Returns the Result as an Object with each name-value pair.
* Returns the Result as an Object with each name-value pair. If
* %%deep%%, any children which are Result objects are also
* converted to an Object.
*
* This will throw if any value is unnamed, or if there are
* any outstanding deferred errors.
*/
toObject(): Record<string, any> {
toObject(deep?: boolean): Record<string, any> {
return this.#names.reduce((accum, name, index) => {
assert(name != null, "value at index ${ index } unnamed", "UNSUPPORTED_OPERATION", {
operation: "toObject()"
});

// Add values for names that don't conflict
if (!(name in accum)) {
accum[name] = this.getValue(name);
let child = this.getValue(name);
if (deep && child instanceof Result) {
child = child.toObject(deep);
}
accum[name] = child;
}

return accum;
Expand Down

0 comments on commit 03bfe2a

Please sign in to comment.