<h1>Array average of max 10 values</h1>
<p><code>arr</code> value</p>
<pre id="data">[]</pre>

<p>
  <label for="data-output"><code>arr.average</code></label>
<input value="0" readonly id="data-output" />
</p>

<button id="button">Add random number</button>
* {
  box-sizing: border-box;
}

body {
  padding: 2rem;
}

label {
  margin-bottom: 0.25rem;
  display: block;
}

pre {
  padding: 1rem;
  background-color: #eee;
  display: block;
}

h1 {
  margin-top: 0;
}
/* UTILS */

const getAverageScore = (score) =>
  score.length ? score.reduce((acc, point) => acc + point) / score.length : 0;

/* PROXY */

const handleSet = (obj, prop, value) => {
  const isNumber = !isNaN(parseInt(prop));

  if (isNumber) {
    const index = parseInt(prop);
    console.log(index);

    if (index >= 10) {
      throw new RangeError("Array limit reached");
    }

    Reflect.set(obj, prop, value);
  }

  Reflect.set(obj, prop, value);
  return true;
};

const handleGet = (obj, prop) => {
  if (prop === "average") {
    return getAverageScore(obj);
  }

  if (prop in obj) {
    return Reflect.get(obj, prop);
  }
};

const createArrayProxy = (arr) => {
  const proxy = new Proxy(arr, {
    set: handleSet,
    get: handleGet
  });

  return proxy;
};

/* INIT */

let arr = createArrayProxy([]);

/* ACTIONS */

const containerData = document.getElementById("data");
const output = document.getElementById("data-output");
const button = document.getElementById("button");

button.addEventListener("click", addRandomNumber);

function addRandomNumber() {
  const value = Math.floor(Math.random() * 11);

  try {
    arr.push(value);
    logValues();
  } catch (e) {
    console.error(e);
  }
}

/* LOG VALUES */

function logValues() {
  containerData.innerHTML = "";
  containerData.innerHTML = JSON.stringify(arr);

  output.value = arr.average;
}

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.