/**
 *
 * @param {number} width
 * @param {number} scale
 * @returns {number}
 */
export function determineUnitSpacing(width, scale) {
    const baseTicks = 10;
    const axisLength = width * scale;

    const basePixelPerUnit = axisLength / baseTicks;
    const targetPixelSpacing = 32;

    const niceDivisionPattern = [1, 2, 5];

    let chosenDivision = 1;
    let lastDiff = Infinity;
    for (const patternValue of niceDivisionPattern) {
        const idealChoice = targetPixelSpacing / basePixelPerUnit
        //Note: patternValue × 10^n ≈ idealChoice
        const idealScale = idealChoice / patternValue;
        const n = Math.round(Math.log10(idealScale))
        const chosenPattern = patternValue * Math.pow(10,n)
        const diff = (Math.abs(basePixelPerUnit * chosenPattern - targetPixelSpacing))

        if ((diff < lastDiff)) {
            lastDiff = diff;
            chosenDivision = chosenPattern;
        }
    }

    return basePixelPerUnit * chosenDivision;
}