Skip to content
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

Fix nullable value error (#28) #44

Merged
merged 1 commit into from
Apr 30, 2023
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
14 changes: 5 additions & 9 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,15 +84,15 @@ const parseString = (() => {
let parameters = [];
let templateFn = () => str;

if (regex.test(str)) {
const matches = str.match(regex);
const matches = str.match(regex);
if (matches) {
parameters = matches.map(Parameter);
templateFn = context => {
context = context || {};
return matches.reduce((str, match, i) => {
return matches.reduce((result, match, i) => {
const parameter = parameters[i];
let value = objectPath.get(context, parameter.key);
if (value === undefined || value == null) {
if (value == null) {
value = parameter.defaultValue;
}

Expand All @@ -104,16 +104,12 @@ const parseString = (() => {
return value;
}

if (value === undefined || value === null) {
return null;
}

// Accommodate numbers as values.
if (matches.length === 1 && str.startsWith('{{') && str.endsWith('}}')) {
return value;
}

return str.replace(match, value);
return result.replace(match, value == null ? '' : value);
}, str);
};
}
Expand Down
5 changes: 5 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,11 @@ describe('json-template', () => {
const template = parse('{{foo}}');
assert.equal(template({ foo: '' }), '');
});

it('should handle null and undefined as empty strings for parameter value', () => {
const template = parse('{{foo}} {{bar}}');
assert.equal(template({ foo: null }), ' ');
});
});

// This section tests that the parse function recursively
Expand Down