Skip to content

feat(regex): Add support for pluggable regex engines for use in evaluation #491

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions src/jsonata.js
Original file line number Diff line number Diff line change
Expand Up @@ -1088,7 +1088,7 @@ var jsonata = (function() {
* @returns {Function} Higher order function representing prepared regex
*/
function evaluateRegex(expr) {
var re = new RegExp(expr.value);
var re = new jsonata.RegexEngine(expr.value);
var closure = function(str, fromIndex) {
var result;
re.lastIndex = fromIndex || 0;
Expand Down Expand Up @@ -2041,7 +2041,9 @@ var jsonata = (function() {
/**
* JSONata
* @param {Object} expr - JSONata expression
* @param {boolean} options - recover: attempt to recover on parse error
* @param {Object} options
* @param {boolean} options.recover: attempt to recover on parse error
* @param {Function} options.RegexEngine: RegEx class constructor to use
* @returns {{evaluate: evaluate, assign: assign}} Evaluated expression
*/
function jsonata(expr, options) {
Expand All @@ -2066,6 +2068,12 @@ var jsonata = (function() {
return timestamp.getTime();
}, '<:n>'));

if(options && options.RegexEngine) {
jsonata.RegexEngine = options.RegexEngine;
} else {
jsonata.RegexEngine = RegExp;
}

return {
evaluate: function (input, bindings, callback) {
// throw if the expression compiled with syntax errors
Expand Down
28 changes: 28 additions & 0 deletions test/parser-pluggable-regex.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"use strict";

var jsonata = require('../src/jsonata');
var assert = require('assert');
var chai = require("chai");
var expect = chai.expect;

describe('Invoke parser with custom RegexEngine param', function() {

var regexContentSpy = null;
var regexEvalSpy = null;

function RegexEngineSpy(content) {
regexContentSpy = content;

this.exec = function(input) {
regexEvalSpy = input;
return null;
}
}

it('should call RegexEngine param constructure during evaluation', function() {
var expr = jsonata('$replace(\"foo\", /bar/, \"baaz\")', { RegexEngine: RegexEngineSpy });
expr.evaluate()
assert.deepEqual(regexContentSpy.toString(), "/bar/g");
assert.deepEqual(regexEvalSpy, "foo");
});
});