This library can parse Plural Forms header without violation of unsafe-eval rule from Content Security Policy.
It is using Shunting yard algorithm instead of eval()
or new Function()
.
const { parse } = require('plural-froms-parser');
const expression = 'n > 1 ? 2 : 3';
const rpnExpression = parse(expression);
// {
// postfix: [ 'n', 1, '>', 2, 3, '?:' ],
// evaluate: [Function: evaluate]
// }
rpnExpression.evaluate(1) // 2
rpnExpression.evaluate(2) // 3
There is also parseMemoized
function, which caches results of evaluation.