index.js 831 Bytes
const allocate = require("./allocate");
const free = require("./free");
const { printMemory, printStatus } = require("./print");
const parse = require("./parse");
const fs = require("fs");

function run(request, state) {
  const { type, payload } = request;
  const method = type == "allocate" ? allocate : free;
  const head =
    type == "allocate"
      ? `Request ${payload.id}: ${payload.size}K`
      : `Free Request ${payload}`;

  const nextState = method(state, payload);
  printMemory(nextState);
  printStatus(nextState);
  return nextState;
}

try {
  const raw = String(fs.readFileSync("test.txt"));
  const { MAX_CAPACITY, requests } = parse(raw);
  const init = { id: -1, size: MAX_CAPACITY };
  let state = [init];

  for (const request of requests) state = run(request, state);
} catch (e) {
  console.error(e);
}