<aside> đź’– This is a demonstration/showcase for how a power rule differentiation algorithm can be implemented programatically!

</aside>

$\color{#ff99c9} \utilde{\mathit{Prerequisites/Validation}}$

$\color{#ff99c9} \utilde{\mathit{Parsing~each~term}}$

$\color{#ff99c9} \utilde{\mathit{Finalizing~our~expression}}$

$\color{#ff99c9} \utilde{\mathit{Example~implementation~in~TypeScript}}$

// <https://bit.ly/cute-power-rule>
function differentiate(polynomial: string | null, variable = 'x') {
    if (!polynomial) return null;
    if (!isNaN(+polynomial)) return '0';

    const terms = polynomial.replace(/[ ]/g, '').split(/(?=[+-])/g).filter(x => x.includes(variable));

    const parsedParts = terms.map(term => {
        const [coefficient, exponent] = term.split(variable);
        if (!exponent) return `${coefficient}`

        const parsedExponent = exponent.replace('^', '');
        const parsedCoefficient = ['', '+', '-'].includes(coefficient) ? `${coefficient}1` : coefficient;

        const newCoefficient = parseInt(parsedCoefficient) * parseInt(parsedExponent);
        const newExponent = parseInt(parsedExponent) - 1;
        const signedCoefficient = `${newCoefficient > 0 ? '+' : ''}${newCoefficient}`;

        switch (newExponent) {
            case 0:
                return `${signedCoefficient}`;
            case 1:
                return `${signedCoefficient}${variable}`;
            default:
                return `${signedCoefficient}${variable}^${newExponent}`
        }
    })

    const result = parsedParts.join('');

    if (result.startsWith('+')) {
        return result.replace('+', '');
    }

    return result;
}