Skip to content

Commit

Permalink
Better enforce symbol naming [fix]
Browse files Browse the repository at this point in the history
  • Loading branch information
overlookmotel committed May 16, 2020
1 parent a19b65d commit 4954e47
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 8 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ symbols.FOO // => Symbol(FOO)
symbols.BAR // => Symbol(BAR)
```

### Naming

Names must only contain upper case letters (`A-Z`), digits (`0-9`), `_` or `$`. They must be valid JS identifiers (i.e. not start with a digit).

### Symbol store

You can cache all Symbols by passing a `store` option. `store` should be a plain object.
Expand Down
12 changes: 9 additions & 3 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@
'use strict';

// Modules
const {isObject, isFullString, isArray} = require('is-it-type');
const {isObject, isString, isFullString, isArray} = require('is-it-type');

// Exports

const NAME_REGEX = /^[A-Z_$][A-Z_$\d]*$/;

module.exports = function makeSymbols(namespace, names, options) {
// Conform args
if (isArray(namespace)) {
Expand All @@ -26,8 +28,12 @@ module.exports = function makeSymbols(namespace, names, options) {
// Validate names
const namesSet = new Set();
for (const name of names) {
if (!isFullString(name)) throw new TypeError('names must be an array of strings');
if (name.toUpperCase() !== name) throw new Error('symbol names must be all capitalized');
if (!isString(name)) throw new TypeError('names must be an array of strings');
if (!NAME_REGEX.test(name)) {
throw new Error(
`'${name}' is not a valid symbol name - must be in SNAKE_CASE and a valid JS identifier`
);
}
if (namesSet.has(name)) {
throw new Error(`symbol names must be unique - '${name}' was duplicated`);
}
Expand Down
18 changes: 13 additions & 5 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,13 +95,21 @@ describe('throws error if', () => {
it('contains empty string', () => {
expect(() => {
makeSymbols('foo', ['BAR', '']);
}).toThrowWithMessage(TypeError, 'names must be an array of strings');
}).toThrowWithMessage(Error, "'' is not a valid symbol name - must be in SNAKE_CASE and a valid JS identifier");
});

it('contains a non-capitalized string', () => {
expect(() => {
makeSymbols('foo', ['BAR', 'Qux']);
}).toThrowWithMessage(Error, 'symbol names must be all capitalized');
describe('contains invalid string', () => {
it.each([
'qux',
'QUx',
'Q.UX',
'Q-UX',
'1QUX'
])('%s', (name) => {
expect(() => {
makeSymbols('foo', ['BAR', name]);
}).toThrowWithMessage(Error, `'${name}' is not a valid symbol name - must be in SNAKE_CASE and a valid JS identifier`);
});
});

it('contains duplicates', () => {
Expand Down

0 comments on commit 4954e47

Please sign in to comment.