Skip to content

Commit

Permalink
Implement map filter function
Browse files Browse the repository at this point in the history
  • Loading branch information
kjellmorten committed Sep 21, 2017
1 parent 5123dbb commit 6d8d67a
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 1 deletion.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,18 @@ const template = 'http://example.com/{section|wrap(_, _)}{?ids|wrap([, ", ", ])}
//--> http://example.com/_news_/?ids=["ent1", "ent2", "ent5"]
```

### `map(from=to[, from=to[, ...]])`
Will map the given value to a replacement according to the `from=to` pairs
given as arguments to the `map` function. If no match is found, the value is
not replaced.

```
const params = {type: 'entry'}
const template = 'http://example.com/{type|map(article=articles, entry=entries)}'
...
//--> http://example.com/entries
```

## Max length
RFC 6570 specifies a 'prefix modifier', that limits the length of the value, by
suffixing a parameter with a colon and the max number of characters. This is
Expand Down
3 changes: 2 additions & 1 deletion lib/filters/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ module.exports = {
upper: require('./upper'),
lower: require('./lower'),
wrap: require('./wrap'),
max: require('./max')
max: require('./max'),
map: require('./map')
}
45 changes: 45 additions & 0 deletions lib/filters/map-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import test from 'ava'

import map from './map'

test('should exist', (t) => {
t.is(typeof map, 'function')
})

test('should map value', (t) => {
const value = 'entry'
const args = [
'account=accounts',
'entry=entries'
]

const ret = map(value, ...args)

t.is(ret, 'entries')
})

test('should return value when no match', (t) => {
const value = 'entry'
const args = ['account=accounts']

const ret = map(value, ...args)

t.is(ret, 'entry')
})

test('should return value when no mappings', (t) => {
const value = 'entry'

const ret = map(value)

t.is(ret, 'entry')
})

test('should not map null value', (t) => {
const value = null
const args = ['null=nope']

const ret = map(value, ...args)

t.is(ret, null)
})
16 changes: 16 additions & 0 deletions lib/filters/map.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
function map (value, ...mappings) {
if (value === null || value === undefined) {
return value
}

const searchFor = `${value}=`
const mapping = mappings.find((mapping) => mapping.startsWith(searchFor))

if (mapping) {
return mapping.substr(searchFor.length)
}

return value
}

module.exports = map

0 comments on commit 6d8d67a

Please sign in to comment.