Skip to content

Commit

Permalink
fix cr comment and bug + add test
Browse files Browse the repository at this point in the history
  • Loading branch information
talsabagport committed Dec 25, 2023
1 parent e3c0109 commit 80bc176
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
6 changes: 3 additions & 3 deletions lib/template.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,16 +58,16 @@ const render = (inputJson, template) => {
}

const firstIndex = indices[0];
if (template.trim().startsWith('{{') && template.trim().endsWith('}}')) {
// If entire string is a template, evaluate and return
if (indices.length === 1 && template.trim().startsWith('{{') && template.trim().endsWith('}}')) {
// If entire string is a template, evaluate and return the result with the original type
return jq.exec(inputJson, template.slice(firstIndex.start, firstIndex.end));
}

let result = template.slice(0, firstIndex.start - '{{'.length); // Initiate result with string until first template start index
indices.forEach((index, i) => {
const jqResult = jq.exec(inputJson, template.slice(index.start, index.end));
result +=
// Add to the result the evaluated jq of the current template
// Add to the result the stringified evaluated jq of the current template
(typeof jqResult === 'string' ? jqResult : JSON.stringify(jqResult)) +
// Add to the result from template end index. if last template index - until the end of string, else until next start index
template.slice(
Expand Down
11 changes: 11 additions & 0 deletions test/template.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,5 +125,16 @@ describe('template', () => {
expect(render({'{{""}}': 'bar'})).toEqual({});
expect(render({'{{\'\'}}': 'bar'})).toEqual({});
});
it('recursive templates should work', () => {
const json = { foo: 'bar', bar: 'foo' };
const render = (input) => jq.renderRecursively(json, input);

expect(render({'{{.foo}}': '{{.bar}}{{.foo}}'})).toEqual({bar: 'foobar'});
expect(render({'{{.foo}}': {foo: '{{.foo}}'}})).toEqual({bar: {foo: 'bar'}});
expect(render([1, true, null, undefined, '{{.foo}}', 'https://{{.bar}}.com'])).toEqual([1, true, null, undefined, 'bar', 'https://foo.com']);
expect(render([['{{.bar}}{{.foo}}'], 1, '{{.bar | ascii_upcase}}'])).toEqual([['foobar'], 1, 'FOO']);
expect(render([{'{{.bar}}': [false, '/foo/{{.foo + .bar}}']}])).toEqual([{foo: [false, '/foo/barfoo']}]);
expect(render({foo: [{bar: '{{1}}'}, '{{empty}}']})).toEqual({foo: [{bar: 1}, undefined]});
});
})

0 comments on commit 80bc176

Please sign in to comment.