Skip to content

monitor-adapter.js -- implement JSON support #1018

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

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
Changes from 3 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
23 changes: 21 additions & 2 deletions src/lib/monitor-adapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,17 @@ import OpcodeLabels from './opcode-labels.js';

const isUndefined = a => typeof a === 'undefined';

const circularReplacer = () => {
const stack = new Set();
return function replacer(key, value) {
if (typeof value === "object" && value !== null) {
if (stack.has(value)) return Array.isArray(value) ? "[...]" : "{...}";
stack.add(value);
}
return value;
};
};

/**
* Convert monitors from VM format to what the GUI needs to render.
* - Convert opcode to a label and a category
Expand Down Expand Up @@ -32,18 +43,26 @@ export default function ({id, spriteName, opcode, params, value, vm}) {
value = Number(value.toFixed(6));
}

// Turn the value to a string, for handle boolean values
// Turn the value to a string, to handle boolean values
if (typeof value === 'boolean') {
value = value.toString();
}

// Lists can contain booleans, which should also be turned to strings
// Turn the value to a string, to handle JSON values
// do not convert arrays as it will be confused for lists
if (typeof value === 'object' && !Array.isArray(value)) {
value = JSON.stringify(value, circularReplacer);
}

// Lists can contain booleans or Objects, which should also be turned to strings
if (Array.isArray(value)) {
value = value.slice();
for (let i = 0; i < value.length; i++) {
const item = value[i];
if (typeof item === 'boolean') {
value[i] = item.toString();
} else if (typeof value[i] === 'object' && !Array.isArray(value[i])) {
value[i] = JSON.stringify(item, circularReplacer);
}
}
}
Expand Down
Loading