Skip to content

Commit

Permalink
feat(issymbol): adding new util for checking if a value is a symbol
Browse files Browse the repository at this point in the history
  • Loading branch information
roggervalf committed May 1, 2020
1 parent 29c981f commit 6ddf3d1
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 5 deletions.
6 changes: 1 addition & 5 deletions src/getTag.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
const toString = Object.prototype.toString;

/**
* Gets the `toStringTag` of `value`.
* @private
Expand All @@ -15,7 +13,5 @@ const toString = Object.prototype.toString;
* ```
*/
export function getTag(value: any): string {
return toString.call(value);
return Object.prototype.toString.call(value);
}

export default getTag;
24 changes: 24 additions & 0 deletions src/isSymbol.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { isSymbol } from './isSymbol';

describe('isSymbol', () => {
it('should return `true` for symbols', () => {
expect(isSymbol(Symbol())).toEqual(true);
expect(isSymbol(Object(Symbol()))).toEqual(true);
});

it('should return `false` for non-symbols', () => {
expect(isSymbol()).toEqual(false);
expect(isSymbol(null)).toEqual(false);
expect(isSymbol(undefined)).toEqual(false);
expect(isSymbol(false)).toEqual(false);
expect(isSymbol(0)).toEqual(false);
expect(isSymbol(NaN)).toEqual(false);
expect(isSymbol('')).toEqual(false);
expect(isSymbol([1, 2, 3])).toEqual(false);
expect(isSymbol(new Date())).toEqual(false);
expect(isSymbol(new Error())).toEqual(false);
expect(isSymbol(Array.prototype.slice)).toEqual(false);
expect(isSymbol({ '0': 1, length: 1 })).toEqual(false);
expect(isSymbol(/x/)).toEqual(false);
});
});
24 changes: 24 additions & 0 deletions src/isSymbol.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { getTag } from './getTag';

/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @since 3.0.5
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* isSymbol(Symbol.iterator)
* // => true
*
* isSymbol('abc')
* // => false
*/
export function isSymbol(value?: any): boolean {
const type = typeof value;
return (
type === 'symbol' ||
(type === 'object' && value !== null && getTag(value) === '[object Symbol]')
);
}

0 comments on commit 6ddf3d1

Please sign in to comment.