<aside> đź’– This is a demonstration/showcase for how a power rule differentiation algorithm can be implemented programatically!
</aside>
$\color{#ff99c9} \utilde{\mathit{Prerequisites/Validation}}$
null early0+ and - but maintain the symbols in the matches
/(?=[+-])/gx term (they are constants)$\color{#ff99c9} \utilde{\mathit{Parsing~each~term}}$
x or whatever variable is passed into the function
4x^3 and the variable is x then splitting will return something similar to ['+4', '^3'].x) then we can assume that it is x^1 and return just the constant coefficient.^ character as this is just semantics.x is just an empty string or +/- then we can assume that there is no coefficient and make it 1.+ symbol to maintain the original sign of the expression, as parseInt will omit the + internally when parsing to a number.0: There is no longer any x term, so just return the constant coefficient an.1: There is only a single x , so don’t include the ^n exponent, just return anxAnything else: Return anx^{n-1}$\color{#ff99c9} \utilde{\mathit{Finalizing~our~expression}}$
+ at the beginning of the parsed expression. If we do, then simply remove it before returning to the user.$\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;
}