bitburner-src/src/NetscriptFunctions/toNative.ts

40 lines
1.3 KiB
TypeScript
Raw Normal View History

2021-10-15 18:47:43 +02:00
import { Interpreter } from "../ThirdParty/JSInterpreter";
const defaultInterpreter = new Interpreter("", () => undefined);
// the acorn interpreter has a bug where it doesn't convert arrays correctly.
// so we have to more or less copy it here.
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
2021-10-15 18:47:43 +02:00
export function toNative(pseudoObj: any): any {
if (pseudoObj == null) return null;
if (
!pseudoObj.hasOwnProperty("properties") ||
!pseudoObj.hasOwnProperty("getter") ||
!pseudoObj.hasOwnProperty("setter") ||
!pseudoObj.hasOwnProperty("proto")
) {
return pseudoObj; // it wasn't a pseudo object anyway.
}
let nativeObj: any;
if (pseudoObj.hasOwnProperty("class") && pseudoObj.class === "Array") {
nativeObj = [];
const length = defaultInterpreter.getProperty(pseudoObj, "length");
2022-07-15 05:03:54 +02:00
if (typeof length === "number") {
for (let i = 0; i < length; i++) {
if (defaultInterpreter.hasProperty(pseudoObj, i)) {
nativeObj[i] = toNative(defaultInterpreter.getProperty(pseudoObj, i));
}
2021-10-15 18:47:43 +02:00
}
}
} else {
// Object.
nativeObj = {};
2022-01-16 01:45:03 +01:00
for (const key of Object.keys(pseudoObj.properties)) {
2021-10-15 18:47:43 +02:00
const val = pseudoObj.properties[key];
nativeObj[key] = toNative(val);
}
}
return nativeObj;
}