all files / liquidjs/src/ syntax.js

100% Statements 37/37
100% Branches 15/15
100% Functions 4/4
100% Lines 36/36
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57   411× 410× 410× 410× 1222× 1222× 1222× 41× 41× 41× 41×       369× 19× 19× 19× 19× 89×   19×     350×     583× 583×   574× 372×   202× 201×       37×     41×          
const operators = require('./operators.js')
const lexical = require('./lexical.js')
const assert = require('../src/util/assert.js')
 
function evalExp (exp, scope) {
  assert(scope, 'unable to evalExp: scope undefined')
  var operatorREs = lexical.operators
  var match
  for (var i = 0; i < operatorREs.length; i++) {
    var operatorRE = operatorREs[i]
    var expRE = new RegExp(`^(${lexical.quoteBalanced.source})(${operatorRE.source})(${lexical.quoteBalanced.source})$`)
    if ((match = exp.match(expRE))) {
      var l = evalExp(match[1], scope)
      var op = operators[match[2].trim()]
      var r = evalExp(match[3], scope)
      return op(l, r)
    }
  }
 
  if ((match = exp.match(lexical.rangeLine))) {
    var low = evalValue(match[1], scope)
    var high = evalValue(match[2], scope)
    var range = []
    for (var j = low; j <= high; j++) {
      range.push(j)
    }
    return range
  }
 
  return evalValue(exp, scope)
}
 
function evalValue (str, scope) {
  str = str && str.trim()
  if (!str) return undefined
 
  if (lexical.isLiteral(str)) {
    return lexical.parseLiteral(str)
  }
  if (lexical.isVariable(str)) {
    return scope.get(str)
  }
  throw new TypeError(`cannot eval '${str}' as value`)
}
 
function isTruthy (val) {
  return !isFalsy(val)
}
 
function isFalsy (val) {
  return val === false || undefined === val || val === null
}
 
module.exports = {
  evalExp, evalValue, isTruthy, isFalsy
}