Last active
August 29, 2015 13:56
-
-
Save husa/8976538 to your computer and use it in GitHub Desktop.
get proper type of any value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var toString = Object.prototype.toString, | |
regexp = /\[object (.*?)\]/; | |
function type(o) { | |
var match = toString.call(o).match(regexp); | |
return match[1].toLowerCase(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type = (o) -> Object::toString.call(o).match(/\[object (.*?)\]/)[1].toLowerCase() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function type(o) {return Object.prototype.toString.call(o).match(/\[object (.*?)\]/)[1].toLowerCase();} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe '::type', -> | |
it 'should always return string', -> | |
expect(type()).toBeString() | |
expect(type(10)).toBeString() | |
it 'should work as "typeof" for basic types', -> | |
expect(type(1)).toBe 'number' | |
expect(type(1.1)).toBe 'number' | |
expect(type(false)).toBe 'boolean' | |
expect(type('')).toBe 'string' | |
expect(type({})).toBe 'object' | |
expect(type(->)).toBe 'function' | |
it 'should return "array" for []', -> | |
expect(type([])).toBe 'array' | |
it 'should return "nan" for NaN', -> | |
expect(type(NaN)).toBe 'nan' | |
it 'should return "regexp" for RegExp', -> | |
expect(type(/a/)).toBe 'regexp' | |
it 'should work with constructors', -> | |
expect(type(new Number(1))).toBe 'number' | |
expect(type(new Number(1.1))).toBe 'number' | |
expect(type(new Boolean(false))).toBe 'boolean' | |
expect(type(new String(''))).toBe 'string' | |
expect(type(new Object())).toBe 'object' | |
expect(type(new Function())).toBe 'function' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment