Skip to content
This repository has been archived by the owner on Sep 17, 2021. It is now read-only.

Commit

Permalink
feat(options): accept options as 3rd param
Browse files Browse the repository at this point in the history
The only option as of now is to skip the undefined ones
  • Loading branch information
thetutlage committed Sep 7, 2017
1 parent 0475cbd commit 3841981
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 6 deletions.
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@
* MIT Licensed
*/

module.exports = require('./src/index').pope
module.exports = require('./src/index').pope
17 changes: 17 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,23 @@ const pope = require('pope')
pope('There are {{0}} emails in your inbox', [20])
```

## Options

You can also pass an options object, which takes only one param for now and that is `skipUndefined`.

If `skipUndefined` is set to true, all unfound variables will be untouched, whereas originally they get replaced with an empty string.

```javascript
const pope = require('pope')
pope('There are {{0}} emails in your inbox', {}, {
skipUndefined: true
})

// returns - There are {{0}} emails in your inbox
```



## The MIT License

Copyright (c) 2015 Harminder Virk
Expand Down
11 changes: 6 additions & 5 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,19 @@ var prop = function(obj, path) {
* @return {String}
* @public
*/
var pope = function (string, data) {
var regex = /\{\{([\w\$\s]+)\}\}/gi
var pope = function (string, data, options) {
options = options || { skipUndefined: false }
var regex = /\{{2}([\w\$\s]+)\}{2}/gi
var result
var formattedString = string
while (result = regex.exec(string)){
var item = result[1].trim()
if(item) {
var value = prop(data, item) || null
if(!value){
formattedString = formattedString.replace(result[0], '')
}else{
if (value) {
formattedString = formattedString.replace(result[0], value)
} else if (!options.skipUndefined) {
formattedString = formattedString.replace(result[0], '')
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions test/pope.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,8 @@ describe('pope', function () {
expect(pope("Hello {{ user_name }}", { user_name: 'virk' }).trim()).to.equal('Hello virk')
expect(pope("Hello {{ $user_name }}", { '$user_name': 'virk' }).trim()).to.equal('Hello virk')
})

it('skip undefined', function () {
expect(pope("Hello {{ user_name }}", {}, { skipUndefined: true }).trim()).to.equal('Hello {{ user_name }}')
})
})

0 comments on commit 3841981

Please sign in to comment.