| 12 | const { Engine } = require('json-rules-engine') |
| 13 | |
| 14 | async function start () { |
| 15 | /** |
| 16 | * Setup a new engine |
| 17 | */ |
| 18 | const engine = new Engine() |
| 19 | |
| 20 | // rule for determining honor role student athletes (student has GPA >= 3.5 AND is an athlete) |
| 21 | engine.addRule({ |
| 22 | conditions: { |
| 23 | all: [{ |
| 24 | fact: 'athlete', |
| 25 | operator: 'equal', |
| 26 | value: true |
| 27 | }, { |
| 28 | fact: 'GPA', |
| 29 | operator: 'greaterThanInclusive', |
| 30 | value: 3.5 |
| 31 | }] |
| 32 | }, |
| 33 | event: { // define the event to fire when the conditions evaluate truthy |
| 34 | type: 'honor-roll', |
| 35 | params: { |
| 36 | message: 'Student made the athletics honor-roll' |
| 37 | } |
| 38 | }, |
| 39 | name: 'Athlete GPA Rule' |
| 40 | }) |
| 41 | |
| 42 | function render (message, ruleResult) { |
| 43 | // if rule succeeded, render success message |
| 44 | if (ruleResult.result) { |
| 45 | return console.log(`${message}`.green) |
| 46 | } |
| 47 | // if rule failed, iterate over each failed condition to determine why the student didn't qualify for athletics honor roll |
| 48 | const detail = ruleResult.conditions.all.filter(condition => !condition.result) |
| 49 | .map(condition => { |
| 50 | switch (condition.operator) { |
| 51 | case 'equal': |
| 52 | return `was not an ${condition.fact}` |
| 53 | case 'greaterThanInclusive': |
| 54 | return `${condition.fact} of ${condition.factResult} was too low` |
| 55 | default: |
| 56 | return '' |
| 57 | } |
| 58 | }).join(' and ') |
| 59 | console.log(`${message} ${detail}`.red) |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * On success, retrieve the student's username and print rule name for display purposes, and render |
| 64 | */ |
| 65 | engine.on('success', (event, almanac, ruleResult) => { |
| 66 | almanac.factValue('username').then(username => { |
| 67 | render(`${username.bold} succeeded ${ruleResult.name}! ${event.params.message}`, ruleResult) |
| 68 | }) |
| 69 | }) |
| 70 | |
| 71 | /** |