Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var cellValue1 = '= a2 + 1 - a1 + average(a1, a2, a3) + sum(a2, a3)'
- var cellValue2 = '= sum(10, 20)'
- var cellValue3 = '100'
- console.log(computeCell(cellValue1))
- console.log(computeCell(cellValue2))
- console.log(computeCell(cellValue3))
- function computeCell(value) {
- if (!isExpression(value)) {
- return value
- }
- return computeExpression(value)
- }
- function computeExpression(expression) {
- var expressionReplaced = expression.toUpperCase()
- // Strip all spaces
- .replace(/\s/g, '')
- // Strip "=" at beggining of expression
- .replace(/^\s*=\s*/, '')
- // Replace cell references with their values
- .replace(/[A-Z]+\d+/g, function (match) {
- return getCellValue(match)
- })
- // Replace SUM expressions with their results
- .replace(/SUM\((.*?)\)/g, function (sumExpression, sumExpressionInner) {
- var sumValues = sumExpressionInner.split(',').map(Number)
- return sumValues.reduce(function (sum, num) {
- return sum + num
- }, 0)
- })
- // Replace AVERAGE expressions with their results
- .replace(/AVERAGE\((.*?)\)/g, function (avgExpression, avgExpressionInner) {
- var avgValues = avgExpressionInner.split(',').map(Number)
- return avgValues.reduce(function (avg, num) {
- return avg + num
- }, 0) / avgValues.length
- })
- return evalMath(expressionReplaced)
- }
- function evalMath(expression) {
- return eval(expression)
- }
- function getCellValue(coords) {
- var values = {
- A1: 5.5,
- A2: 10,
- A3: 6.6,
- }
- return values[coords]
- }
- function isExpression(value) {
- return /^\s*=\s*/.test(value)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement