Skip to content

Instantly share code, notes, and snippets.

@husa
Last active August 29, 2015 13:56
Show Gist options
  • Save husa/8976538 to your computer and use it in GitHub Desktop.
Save husa/8976538 to your computer and use it in GitHub Desktop.
get proper type of any value
var toString = Object.prototype.toString,
regexp = /\[object (.*?)\]/;
function type(o) {
var match = toString.call(o).match(regexp);
return match[1].toLowerCase();
}
type = (o) -> Object::toString.call(o).match(/\[object (.*?)\]/)[1].toLowerCase()
function type(o) {return Object.prototype.toString.call(o).match(/\[object (.*?)\]/)[1].toLowerCase();}
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