Skip to content

Commit

Permalink
Add isKey util method
Browse files Browse the repository at this point in the history
  • Loading branch information
aedart committed Jan 28, 2024
1 parent 39714bd commit ac5828e
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/support/src/misc/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from './empty';
export * from './isKey';
export * from './isPrimitive';
export * from './isPropertyKey';
export * from './isset';
Expand Down
29 changes: 29 additions & 0 deletions packages/support/src/misc/isKey.ts
Original file line number Diff line number Diff line change
@@ -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;
}
43 changes: 43 additions & 0 deletions tests/browser/packages/support/misc/isKey.test.js
Original file line number Diff line number Diff line change
@@ -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();
});
});
});
});

0 comments on commit ac5828e

Please sign in to comment.