// bench_array.js — array operation benchmark (QuickJS)

const size = 100000;

function bench_push() {
  let a = [];
  for (let i = 0; i < size; i++) {
    a.push(i);
  }
  return a.length;
}

function bench_index_write() {
  let a = new Array(size).fill(0);
  for (let i = 0; i < size; i++) {
    a[i] = i;
  }
  return a[size - 1];
}

function bench_seq_read() {
  let a = new Array(size).fill(0);
  for (let i = 0; i < size; i++) {
    a[i] = i;
  }
  let s = 0;
  for (let i = 0; i < size; i++) {
    s = s + a[i];
  }
  return s;
}

function bench_reverse() {
  let a = new Array(size).fill(0);
  for (let i = 0; i < size; i++) {
    a[i] = i;
  }
  let lo = 0, hi = size - 1, tmp;
  while (lo < hi) {
    tmp = a[lo];
    a[lo] = a[hi];
    a[hi] = tmp;
    lo = lo + 1;
    hi = hi - 1;
  }
  return a[0];
}

function bench_matrix() {
  const n = 300;
  let mat = new Array(n);
  for (let i = 0; i < n; i++) {
    mat[i] = new Array(n).fill(0);
    for (let j = 0; j < n; j++) {
      mat[i][j] = i * n + j;
    }
  }
  let s = 0;
  for (let i = 0; i < n; i++) {
    s = s + mat[i][i];
  }
  return s;
}

function bench_filter_count() {
  let a = new Array(size).fill(0);
  for (let i = 0; i < size; i++) {
    a[i] = i;
  }
  let count = 0;
  for (let i = 0; i < size; i++) {
    if (a[i] % 2 === 0) {
      count = count + 1;
    }
  }
  return count;
}

function run(name, fn) {
  const start = performance.now();
  const result = fn();
  const elapsed = performance.now() - start;
  console.log(`  ${name}: ${elapsed.toFixed(2)} ms  (result: ${result})`);
}

console.log("=== Array Benchmark ===");
console.log(`  size: ${size}`);
run("push         ", bench_push);
run("index_write  ", bench_index_write);
run("seq_read_sum ", bench_seq_read);
run("reverse      ", bench_reverse);
run("matrix_300   ", bench_matrix);
run("filter_count ", bench_filter_count);
