Created
September 18, 2012 12:23
-
-
Save cowboy/3742823 to your computer and use it in GitHub Desktop.
JavaScript: isPrimitive
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 isPrimitive = function(val) { | |
return val !== function() { return this; }.call(val); | |
}; |
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
'use strict'; | |
var isPrimitive = function(val) { | |
return val == null || /^[sbn]/.test(typeof val); | |
}; |
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 assert = require('assert'); | |
assert.ok(isPrimitive(null)); | |
assert.ok(isPrimitive(undefined)); | |
assert.ok(isPrimitive(1)); | |
assert.ok(isPrimitive('foo')); | |
assert.ok(isPrimitive(true)); | |
assert.ok(isPrimitive(false)); | |
assert.ok(isPrimitive(NaN)); | |
assert.ok(isPrimitive(Infinity)); | |
assert.equal(isPrimitive({}), false); | |
assert.equal(isPrimitive([]), false); | |
assert.equal(isPrimitive(/./), false); | |
assert.equal(isPrimitive(global), false); | |
assert.equal(isPrimitive(function() {}), false); | |
assert.equal(isPrimitive(new function() {}), false); | |
assert.equal(isPrimitive(new Number), false); | |
assert.equal(isPrimitive(new String), false); | |
assert.equal(isPrimitive(new Boolean), false); | |
assert.equal(isPrimitive(new Date), false); | |
assert.equal(isPrimitive(new Error), false); | |
assert.equal(isPrimitive(Object.create(null)), false); | |
3 |
RegExp is represented via /./
function isPrimitive(val) {
return val !== Object(val);
}
function isPrimitive(val) {
return !Object.prototype.isPrototypeOf(val);
}
@AutoSponge, your second version of isPrimitive
fails on objects created via Object.create(null, ...
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Regexp?