Created
May 2, 2023 09:02
-
-
Save codeAdrian/429d64c96aadd003c372fa8e667f84f4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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([]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment