JSFiddle - React, Tailwind, and code Playground
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.min.css">
<input type="text" id="in" placeholder="enter desired pitch in mm">
<ul id="out"></ul>
CSS
input {
margin: 2em;
padding: 1em;
border-radius: 2px;
}
JavaScript 1.7
const range = (start, end) => {
let length = end - start;
let result = [start];
while (length--) result.push(++start);
return result;
};
const debounce = f => {
let timeout;
return function() {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(f.call.bind(f, this, ...arguments), 400);
};
};
const diff = (a, b) => (a - b) / a * 100;
const out = document.querySelector("#out");
const clear = () => {
while (out.firstChild) out.removeChild(out.firstChild);
};
const line = s => {
const li = document.createElement("li");
const t = document.createTextNode(s);
li.appendChild(t);
out.appendChild(li);
};
const gcd = (a,b) => {
while (b != 0) {
const t = b;
b = a % b;
a = t;
}
return a;
}
const simplify = (numer,denom) => {
while (numer % 1 !== 0|| denom % 1 !== 0) {
numer *= 10;
denom *= 10;
}
const g = gcd(numer,denom);
return [numer/g, denom/g];
}
/*
the meaty bit starts here:
*/
const startingPitch = 1.25;
const tolerance = 2.5;
const cogs = range(9, 100);
const chooseCogs = (ratio, desiredPitch) => {
let j,
chosenCogs = [],
finalPitch,
variance;
const tempCogs = ratio < 1 ? cogs.reduceRight((a, b) => [...a, b], []) : cogs;
for (const [i, cog1] of tempCogs.entries()) {
for (const cog2 of tempCogs.slice(i + 1)) {
finalPitch = (cog2 / cog1 * startingPitch).toFixed(2);
variance = Math.abs(diff(finalPitch, desiredPitch)).toFixed(1);
if (variance <= tolerance)
chosenCogs.push({ cog1, cog2, variance, finalPitch });
}
}
return chosenCogs;
};
const printCogs = (chosenCogs) => {
if (chosenCogs.length) {
const firstCogs = chosenCogs.shift();
line("\u200B");
line(`Optimal cog selection: ${firstCogs.cog1} and ${firstCogs.cog2} for ${firstCogs.finalPitch}mm (${firstCogs.variance}% variance)`);
if (chosenCogs.length) {
line("\u200B");
line(`Other cog selections:`);
chosenCogs
.slice(0, 10)
...