Expanding binomial expression using JavaScript


Problem

We are required to write a JavaScript function that takes in an expression in the form (ax+b)^n where a and b are integers which may be positive or negative, x is any single character variable, and n is a natural number. If a = 1, no coefficient will be placed in front of the variable.

Our function should return the expanded form as a string in the form ax^b+cx^d+ex^f... where a, c, and e are the coefficients of the term, x is the original one-character variable that was passed in the original expression and b, d, and f, are the powers that x is being raised to in each term and are in decreasing order

Example

Following is the code −

 Live Demo

const str = '(8a+6)^4';
const trim = value => value === 1 ? '' : value === -1 ? '-' : value
const factorial = (value, total = 1) =>
value <= 1 ? total : factorial(value - 1, total * value)
const find = (str = '') => {
   let [op1, coefficient, variable, op2, constant, power] = str
   .match(/(\W)(\d*)(\w)(\W)(\d+)..(\d+)/)
   .slice(1)
   power = +power
   if (!power) {
      return '1'
   }
   if (power === 1) {
      return str.match(/\((.*)\)/)[1]
   }
   coefficient =
   op1 === '-'
   ? coefficient
   ? -coefficient
   : -1
   : coefficient
   ? +coefficient
   : 1
   constant = op2 === '-' ? -constant : +constant
   const factorials = Array.from({ length: power + 1 }, (_,i) => factorial(i))
   let result = ''
   for (let i = 0, p = power; i <= power; ++i, p = power - i) {
      let judge =
      factorials[power] / (factorials[i] * factorials[p]) *
      (coefficient * p * constant * i)
      if (!judge) {
         continue
      }
      result += p
      ? trim(judge) + variable + (p === 1 ? '' : `^${p}`)
      : judge
      result += '+'
   }
   return result.replace(/\+\-/g, '-').replace(/\+$/, '')
};
console.log(find(str));

Output

576a^3+1152a^2+576a

Updated on: 17-Apr-2021

205 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements