Advertisement
Guest User

Untitled

a guest
Feb 19th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var cellValue1 = '= a2 + 1 - a1 + average(a1, a2, a3) + sum(a2, a3)'
  2. var cellValue2 = '= sum(10, 20)'
  3. var cellValue3 = '100'
  4.  
  5. console.log(computeCell(cellValue1))
  6. console.log(computeCell(cellValue2))
  7. console.log(computeCell(cellValue3))
  8.  
  9. function computeCell(value) {
  10.   if (!isExpression(value)) {
  11.     return value
  12.   }
  13.   return computeExpression(value)
  14. }
  15.  
  16. function computeExpression(expression) {
  17.   var expressionReplaced = expression.toUpperCase()
  18.     // Strip all spaces
  19.     .replace(/\s/g, '')
  20.  
  21.     // Strip "=" at beggining of expression
  22.     .replace(/^\s*=\s*/, '')
  23.  
  24.     // Replace cell references with their values
  25.     .replace(/[A-Z]+\d+/g, function (match) {
  26.       return getCellValue(match)
  27.     })
  28.  
  29.     // Replace SUM expressions with their results
  30.     .replace(/SUM\((.*?)\)/g, function (sumExpression, sumExpressionInner) {
  31.       var sumValues = sumExpressionInner.split(',').map(Number)
  32.       return sumValues.reduce(function (sum, num) {
  33.         return sum + num
  34.       }, 0)
  35.     })
  36.  
  37.     // Replace AVERAGE expressions with their results
  38.     .replace(/AVERAGE\((.*?)\)/g, function (avgExpression, avgExpressionInner) {
  39.       var avgValues = avgExpressionInner.split(',').map(Number)
  40.       return avgValues.reduce(function (avg, num) {
  41.         return avg + num
  42.       }, 0) / avgValues.length
  43.     })
  44.   return evalMath(expressionReplaced)
  45. }
  46.  
  47. function evalMath(expression) {
  48.   return eval(expression)
  49. }
  50.  
  51. function getCellValue(coords) {
  52.   var values = {
  53.     A1: 5.5,
  54.     A2: 10,
  55.     A3: 6.6,
  56.   }
  57.   return values[coords]
  58. }
  59.  
  60. function isExpression(value) {
  61.   return /^\s*=\s*/.test(value)
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement