-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #18 from cloudfour/feat-default_helper
Feature: defaultTo helper
- Loading branch information
Showing
2 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
'use strict'; | ||
|
||
var R = require('ramda'); | ||
|
||
/** | ||
* Output a value if it exists, or fallback to a default if it does not. | ||
* | ||
* @since v0.0.1 | ||
* @param {*} value | ||
* @param {*} fallback | ||
* @param {Object} options | ||
* @return {String} | ||
* @example | ||
* | ||
* var doesExist = 'Hello'; | ||
* | ||
* {{defaultTo doesExist "Goodbye"}} // => "Hello" | ||
* {{defaultTo doesNotExist "Goodbye"}} // => "Goodbye" | ||
* {{defaultTo doesNotExist}} // => "" | ||
*/ | ||
|
||
module.exports = function defaultTo (value, fallback, options) { | ||
var defaultBlank = R.defaultTo(''); | ||
var defaultFallback = R.defaultTo(fallback); | ||
return R.isNil(options) ? | ||
defaultBlank(value) : R.pipe(defaultFallback, defaultBlank)(value); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
'use strict'; | ||
|
||
var defaultTo = require('../').defaultTo; | ||
var tape = require('tape'); | ||
var Handlebars = require('handlebars'); | ||
|
||
Handlebars.registerHelper(defaultTo.name, defaultTo); | ||
|
||
tape('defaultTo', function (test) { | ||
var template; | ||
var expected; | ||
var actual; | ||
|
||
test.plan(3); | ||
|
||
template = Handlebars.compile('{{defaultTo doesExist "Goodbye"}}'); | ||
expected = 'Hello'; | ||
actual = template({ doesExist: 'Hello' }); | ||
test.equal(actual, expected, 'Works with value set'); | ||
|
||
template = Handlebars.compile('{{defaultTo doesNotExist "Goodbye"}}'); | ||
expected = 'Goodbye'; | ||
actual = template({}); | ||
test.equal(actual, expected, 'Works with value not set'); | ||
|
||
template = Handlebars.compile('{{defaultTo doesNotExist}}'); | ||
expected = ''; | ||
actual = template({}); | ||
test.equal(actual, expected, 'Works with value and fallback not set'); | ||
}); |