« get me outta code hell

quickstat (mayhaps) - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/quickstat.js
diff options
context:
space:
mode:
author(quasar) nebula <qznebula@protonmail.com>2025-12-20 20:26:44 -0400
committer(quasar) nebula <qznebula@protonmail.com>2025-12-20 20:26:44 -0400
commit1cf2cab3fdc25301f6a5276ebb40fec719808fc4 (patch)
tree05a9869ea1daeaef412afc03b1a042d773a54aa9 /src/quickstat.js
parent4b6de9bc45ec840ebda44c62f66f601a70a211cd (diff)
quickstat (mayhaps)
Diffstat (limited to 'src/quickstat.js')
-rw-r--r--src/quickstat.js52
1 files changed, 52 insertions, 0 deletions
diff --git a/src/quickstat.js b/src/quickstat.js
new file mode 100644
index 00000000..e8714b2a
--- /dev/null
+++ b/src/quickstat.js
@@ -0,0 +1,52 @@
+import * as fs from 'node:fs/promises';
+import * as path from 'node:path';
+
+export const requested = {};
+export const recorded = {};
+
+export function track(pathArg, {
+  readdir = false,
+  stat = false,
+}) {
+  pathArg = path.resolve(pathArg);
+  requested[pathArg] = {readdir, stat};
+}
+
+export function tracking(pathArg, resolved = false) {
+  if (!resolved) pathArg = path.resolve(pathArg);
+  for (const key of Object.keys(requested)) {
+    if (pathArg.startsWith(key + '/')) {
+      return requested[key];
+    }
+  }
+
+  return null;
+}
+
+async function go(fn, key, pathArg) {
+  pathArg = path.resolve(pathArg);
+
+  const info = tracking(pathArg, true);
+  if (!info?.[key]) return fn(pathArg);
+
+  const record = recorded[pathArg]?.[key];
+  if (record) return record;
+
+  const result = await fn(pathArg);
+  recorded[pathArg] ??= {};
+  recorded[pathArg][key] = result;
+  return result;
+}
+
+export function stat(pathArg) {
+  return go(fs.stat, 'stat', pathArg);
+}
+
+export function readdir(pathArg) {
+  return go(fs.readdir, 'readdir', pathArg);
+}
+
+export function reset() {
+  for (const key in requested) delete requested[key];
+  for (const key in recorded) delete recorded[key];
+}
\ No newline at end of file