From 94e2b7df85b4a533446fd884822919048ffd4408 Mon Sep 17 00:00:00 2001 From: Martin Goffan Date: Tue, 27 Dec 2016 11:59:58 -0300 Subject: [PATCH] Added ability to transform constants name --- README.md | 20 ++++++++++++++++++++ src/index.js | 7 +++++-- test/index.js | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 64fd3f9..0eba5c0 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/src/index.js b/src/index.js index b8aeb84..c618fb4 100644 --- a/src/index.js +++ b/src/index.js @@ -1,5 +1,6 @@ const defaultOptions = { - separator: ':' + separator: ':', + transform: v => v }; const constants = (namespace = '', constants = [], options = defaultOptions) => { @@ -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 }; }, {})); }; diff --git a/test/index.js b/test/index.js index e157f6c..ca424ac 100644 --- a/test/index.js +++ b/test/index.js @@ -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(); +}) \ No newline at end of file