On my quest towards creating a questionnaire, I aim to have questions appear or disappear dynamically based on specific rules represented as strings (e.g.
answers[1] == 'yes' || (answers[2] > 18 && answers[2] < 24)
).
These rules originate from the database and always result in either true or false. If true, the question is displayed, and if false, it remains hidden. Utilizing vue.js for the front-end, these rules are passed as props and need evaluation within a component during runtime.
I am seeking the most effective method to achieve this goal.
In preliminary tests, I experimented with
eval()
which yielded results. However, I acknowledge its safety risks and hence explore other options.One alternative involves replacing instances of "answers[x]" with their corresponding values since they are the only variables accessible. Nevertheless, this approach would still require another string for evaluation.
I came across a package named safe-eval that provides a sandboxed eval function where a context can be supplied for access to the answers. While previous versions reportedly had security vulnerabilities, newer updates seem to have addressed them. Would adopting this be a viable solution?
Are there any libraries designed to assist in crafting a parser or offering frameworks for rule creation and evaluation?
Edit: My initial inclination towards utilizing safe-eval
over custom parser development stems from its ability to evaluate intricate logic without necessitating an extensive class for handling such complexities.