diff --git a/packages/support/src/misc/index.ts b/packages/support/src/misc/index.ts index ec2a9815..c795169b 100644 --- a/packages/support/src/misc/index.ts +++ b/packages/support/src/misc/index.ts @@ -1,4 +1,5 @@ export * from './empty'; +export * from './isKey'; export * from './isPrimitive'; export * from './isPropertyKey'; export * from './isset'; diff --git a/packages/support/src/misc/isKey.ts b/packages/support/src/misc/isKey.ts new file mode 100644 index 00000000..b8f36690 --- /dev/null +++ b/packages/support/src/misc/isKey.ts @@ -0,0 +1,29 @@ +import { isPropertyKey } from "./isPropertyKey"; + +/** + * Determine if given is a valid {@link import('@aedart/contracts/support').Key} + * + * @see {isPropertyKey} + * + * @param {any} key + * + * @returns {boolean} + */ +export function isKey(key: any): boolean +{ + if (!Array.isArray(key)) { + key = [ key ]; + } + + if (key.length === 0) { + return false; + } + + for (const entry of key) { + if (!isPropertyKey(entry)) { + return false; + } + } + + return true; +} \ No newline at end of file diff --git a/tests/browser/packages/support/misc/isKey.test.js b/tests/browser/packages/support/misc/isKey.test.js new file mode 100644 index 00000000..876c720e --- /dev/null +++ b/tests/browser/packages/support/misc/isKey.test.js @@ -0,0 +1,43 @@ +import { + isKey +} from '@aedart/support/misc'; + +describe('@aedart/support/misc', () => { + describe('isKey', () => { + + it('can determine if value is a valid key', function () { + const valid = [ + 0, + 1, + -1, + NaN, + 'foo', + Symbol('my-symbol'), + [ 'a', 'b.c' ], + [ 'a', 'b.c', 12, Symbol('my-other-symbol') ], + ]; + + valid.forEach((value, index) => { + expect(isKey(value)) + .withContext(`Value at index ${index} is not a valid key`) + .toBeTrue(); + }); + + const invalid = [ + [], + () => false, + { name: 'John' }, + true, + false, + null, + undefined + ]; + + invalid.forEach((value, index) => { + expect(isKey(value)) + .withContext(`Invalid value at index ${index} SHOULD NOT be a valid key`) + .toBeFalse(); + }); + }); + }); +}); \ No newline at end of file