Skip to content

Commit 7364ae8

Browse files
authored
Merge pull request #44 from mytharcher/master
Fix nullable value error (#28)
2 parents 0441c67 + 3808cbb commit 7364ae8

File tree

2 files changed

+10
-9
lines changed

2 files changed

+10
-9
lines changed

index.js

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -84,15 +84,15 @@ const parseString = (() => {
8484
let parameters = [];
8585
let templateFn = () => str;
8686

87-
if (regex.test(str)) {
88-
const matches = str.match(regex);
87+
const matches = str.match(regex);
88+
if (matches) {
8989
parameters = matches.map(Parameter);
9090
templateFn = context => {
9191
context = context || {};
92-
return matches.reduce((str, match, i) => {
92+
return matches.reduce((result, match, i) => {
9393
const parameter = parameters[i];
9494
let value = objectPath.get(context, parameter.key);
95-
if (value === undefined || value == null) {
95+
if (value == null) {
9696
value = parameter.defaultValue;
9797
}
9898

@@ -104,16 +104,12 @@ const parseString = (() => {
104104
return value;
105105
}
106106

107-
if (value === undefined || value === null) {
108-
return null;
109-
}
110-
111107
// Accommodate numbers as values.
112108
if (matches.length === 1 && str.startsWith('{{') && str.endsWith('}}')) {
113109
return value;
114110
}
115111

116-
return str.replace(match, value);
112+
return result.replace(match, value == null ? '' : value);
117113
}, str);
118114
};
119115
}

test.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,11 @@ describe('json-template', () => {
130130
const template = parse('{{foo}}');
131131
assert.equal(template({ foo: '' }), '');
132132
});
133+
134+
it('should handle null and undefined as empty strings for parameter value', () => {
135+
const template = parse('{{foo}} {{bar}}');
136+
assert.equal(template({ foo: null }), ' ');
137+
});
133138
});
134139

135140
// This section tests that the parse function recursively

0 commit comments

Comments
 (0)