From bd4aafe03d625de790d707b04ca277ceb3147aba Mon Sep 17 00:00:00 2001 From: magic-akari Date: Sat, 12 Aug 2023 02:38:15 +0800 Subject: [PATCH] refactor: early return for instance --- lib.js | 58 +++++++++++++++++++++++++++------------------------------- 1 file changed, 27 insertions(+), 31 deletions(-) diff --git a/lib.js b/lib.js index 626f361..5609c72 100644 --- a/lib.js +++ b/lib.js @@ -4,41 +4,37 @@ const go = new Go(); let inst; export default async function init(wasm_url) { - if (!inst) { - if (!wasm_url) { - wasm_url = new URL("lib.wasm", import.meta.url); - } + if (inst) { + return await inst; + } - if (typeof wasm_url === "string") { - wasm_url = new URL(wasm_url); - } + if (!wasm_url) { + wasm_url = new URL("lib.wasm", import.meta.url); + } - if ( - typeof __webpack_require__ !== "function" && - wasm_url.protocol === "file:" - ) { - inst = import("node:fs/promises") - .then((fs) => fs.readFile(wasm_url)) - .then((bytes) => - WebAssembly.instantiate(bytes, go.importObject) - ); - } else if ("instantiateStreaming" in WebAssembly) { - inst = WebAssembly.instantiateStreaming( - fetch(wasm_url), - go.importObject - ); - } else { - inst = fetch(wasm_url) - .then((response) => response.arrayBuffer()) - .then((bytes) => - WebAssembly.instantiate(bytes, go.importObject) - ); - } - inst = (await inst).instance; - go.run(inst); + if (typeof wasm_url === "string") { + wasm_url = new URL(wasm_url); } - await inst; + if ( + typeof __webpack_require__ !== "function" && + wasm_url.protocol === "file:" + ) { + inst = import("node:fs/promises") + .then((fs) => fs.readFile(wasm_url)) + .then((bytes) => WebAssembly.instantiate(bytes, go.importObject)); + } else if ("instantiateStreaming" in WebAssembly) { + inst = WebAssembly.instantiateStreaming( + fetch(wasm_url), + go.importObject + ); + } else { + inst = fetch(wasm_url) + .then((response) => response.arrayBuffer()) + .then((bytes) => WebAssembly.instantiate(bytes, go.importObject)); + } + inst = (await inst).instance; + go.run(inst); } export function format(input) {