diff --git a/src/lib/util/typeOf.js b/src/lib/util/typeOf.js new file mode 100644 index 000000000..f96af511a --- /dev/null +++ b/src/lib/util/typeOf.js @@ -0,0 +1,10 @@ +/** + * Better way to handle type checking + * null, {}, array and date are objects, which confuses + */ +export default function typeOf(input) { + const rawObject = Object.prototype.toString.call(input).toLowerCase(); + const typeOfRegex = /\[object (.*)]/g; + const type = typeOfRegex.exec(rawObject)[1]; + return type; +} diff --git a/test/util.js b/test/util.js new file mode 100644 index 000000000..449cd9ee7 --- /dev/null +++ b/test/util.js @@ -0,0 +1,20 @@ +/** + * All tests that tests any utility. + * Prevent any breaking of functionality + */ +import assert from 'assert'; +import typeOf from '../src/lib/util/typeOf'; + +describe('Util', () => { + it('should validate different typeOf', () => { + assert.strictEqual(typeOf([]), 'array'); + assert.strictEqual(typeOf(null), 'null'); + assert.strictEqual(typeOf({}), 'object'); + assert.strictEqual(typeOf(new Date()), 'date'); + assert.strictEqual(typeOf('ezkemboi'), 'string'); + assert.strictEqual(typeOf(String('kemboi')), 'string'); + assert.strictEqual(typeOf(undefined), 'undefined'); + assert.strictEqual(typeOf(2021), 'number'); + assert.notStrictEqual(typeOf([]), 'object'); + }); +});