2nd deegree equation flowie example

node v12.22.12
version: 1.0.0
endpointsharetweet
const flowie = require("flowie"); const secondDeegreeResolverFlow = flowie(detectsABC) // string(equation) to [number, number, number](a,b,c) .pipe(calculateDelta) // [number, number, number](a,b,c) to [number, number, number](a,b,delta) .split( returnsX1Result, // [number, number, number](a,b,delta) to { x': number, delta }(x1) returnsX2Result // [number, number, number](a,b,delta) to { x": number, delta }(x2) ) .pipe(mergeObjects) // merge objects const result = secondDeegreeResolverFlow('1x² - 3x - 10 = 0') console.log(result) // focus on the code above function detectsABC (equation) { const secondDeegreeEquationRegex = /^([+-]?\d+(?:\.\d+)?)x² ([+-] \d+(?:\.\d+)?)x ([+-] \d+(?:\.\d+)?) \= 0$/ if (!secondDeegreeEquationRegex.test(equation)) throw new Error("Unfortunately the equation has to be a.x² ± b.x ± c = 0\n, pay attention on spaces. Example: '1x² - 3x - 10 = 0'") const [, aCandidate, bCandidate, cCandidate] = equation.match(secondDeegreeEquationRegex) return [parseFloat(aCandidate), parseFloat(bCandidate.replace(' ', '')), parseFloat(cCandidate.replace(' ', ''))] } function calculateDelta ([a, b, c]) { return [a, b, (b ** 2) - 4 * a * c] } function returnsX1Result ([a, b, delta]) { return { "x'": ((-b + Math.sqrt(delta)) / (2 * a)), delta} } function returnsX2Result ([a, b, delta]) { return { 'x\"': ((-b - Math.sqrt(delta)) / (2 * a)), delta} } function mergeObjects ([x1, x2]) { return Object.assign({}, x1, x2) }
Loading…

no comments

    sign in to comment