Public
Edited
Jul 30, 2023
Insert cell
Insert cell
function findAllowedFractions(denominators) {
function uniqueArr (arr, key) {
return arr.filter(
(obj, index) =>
arr.findIndex((item) => item[key] === obj[key]) === index
)
};
return uniqueArr(denominators.map(v => {
const fractions = [[0, 0, 0], [1, 1, 1]];
for (let i = 1; i < v; ++i) {
fractions.push([i, v, i / v]);
}
return fractions;
}).flat().sort((a, b) => a[2] - b[2]), 2);
}
Insert cell
function findFraction(val, denominators) {
const allowedFractions = findAllowedFractions(denominators);
let fraction = allowedFractions[0];
for (let i = 0; i < allowedFractions.length; ++i) {
const current = allowedFractions[i];
if (current[2] > val) {
return Math.abs(current[2] - val) > Math.abs(fraction[2] - val) ? fraction : current;
} else {
fraction = current;
}
}
return fraction;
}
Insert cell
findFraction(0.53, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
Insert cell
findFraction(0.1, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
Insert cell
findFraction(0.912, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more