custom_relational_functions.js (2051B)
1 const { create, all, factory } = require('../..') 2 3 // First let's see what the default behavior is: 4 // strings are compared by their numerical value 5 console.log('default (compare string by their numerical value)') 6 const { evaluate } = create(all) 7 evaluateAndLog(evaluate, '2 < 10') // true 8 evaluateAndLog(evaluate, '"2" < "10"') // true 9 evaluateAndLog(evaluate, '"a" == "b"') // Error: Cannot convert "a" to a number 10 evaluateAndLog(evaluate, '"a" == "a"') // Error: Cannot convert "a" to a number 11 console.log('') 12 13 // Suppose we want different behavior for string comparisons. To achieve 14 // this we can replace the factory functions for all relational functions 15 // with our own. In this simple example we use the JavaScript implementation. 16 console.log('custom (compare strings lexically)') 17 18 const allWithCustomFunctions = { 19 ...all, 20 21 createEqual: factory('equal', [], () => function equal (a, b) { 22 return a === b 23 }), 24 25 createUnequal: factory('unequal', [], () => function unequal (a, b) { 26 return a !== b 27 }), 28 29 createSmaller: factory('smaller', [], () => function smaller (a, b) { 30 return a < b 31 }), 32 33 createSmallerEq: factory('smallerEq', [], () => function smallerEq (a, b) { 34 return a <= b 35 }), 36 37 createLarger: factory('larger', [], () => function larger (a, b) { 38 return a > b 39 }), 40 41 createLargerEq: factory('largerEq', [], () => function largerEq (a, b) { 42 return a >= b 43 }), 44 45 createCompare: factory('compare', [], () => function compare (a, b) { 46 return a > b ? 1 : a < b ? -1 : 0 47 }) 48 } 49 const evaluateCustom = create(allWithCustomFunctions).evaluate 50 evaluateAndLog(evaluateCustom, '2 < 10') // true 51 evaluateAndLog(evaluateCustom, '"2" < "10"') // false 52 evaluateAndLog(evaluateCustom, '"a" == "b"') // false 53 evaluateAndLog(evaluateCustom, '"a" == "a"') // true 54 55 // helper function to evaluate an expression and print the results 56 function evaluateAndLog (evaluate, expression) { 57 try { 58 console.log(expression, evaluate(expression)) 59 } catch (err) { 60 console.error(expression, err.toString()) 61 } 62 }