Skip to content

Commit ea6cf31

Browse files
committed
Add defaultTo helper
1 parent e77e2f2 commit ea6cf31

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

lib/defaultTo.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
'use strict';
2+
3+
var R = require('ramda');
4+
5+
/**
6+
* Output a value if it exists, or fallback to a default if it does not.
7+
*
8+
* @since v0.0.1
9+
* @param {*} value
10+
* @param {*} fallback
11+
* @param {Object} options
12+
* @return {String}
13+
* @example
14+
*
15+
* var doesExist = 'Hello';
16+
*
17+
* {{defaultTo doesExist "Goodbye"}} // => "Hello"
18+
* {{defaultTo doesNotExist "Goodbye"}} // => "Goodbye"
19+
* {{defaultTo doesNotExist}} // => ""
20+
*/
21+
22+
module.exports = function defaultTo (value, fallback, options) {
23+
var defaultBlank = R.defaultTo('');
24+
var defaultFallback = R.defaultTo(fallback);
25+
return R.isNil(options) ?
26+
defaultBlank(value) : R.pipe(defaultFallback, defaultBlank)(value);
27+
};

test/defaultTo.spec.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
'use strict';
2+
3+
var defaultTo = require('../').defaultTo;
4+
var tape = require('tape');
5+
var Handlebars = require('handlebars');
6+
7+
Handlebars.registerHelper(defaultTo.name, defaultTo);
8+
9+
tape('defaultTo', function (test) {
10+
var template;
11+
var expected;
12+
var actual;
13+
14+
test.plan(3);
15+
16+
template = Handlebars.compile('{{defaultTo doesExist "Goodbye"}}');
17+
expected = 'Hello';
18+
actual = template({ doesExist: 'Hello' });
19+
test.equal(actual, expected, 'Works with value set');
20+
21+
template = Handlebars.compile('{{defaultTo doesNotExist "Goodbye"}}');
22+
expected = 'Goodbye';
23+
actual = template({});
24+
test.equal(actual, expected, 'Works with value not set');
25+
26+
template = Handlebars.compile('{{defaultTo doesNotExist}}');
27+
expected = '';
28+
actual = template({});
29+
test.equal(actual, expected, 'Works with value and fallback not set');
30+
});

0 commit comments

Comments
 (0)