Skip to content

Commit

Permalink
Merge pull request #1 from mgoffan/master
Browse files Browse the repository at this point in the history
  • Loading branch information
cheton committed Dec 27, 2016
2 parents 2d26894 + 94e2b7d commit 7c362d3
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 2 deletions.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,26 @@ module.exports = constants('todos', [
// }
```

#### Transform constants
You can pass a custom transform function as well:
```js
module.exports = constants('todos', [
'add todo',
'remove todo',
'toggle todo'
], {
separator: '/',
transform: function (v) {
return v.replace(/\ /g, '_').toUpperCase();
}
});
// {
// 'ADD_TODO': 'todos/ADD_TODO',
// 'REMOVE_TODO': 'todos/REMOVE_TODO'
// 'TOGGLE_TODO': 'todos/TOGGLE_TODO'
// }
```

## License

Copyright (c) 2016 Cheton Wu
Expand Down
7 changes: 5 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const defaultOptions = {
separator: ':'
separator: ':',
transform: v => v
};

const constants = (namespace = '', constants = [], options = defaultOptions) => {
Expand All @@ -9,12 +10,14 @@ const constants = (namespace = '', constants = [], options = defaultOptions) =>
}

options.separator = options.separator || defaultOptions.separator;
options.transform = options.transform || defaultOptions.transform;

// Prevent new properties from being added to it
return Object.freeze(constants.reduce((memo, constant) => {
const transformedConstant = options.transform(constant)
return {
...memo,
[constant]: namespace ? `${namespace}${options.separator}${constant}` : constant
[transformedConstant]: namespace ? `${namespace}${options.separator}${transformedConstant}` : transformedConstant
};
}, {}));
};
Expand Down
35 changes: 35 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,38 @@ test('namespace action constants with a custom separator', (t) => {
t.same(result, wanted);
t.end();
});

test('namespace action constants with a custom transform', (t) => {
const result = constants('todos', [
'add todo',
'remove todo',
'toggle todo'
], {
separator: '/',
transform: v => v.replace(/\ /g, '_').toUpperCase()
})
const wanted = {
'ADD_TODO': 'todos/ADD_TODO',
'REMOVE_TODO': 'todos/REMOVE_TODO',
'TOGGLE_TODO': 'todos/TOGGLE_TODO'
};
t.same(result, wanted);
t.end();
})

test('namespace action constants with a custom separator and custom transform', (t) => {
const result = constants('todos', [
'add todo',
'remove todo',
'toggle todo'
], {
transform: v => v.replace(/\ /g, '_').toUpperCase()
})
const wanted = {
'ADD_TODO': 'todos:ADD_TODO',
'REMOVE_TODO': 'todos:REMOVE_TODO',
'TOGGLE_TODO': 'todos:TOGGLE_TODO'
};
t.same(result, wanted);
t.end();
})

0 comments on commit 7c362d3

Please sign in to comment.