Skip to content

Commit 61168f3

Browse files
authored
refactor(lodash): replace usage of snakeCase (#321)
1 parent 7ea8512 commit 61168f3

File tree

3 files changed

+23
-4
lines changed

3 files changed

+23
-4
lines changed

src/icon.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import React from 'react';
22
import IconMui from '@material-ui/core/Icon';
3-
import snakeCase from 'lodash/snakeCase';
3+
import utils from './utils';
44

55
// Note: we use font icons instead of SVG icons as this allows us to support any icon dynamically
66
// without adding all icons to the JS bundle. The MaterialUI icons are about 54KB which is
@@ -15,10 +15,10 @@ export default class Icon extends React.PureComponent {
1515
}
1616
};
1717

18-
// Convert to the font icon name so that we can use the SVG Icon names. This allows us to make
19-
// changes to this logic without changing the calling code.
18+
// Convert to the font icon name so that we can use the SVG Icon names in the MSON. This allows us
19+
// switch between font and SVG icons without changing the MSON definitions.
2020
toFontIconName(svgIconName) {
21-
return snakeCase(svgIconName);
21+
return utils.snakeCase(svgIconName);
2222
}
2323

2424
render() {

src/utils.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,16 @@ class Utils {
99
});
1010
return definedProps;
1111
}
12+
13+
snakeCase(str) {
14+
// 1. Make the first letter lower case so that we don't prepend an underscore in step 2
15+
const a = str.charAt(0).toLowerCase() + str.slice(1);
16+
17+
// 2. Convert all caps to lower case and prepend an underscore in all cases, except the first.
18+
const b = a.replace(/([A-Z])/g, (match) => '_' + match.toLowerCase());
19+
20+
// 3. Convert any sequence of non-alphanumeric characters to a single underscore
21+
return b.replace(/[^a-z0-9]+/, '_');
22+
}
1223
}
1324
export default new Utils();

src/utils.test.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import utils from './utils';
2+
3+
it('should convert to snake case', () => {
4+
expect(utils.snakeCase('Foo Bar')).toEqual('foo_bar');
5+
expect(utils.snakeCase('fooBar')).toEqual('foo_bar');
6+
expect(utils.snakeCase('FooBar')).toEqual('foo_bar');
7+
expect(utils.snakeCase('Foo Bar')).toEqual('foo_bar');
8+
});

0 commit comments

Comments
 (0)