// round to <digits> significant places
function round(value, d=3) {
    let digits = d;
    let prec = Math.pow(10, Math.floor(Math.log(value) / Math.log(10)) - digits + 1);
    return Math.round(value / prec) * prec;
}

function typeset(value, lang) {  // number typesetting

    let digits = Math.log(value) / Math.log(10);

    let val = 0;
    if (digits < 0) {
        val = value.toFixed(2);
        if(val < 0.01) {
            return '< 0,01';
        }
        if(lang === 'de') {
            val = val.replace(/\./, ',');
        }
        return val;
    }
    if (digits < 1) {
        val = value.toFixed(1);
        if(lang === 'de') {
            val = val.replace(/\./, ',');
        }
        return val;
    }

    let factor = Math.pow(10, digits-1);
    val = Math.round(value / factor) * factor;
    val = val.toFixed(0);

    let s = '';
    while (val.length > 3) {  // 'layout' number in thousands groups
        s = ' ' + val.substr(-3) + s;
        val = val.substr(0, val.length-3);
    }

    return val + s;
}

function interpolate(min, max, t, mode) {

    switch (mode) {
        case 'inverseLinear':
            t = 1 - t;
            break;
        case 'quadratic':
            t = t * t;
            break;
        case 'inverseQuadratic':
            t = 1 - (1 - t) * (1 - t);
            break;
        case 'cubic':
            t = t * t * t;
            break;
        case 'inverseCubic':
            t = 1 - (1 - t ) * (1 - t) * (1 - t);
            break;
        case 'logarithmic':
            return Math.pow(min, t) * Math.pow(max, (1 - t));
        case 'inverseLogarithmic':
            return Math.pow(max, t) * Math.pow(min, (1 - t));
        case 'sine':
            return Math.sin(t * Math.PI / 2);
        case 'inverseSine':
            return 1 - Math.sin(t * Math.PI / 2);
        default:
            break;
    }

    return (1 - t) * min + t * max;
}

export {
    round,
    typeset,
    interpolate
};
