Skip to content

Instantly share code, notes, and snippets.

@dSalieri
Last active July 19, 2021 16:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dSalieri/a31e823147d0723dbfa844b4f9f866b6 to your computer and use it in GitHub Desktop.
Save dSalieri/a31e823147d0723dbfa844b4f9f866b6 to your computer and use it in GitHub Desktop.
If you want to know hz of your monitor
/// Complexity can't be less than 3 because sometimes happens lags and can get incorrect value, so minimal is 3, not less
async function getHz(complexity, approach) {
complexity = (complexity < 3 ? 3 : complexity) || 5;
approach = approach || "average";
let arr = [];
while (arr.length < complexity) {
let value = Math.floor(
await new Promise((resolve, reject) => {
requestAnimationFrame((time1) => requestAnimationFrame((time2) => resolve(1000 / (time2 - time1))));
})
);
arr.push(value);
}
/// approach #1 count the most amount repeats
function getMax(arr) {
let item = 0;
let count = 0;
arr.reduce((acc, el) => {
acc[el] = (acc[el] || 0) + 1;
item = acc[el] >= count ? (count++, el) : item;
return acc;
}, {});
return item;
}
/// approach #2 sort and get number standing in the middle
function getAverage(arr){
arr = arr.sort((a, b) => {
return a > b ? 1 : -1
});
return arr[Math.floor(arr.length / 2)];
}
return (approach === "average") ? getAverage(arr) : (approach === "counting") ? getMax(arr) : getAverage(arr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment