using jQuery.type for typeOf

This commit is contained in:
AJ ONeal 2010-11-30 01:59:29 -07:00
parent c8b6995501
commit a2e251141f
4 changed files with 47 additions and 15 deletions

View File

@ -12,9 +12,10 @@ This works in both the Browser and SSJS.
Notes
----
This uses the ["Flanagan / Miller device"](http://groups.google.com/group/nodejs/msg/0670a986a2906aeb) rather than the Crockford's original.
`typeOf` is taken from `jQuery.type`, which is more accurate than Crockford's original and even simpler
than the ["Flanagan / Miller device"](http://groups.google.com/group/nodejs/msg/0670a986a2906aeb).
There is [a more specific typeof()](http://rolandog.com/archives/2007/01/18/typeof-a-more-specific-typeof/) implementation worthy of consideration.
There is [a more specific typeof()](http://rolandog.com/archives/2007/01/18/typeof-a-more-specific-typeof/) implementation also worthy of consideration.
Globals
====

View File

@ -1,18 +1,18 @@
/*jslint onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true */
"use strict";
(function () {
function typeOf(value) {
var s = typeof value;
if (s === 'object') {
if (value) {
if ((/array/i).test(({}).toString.call(value))) {
s = 'array';
}
} else {
s = 'null';
}
}
return s;
var classes = "Boolean Number String Function Array Date RegExp Object".split(" "),
i,
name,
class2type = {};
for (i in classes) {
name = classes[i];
class2type["[object " + name + "]"] = name.toLowerCase();
}
function typeOf(obj) {
return (null === obj || undefined === obj) ? String(obj) : class2type[Object.prototype.toString.call(obj)] || "object";
}
function isEmpty(o) {

View File

@ -24,7 +24,7 @@
// Expected: 3
// Node/V8/FF: 0
console.log(typeOf(b));
// Expected: Object
// Expected: Object (with Flanagan / Miller device or jQuery's type)
// Node/V8/FF: array (with Crockford's original)

31
tests/types.js Normal file
View File

@ -0,0 +1,31 @@
(function () {
require('../lib/remedial');
var n = null,
u;
if (
'object' === typeOf(Object.create([])) &&
'object' === typeOf(Object.create(function () {})) &&
'array' === typeOf([]) &&
'string' === typeOf('') &&
'regexp' === typeOf(/ /) &&
'number' === typeOf(0) &&
'function' === typeOf(function () {}) &&
'function' === typeOf((function () {
var a = function () {};
a.foo = 'bar';
return a;
}())) &&
'boolean' === typeOf(true) &&
'boolean' === typeOf(false) &&
'date' === typeOf(new Date()) &&
'undefined' === typeOf(u) &&
'undefined' === typeOf(undefined) &&
'null' === typeOf(n) &&
'object' === typeOf({})
) {
console.log('passed type detections')
} else {
console.log('failed type detections')
}
}());