From 138fd3ec9b75c897b54ccac69f06abff83bfcf07 Mon Sep 17 00:00:00 2001 From: atomiks Date: Sun, 31 Dec 2017 21:48:13 +1100 Subject: [PATCH 1/2] Add isPrimitive utility snippet --- snippets/isPrimitive.md | 22 ++++++++++++++++++++++ tag_database | 1 + 2 files changed, 23 insertions(+) create mode 100644 snippets/isPrimitive.md diff --git a/snippets/isPrimitive.md b/snippets/isPrimitive.md new file mode 100644 index 000000000..cd90501b3 --- /dev/null +++ b/snippets/isPrimitive.md @@ -0,0 +1,22 @@ +### isPrimitive + +Returns a boolean determining if the supplied value is primitive or not. + +Use `Array.includes()` on an array of type strings, supplying the type using `typeof`. +Since `typeof null` evaluates to `'object'`, it needs to be directly compared. + +```js +const isPrimitive = value => + ['string', 'number', 'symbol', 'boolean', 'undefined'].includes(typeof value) || value === null; +``` + +```js +isPrimitive(window.someNonExistentProperty); // true +isPrimitive(null); // true +isPrimitive(50); // true +isPrimitive('Hello!'); // true +isPrimitive(false); // true +isPrimitive(Symbol()); // true +isPrimitive([]); // false +isPrimitive(new String('Hello!')); // false +``` diff --git a/tag_database b/tag_database index d897e319c..9287acd90 100644 --- a/tag_database +++ b/tag_database @@ -71,6 +71,7 @@ isEven:math isFunction:utility isNumber:utility isPrime:math +isPrimitive:utility isString:utility isSymbol:utility JSONToDate:date From 31d41352ffaeb95e77241022c6a01ba6c765d093 Mon Sep 17 00:00:00 2001 From: atomiks Date: Mon, 1 Jan 2018 04:27:20 +1100 Subject: [PATCH 2/2] Optimize --- snippets/isPrimitive.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/snippets/isPrimitive.md b/snippets/isPrimitive.md index cd90501b3..3abe155c4 100644 --- a/snippets/isPrimitive.md +++ b/snippets/isPrimitive.md @@ -2,12 +2,12 @@ Returns a boolean determining if the supplied value is primitive or not. -Use `Array.includes()` on an array of type strings, supplying the type using `typeof`. +Use `Array.includes()` on an array of type strings which are not primitive, +supplying the type using `typeof`. Since `typeof null` evaluates to `'object'`, it needs to be directly compared. ```js -const isPrimitive = value => - ['string', 'number', 'symbol', 'boolean', 'undefined'].includes(typeof value) || value === null; +const isPrimitive = val => !['object', 'function'].includes(typeof val) || val === null; ``` ```js