UNPKG

2.05 kBJavaScriptView Raw
1const { create, all, factory } = require('../..')
2
3// First let's see what the default behavior is:
4// strings are compared by their numerical value
5console.log('default (compare string by their numerical value)')
6const { evaluate } = create(all)
7evaluateAndLog(evaluate, '2 < 10') // true
8evaluateAndLog(evaluate, '"2" < "10"') // true
9evaluateAndLog(evaluate, '"a" == "b"') // Error: Cannot convert "a" to a number
10evaluateAndLog(evaluate, '"a" == "a"') // Error: Cannot convert "a" to a number
11console.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.
16console.log('custom (compare strings lexically)')
17
18const 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}
49const evaluateCustom = create(allWithCustomFunctions).evaluate
50evaluateAndLog(evaluateCustom, '2 < 10') // true
51evaluateAndLog(evaluateCustom, '"2" < "10"') // false
52evaluateAndLog(evaluateCustom, '"a" == "b"') // false
53evaluateAndLog(evaluateCustom, '"a" == "a"') // true
54
55// helper function to evaluate an expression and print the results
56function evaluateAndLog (evaluate, expression) {
57 try {
58 console.log(expression, evaluate(expression))
59 } catch (err) {
60 console.error(expression, err.toString())
61 }
62}