Skip to content

Commit

Permalink
Merge pull request naturalcrit#3625 from G-Ambatte/fixVarNameAsParam-…
Browse files Browse the repository at this point in the history
…#3622

Tweak variable math split regex
  • Loading branch information
calculuschild authored Aug 12, 2024
2 parents 284bfe5 + 5894dc5 commit cbc6dcd
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
2 changes: 1 addition & 1 deletion shared/naturalcrit/markdown.js
Original file line number Diff line number Diff line change
Expand Up @@ -452,7 +452,7 @@ const replaceVar = function(input, hoist=false, allowUnresolved=false) {
const label = match[2];

//v=====--------------------< HANDLE MATH >-------------------=====v//
const mathRegex = /[a-z]+\(|[+\-*/^()]/g;
const mathRegex = /[a-z]+\(|[+\-*/^(),]/g;
const matches = label.split(mathRegex);
const mathVars = matches.filter((match)=>isNaN(match))?.map((s)=>s.trim()); // Capture any variable names

Expand Down
24 changes: 21 additions & 3 deletions tests/markdown/variables.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -372,14 +372,32 @@ describe('Cross-page variables', ()=>{
});
});

describe('Variable name as a subset of a function or other variable name', ()=>{
it('Variable name as a subset of a function', function() {
describe('Math function parameter handling', ()=>{
it('allows variables in single-parameter functions', function() {
const source = '[var]:4.1\n\n$[floor(var)]';
const rendered = Markdown.render(source).trimReturns();
expect(rendered, `Input:\n${source}`, { showPrefix: false }).toBe(`<p>4</p>`);
});
it('allows one variable and a number in two-parameter functions', function() {
const source = '[var]:4\n\n$[min(1,var)]';
const rendered = Markdown.render(source).trimReturns();
expect(rendered, `Input:\n${source}`, { showPrefix: false }).toBe(`<p>1</p>`);
});
it('allows two variables in two-parameter functions', function() {
const source = '[var1]:4\n\n[var2]:8\n\n$[min(var1,var2)]';
const rendered = Markdown.render(source).trimReturns();
expect(rendered, `Input:\n${source}`, { showPrefix: false }).toBe(`<p>4</p>`);
});
});

describe('Variable names that are subsets of other names', ()=>{
it('do not conflict with function names', function() {
const source = `[a]: -1\n\n$[abs(a)]`;
const rendered = Markdown.render(source).trimReturns();
expect(rendered).toBe('<p>1</p>');
});

it('Variable name as a subset of another variable name', function() {
it('do not conflict with other variable names', function() {
const source = `[ab]: 2\n\n[aba]: 8\n\n[ba]: 4\n\n$[ab + aba + ba]`;
const rendered = Markdown.render(source).trimReturns();
expect(rendered).toBe('<p>14</p>');
Expand Down

0 comments on commit cbc6dcd

Please sign in to comment.