Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API: Improve built-in print APIs when printing objects containing Map or Set #1723

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 22 additions & 8 deletions src/Netscript/NetscriptHelpers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,19 @@ function spawnOptions(ctx: NetscriptContext, threadOrOption: unknown): CompleteS
return result;
}

function mapToString(map: Map<unknown, unknown>): string {
const formattedMap = [...map]
.map((m) => {
return `${m[0]} => ${m[1]}`;
})
.join("; ");
return `< Map: ${formattedMap} >`;
}

function setToString(set: Set<unknown>): string {
return `< Set: ${[...set].join("; ")} >`;
}

/** Convert multiple arguments for tprint or print into a single string. */
function argsToString(args: unknown[]): string {
// Reduce array of args into a single output string
Expand All @@ -243,17 +256,12 @@ function argsToString(args: unknown[]): string {

// Handle Map formatting, since it does not JSON stringify or toString in a helpful way
// output is "< Map: key1 => value1; key2 => value2 >"
if (nativeArg instanceof Map && [...nativeArg].length) {
const formattedMap = [...nativeArg]
.map((m) => {
return `${m[0]} => ${m[1]}`;
})
.join("; ");
return (out += `< Map: ${formattedMap} >`);
if (nativeArg instanceof Map) {
return (out += mapToString(nativeArg));
}
// Handle Set formatting, since it does not JSON stringify or toString in a helpful way
if (nativeArg instanceof Set) {
return (out += `< Set: ${[...nativeArg].join("; ")} >`);
return (out += setToString(nativeArg));
}
if (typeof nativeArg === "object") {
return (out += JSON.stringify(nativeArg, (_, value) => {
Expand All @@ -264,6 +272,12 @@ function argsToString(args: unknown[]): string {
if (value instanceof Promise) {
return value.toString();
}
if (value instanceof Map) {
return mapToString(value);
}
if (value instanceof Set) {
return setToString(value);
}
return value;
}));
}
Expand Down