Vue

by WILLIAM CORREA

HTML

<div id="app">
  <fieldset>
    <div v-for="(value, key) in record">
      <label>{{ key }}</label>:
      <input type="number" v-model="record[key]">
    </div>
  </fieldset>
  <hr>
  <input type="text" class="formule" v-model="formule">
  <pre>{{ solved }}</pre>
</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

.formule {
  width: 100%;
}

Vue

/**
 * Title: Evaluating a string as a mathematical expression in JavaScript
 * Source code in: https://www.apptic.me/blog/evaluating-mathematical-expression-javascript.php
 */

function replaceAll (haystack, needle, replace) {
  return haystack.split(needle).join(replace)
} // replace all fx

const reformat = (s) => {
  s = s.toLowerCase()
  s = replaceAll(s, '-(', '-1*(')
  s = replaceAll(s, ')(', ')*(')
  s = replaceAll(s, ' ', '')
  s = replaceAll(s, '-', '+-')
  s = replaceAll(s, '--', '+')
  s = replaceAll(s, '++', '+')
  s = replaceAll(s, '(+', '(')
  for (let i = 0; i < 10; i++) {
    s = replaceAll(s, i + '(', i + '*' + '(')
  }
  while (s.charAt(0) === '+') s = s.substr(1)
  // console.log(s)
  return s
} // standardize string format

const strContain = (haystack, needle) => {
  return haystack.indexOf(needle) > -1
} // custom true/false contains

const isParseable = (n, minus) => {
  return (!isNaN(n) || (n === '-' && !minus) || n === '.')
} // determine if char should be added to side

const getSide = (haystack, middle, direction, minus) => {
  let i = middle + direction
  let term = ''
  let limit = (direction === -1) ? 0 : haystack.length // set the stopping point, when you have gone too far
  while (i * direction <= limit) { // while the current position is >= 0, or <= upper limit
    if (isParseable(haystack[i], minus)) {
      if (direction === 1) term = term + haystack[i]
      else term = haystack[i] + term
      i += direction
    } else { return term }
  }
  return term
} // general fx to get two terms of any fx (multiply, add, etc)

const allocFx = (eq, symbol, alloc, minus) => {
  minus = (typeof minus !== 'undefined') // sometimes we want to capture minus signs, sometimes not
  if (strContain(eq, symbol)) {
    let middleIndex = eq.indexOf(symbol)
    let left = getSide(eq, middleIndex, -1, minus)
    let right = getSide(eq, middleIndex, 1, false)
    eq = replaceAll(eq, left + symbol + right, alloc(left, right))
  }
  return eq
} // fx to...