From: Ben Noordhuis Date: Wed, 24 Jul 2013 16:03:53 +0000 (+0200) Subject: lib: macro-ify type checks X-Git-Tag: v0.11.5~73 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=0330bdf5195eb77f04c26a09a8bd2088a261fe53;p=platform%2Fupstream%2Fnodejs.git lib: macro-ify type checks Increases the grep factor. Makes it easier to harmonize type checks across the code base. --- diff --git a/lib/_debugger.js b/lib/_debugger.js index 10096b5..993fcba 100644 --- a/lib/_debugger.js +++ b/lib/_debugger.js @@ -182,7 +182,7 @@ exports.Client = Client; Client.prototype._addHandle = function(desc) { - if (typeof desc != 'object' || typeof desc.handle != 'number') { + if (!IS_OBJECT(desc) || !IS_NUMBER(desc.handle)) { return; } @@ -296,7 +296,7 @@ Client.prototype.reqLookup = function(refs, cb) { this.req(req, function(err, res) { if (err) return cb(err); for (var ref in res) { - if (typeof res[ref] == 'object') { + if (IS_OBJECT(res[ref])) { self._addHandle(res[ref]); } } @@ -559,8 +559,7 @@ Client.prototype.mirrorObject = function(handle, depth, cb) { } - if (Array.isArray(mirror) && - typeof prop.name != 'number') { + if (IS_ARRAY(mirror) && !IS_NUMBER(prop.name)) { // Skip the 'length' property. return; } @@ -593,7 +592,7 @@ Client.prototype.mirrorObject = function(handle, depth, cb) { val = function() {}; } else if (handle.type === 'null') { val = null; - } else if (handle.value !== undefined) { + } else if (!IS_UNDEFINED(handle.value)) { val = handle.value; } else if (handle.type === 'undefined') { val = undefined; @@ -892,7 +891,7 @@ Interface.prototype.print = function(text, oneline) { if (this.killed) return; this.clearline(); - this.stdout.write(typeof text === 'string' ? text : util.inspect(text)); + this.stdout.write(IS_STRING(text) ? text : util.inspect(text)); if (oneline !== true) { this.stdout.write('\n'); @@ -1214,7 +1213,7 @@ Interface.prototype.scripts = function() { this.pause(); for (var id in client.scripts) { var script = client.scripts[id]; - if (typeof script == 'object' && script.name) { + if (IS_OBJECT(script) && script.name) { if (displayNatives || script.name == client.currentScript || !script.isNative) { @@ -1351,13 +1350,13 @@ Interface.prototype.setBreakpoint = function(script, line, ambiguous; // setBreakpoint() should insert breakpoint on current line - if (script === undefined) { + if (IS_UNDEFINED(script)) { script = this.client.currentScript; line = this.client.currentSourceLine + 1; } // setBreakpoint(line-number) should insert breakpoint in current script - if (line === undefined && typeof script === 'number') { + if (IS_UNDEFINED(line) && IS_NUMBER(script)) { line = script; script = this.client.currentScript; } @@ -1452,7 +1451,7 @@ Interface.prototype.clearBreakpoint = function(script, line) { if (bp.scriptId === script || bp.scriptReq === script || (bp.script && bp.script.indexOf(script) !== -1)) { - if (index !== undefined) { + if (!IS_UNDEFINED(index)) { ambiguous = true; } if (bp.line === line) { @@ -1465,7 +1464,7 @@ Interface.prototype.clearBreakpoint = function(script, line) { if (ambiguous) return this.error('Script name is ambiguous'); - if (breakpoint === undefined) { + if (IS_UNDEFINED(breakpoint)) { return this.error('Script : ' + script + ' not found'); } diff --git a/lib/_http_agent.js b/lib/_http_agent.js index 07e8f4c..500ddb0 100644 --- a/lib/_http_agent.js +++ b/lib/_http_agent.js @@ -246,7 +246,7 @@ Agent.prototype.destroy = function() { }; Agent.prototype.request = function(options, cb) { - if (typeof options === 'string') { + if (IS_STRING(options)) { options = url.parse(options); } // don't try to do dns lookups of foo.com:8080, just foo.com diff --git a/lib/_http_client.js b/lib/_http_client.js index 2af127c..ca82bf7 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -44,14 +44,14 @@ function ClientRequest(options, cb) { var self = this; OutgoingMessage.call(self); - self.agent = options.agent === undefined ? globalAgent : options.agent; + self.agent = IS_UNDEFINED(options.agent) ? globalAgent : options.agent; var defaultPort = options.defaultPort || 80; var port = options.port || defaultPort; var host = options.hostname || options.host || 'localhost'; - if (options.setHost === undefined) { + if (IS_UNDEFINED(options.setHost)) { var setHost = true; } @@ -63,7 +63,7 @@ function ClientRequest(options, cb) { self.once('response', cb); } - if (!Array.isArray(options.headers)) { + if (!IS_ARRAY(options.headers)) { if (options.headers) { var keys = Object.keys(options.headers); for (var i = 0, l = keys.length; i < l; i++) { @@ -92,7 +92,7 @@ function ClientRequest(options, cb) { self.useChunkedEncodingByDefault = true; } - if (Array.isArray(options.headers)) { + if (IS_ARRAY(options.headers)) { self._storeHeader(self.method + ' ' + self.path + ' HTTP/1.1\r\n', options.headers); } else if (self.getHeader('expect')) { @@ -413,7 +413,7 @@ ClientRequest.prototype.onSocket = function(socket) { httpSocketSetup(socket); // Propagate headers limit from request object to parser - if (typeof req.maxHeadersCount === 'number') { + if (IS_NUMBER(req.maxHeadersCount)) { parser.maxHeaderPairs = req.maxHeadersCount << 1; } else { // Set default value because parser may be reused from FreeList diff --git a/lib/_http_incoming.js b/lib/_http_incoming.js index c089ec9..f11d098 100644 --- a/lib/_http_incoming.js +++ b/lib/_http_incoming.js @@ -125,7 +125,7 @@ IncomingMessage.prototype._addHeaderLine = function(field, value) { switch (field) { // Array headers: case 'set-cookie': - if (dest[field] !== undefined) { + if (!IS_UNDEFINED(dest[field])) { dest[field].push(value); } else { dest[field] = [value]; @@ -145,7 +145,7 @@ IncomingMessage.prototype._addHeaderLine = function(field, value) { case 'proxy-authenticate': case 'sec-websocket-extensions': case 'sec-websocket-protocol': - if (dest[field] !== undefined) { + if (!IS_UNDEFINED(dest[field])) { dest[field] += ', ' + value; } else { dest[field] = value; @@ -156,14 +156,14 @@ IncomingMessage.prototype._addHeaderLine = function(field, value) { default: if (field.slice(0, 2) == 'x-') { // except for x- - if (dest[field] !== undefined) { + if (!IS_UNDEFINED(dest[field])) { dest[field] += ', ' + value; } else { dest[field] = value; } } else { // drop duplicates - if (dest[field] === undefined) dest[field] = value; + if (IS_UNDEFINED(dest[field])) dest[field] = value; } break; } diff --git a/lib/_http_outgoing.js b/lib/_http_outgoing.js index 397b430..fd4681f 100644 --- a/lib/_http_outgoing.js +++ b/lib/_http_outgoing.js @@ -115,7 +115,7 @@ OutgoingMessage.prototype._send = function(data, encoding) { // the same packet. Future versions of Node are going to take care of // this at a lower level and in a more general way. if (!this._headerSent) { - if (typeof data === 'string') { + if (IS_STRING(data)) { data = this._header + data; } else { this.output.unshift(this._header); @@ -166,7 +166,7 @@ OutgoingMessage.prototype._buffer = function(data, encoding) { var length = this.output.length; - if (length === 0 || typeof data != 'string') { + if (length === 0 || !IS_STRING(data)) { this.output.push(data); this.outputEncodings.push(encoding); return false; @@ -205,7 +205,7 @@ OutgoingMessage.prototype._storeHeader = function(firstLine, headers) { if (headers) { var keys = Object.keys(headers); - var isArray = (Array.isArray(headers)); + var isArray = IS_ARRAY(headers); var field, value; for (var i = 0, l = keys.length; i < l; i++) { @@ -218,7 +218,7 @@ OutgoingMessage.prototype._storeHeader = function(firstLine, headers) { value = headers[key]; } - if (Array.isArray(value)) { + if (IS_ARRAY(value)) { for (var j = 0; j < value.length; j++) { storeHeader(this, state, field, value[j]); } @@ -401,7 +401,7 @@ OutgoingMessage.prototype.write = function(chunk, encoding) { return true; } - if (typeof chunk !== 'string' && !Buffer.isBuffer(chunk)) { + if (!IS_STRING(chunk) && !IS_BUFFER(chunk)) { throw new TypeError('first argument must be a string or Buffer'); } @@ -412,7 +412,7 @@ OutgoingMessage.prototype.write = function(chunk, encoding) { var len, ret; if (this.chunkedEncoding) { - if (typeof(chunk) === 'string' && + if (IS_STRING(chunk) && encoding !== 'hex' && encoding !== 'base64' && encoding !== 'binary') { @@ -444,7 +444,7 @@ OutgoingMessage.prototype.write = function(chunk, encoding) { OutgoingMessage.prototype.addTrailers = function(headers) { this._trailer = ''; var keys = Object.keys(headers); - var isArray = (Array.isArray(headers)); + var isArray = IS_ARRAY(headers); var field, value; for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; @@ -466,7 +466,7 @@ var crlf_buf = new Buffer('\r\n'); OutgoingMessage.prototype.end = function(data, encoding) { - if (data && typeof data !== 'string' && !Buffer.isBuffer(data)) { + if (data && !IS_STRING(data) && !IS_BUFFER(data)) { throw new TypeError('first argument must be a string or Buffer'); } diff --git a/lib/_http_server.js b/lib/_http_server.js index f6cfa35..4c7f92d 100644 --- a/lib/_http_server.js +++ b/lib/_http_server.js @@ -173,7 +173,7 @@ ServerResponse.prototype._implicitHeader = function() { ServerResponse.prototype.writeHead = function(statusCode) { var reasonPhrase, headers, headerIndex; - if (typeof arguments[1] == 'string') { + if (IS_STRING(arguments[1])) { reasonPhrase = arguments[1]; headerIndex = 2; } else { @@ -188,13 +188,13 @@ ServerResponse.prototype.writeHead = function(statusCode) { // Slow-case: when progressive API and header fields are passed. headers = this._renderHeaders(); - if (Array.isArray(obj)) { + if (IS_ARRAY(obj)) { // handle array case // TODO: remove when array is no longer accepted var field; for (var i = 0, len = obj.length; i < len; ++i) { field = obj[i][0]; - if (headers[field] !== undefined) { + if (!IS_UNDEFINED(headers[field])) { obj.push([field, headers[field]]); } } @@ -332,7 +332,7 @@ function connectionListener(socket) { parser.incoming = null; // Propagate headers limit from server instance to parser - if (typeof this.maxHeadersCount === 'number') { + if (IS_NUMBER(this.maxHeadersCount)) { parser.maxHeaderPairs = this.maxHeadersCount << 1; } else { // Set default value because parser may be reused from FreeList @@ -442,7 +442,7 @@ function connectionListener(socket) { } }); - if (req.headers.expect !== undefined && + if (!IS_UNDEFINED(req.headers.expect) && (req.httpVersionMajor == 1 && req.httpVersionMinor == 1) && continueExpression.test(req.headers['expect'])) { res._expect_continue = true; diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js index c6f31bc..0b5af41 100644 --- a/lib/_stream_readable.js +++ b/lib/_stream_readable.js @@ -117,7 +117,7 @@ function Readable(options) { Readable.prototype.push = function(chunk, encoding) { var state = this._readableState; - if (typeof chunk === 'string' && !state.objectMode) { + if (IS_STRING(chunk) && !state.objectMode) { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { chunk = new Buffer(chunk, encoding); @@ -138,7 +138,7 @@ function readableAddChunk(stream, state, chunk, encoding, addToFront) { var er = chunkInvalid(state, chunk); if (er) { stream.emit('error', er); - } else if (chunk === null || chunk === undefined) { + } else if (IS_NULL_OR_UNDEFINED(chunk)) { state.reading = false; if (!state.ended) onEofChunk(stream, state); @@ -219,7 +219,7 @@ function howMuchToRead(n, state) { if (state.objectMode) return n === 0 ? 0 : 1; - if (isNaN(n) || n === null) { + if (isNaN(n) || IS_NULL(n)) { // only flow one buffer at a time if (state.flowing && state.buffer.length) return state.buffer[0].length; @@ -256,7 +256,7 @@ Readable.prototype.read = function(n) { state.calledRead = true; var nOrig = n; - if (typeof n !== 'number' || n > 0) + if (!IS_NUMBER(n) || n > 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we @@ -345,7 +345,7 @@ Readable.prototype.read = function(n) { else ret = null; - if (ret === null) { + if (IS_NULL(ret)) { state.needReadable = true; n = 0; } @@ -363,17 +363,16 @@ Readable.prototype.read = function(n) { if (state.ended && !state.endEmitted && state.length === 0) endReadable(this); - if (ret !== null) + if (!IS_NULL(ret)) this.emit('data', ret); return ret; }; function chunkInvalid(state, chunk) { var er = null; - if (!Buffer.isBuffer(chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && + if (!IS_BUFFER(chunk) && + !IS_STRING(chunk) && + !IS_NULL_OR_UNDEFINED(chunk) && !state.objectMode && !er) { er = new TypeError('Invalid non-string/buffer chunk'); @@ -775,8 +774,7 @@ Readable.prototype.wrap = function(stream) { // proxy all the other methods. // important when wrapping filters and duplexes. for (var i in stream) { - if (typeof stream[i] === 'function' && - typeof this[i] === 'undefined') { + if (IS_FUNCTION(stream[i]) && IS_UNDEFINED(this[i])) { this[i] = function(method) { return function() { return stream[method].apply(stream, arguments); }}(i); diff --git a/lib/_stream_transform.js b/lib/_stream_transform.js index f246ef7..735f2cf 100644 --- a/lib/_stream_transform.js +++ b/lib/_stream_transform.js @@ -92,7 +92,7 @@ function afterTransform(stream, er, data) { ts.writechunk = null; ts.writecb = null; - if (data !== null && data !== undefined) + if (!IS_NULL_OR_UNDEFINED(data)) stream.push(data); if (cb) @@ -126,7 +126,7 @@ function Transform(options) { this._readableState.sync = false; this.once('prefinish', function() { - if ('function' === typeof this._flush) + if (IS_FUNCTION(this._flush)) this._flush(function(er) { done(stream, er); }); @@ -174,7 +174,7 @@ Transform.prototype._write = function(chunk, encoding, cb) { Transform.prototype._read = function(n) { var ts = this._transformState; - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + if (!IS_NULL(ts.writechunk) && ts.writecb && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js index cada467..a6b02f6 100644 --- a/lib/_stream_writable.js +++ b/lib/_stream_writable.js @@ -153,10 +153,9 @@ function writeAfterEnd(stream, state, cb) { // how many bytes or characters. function validChunk(stream, state, chunk, cb) { var valid = true; - if (!Buffer.isBuffer(chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && + if (!IS_BUFFER(chunk) && + !IS_STRING(chunk) && + !IS_NULL_OR_UNDEFINED(chunk) && !state.objectMode) { var er = new TypeError('Invalid non-string/buffer chunk'); stream.emit('error', er); @@ -172,17 +171,17 @@ Writable.prototype.write = function(chunk, encoding, cb) { var state = this._writableState; var ret = false; - if (typeof encoding === 'function') { + if (IS_FUNCTION(encoding)) { cb = encoding; encoding = null; } - if (Buffer.isBuffer(chunk)) + if (IS_BUFFER(chunk)) encoding = 'buffer'; else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') + if (!IS_FUNCTION(cb)) cb = function() {}; if (state.ended) @@ -217,9 +216,7 @@ Writable.prototype.uncork = function() { }; function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && - state.decodeStrings !== false && - typeof chunk === 'string') { + if (!state.objectMode && state.decodeStrings !== false && IS_STRING(chunk)) { chunk = new Buffer(chunk, encoding); } return chunk; @@ -230,7 +227,7 @@ function decodeChunk(state, chunk, encoding) { // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, chunk, encoding, cb) { chunk = decodeChunk(state, chunk, encoding); - if (Buffer.isBuffer(chunk)) + if (IS_BUFFER(chunk)) encoding = 'buffer'; var len = state.objectMode ? 1 : chunk.length; @@ -391,16 +388,16 @@ Writable.prototype._writev = null; Writable.prototype.end = function(chunk, encoding, cb) { var state = this._writableState; - if (typeof chunk === 'function') { + if (IS_FUNCTION(chunk)) { cb = chunk; chunk = null; encoding = null; - } else if (typeof encoding === 'function') { + } else if (IS_FUNCTION(encoding)) { cb = encoding; encoding = null; } - if (typeof chunk !== 'undefined' && chunk !== null) + if (!IS_NULL_OR_UNDEFINED(chunk)) this.write(chunk, encoding); // .end() fully uncorks diff --git a/lib/_tls_legacy.js b/lib/_tls_legacy.js index 4acabe3..6c85251 100644 --- a/lib/_tls_legacy.js +++ b/lib/_tls_legacy.js @@ -36,7 +36,7 @@ SlabBuffer.prototype.use = function use(context, fn, size) { var actualSize = this.remaining; - if (size !== null) actualSize = Math.min(size, actualSize); + if (!IS_NULL(size)) actualSize = Math.min(size, actualSize); var bytes = fn.call(context, this.pool, this.offset, actualSize); if (bytes > 0) { @@ -72,7 +72,7 @@ function CryptoStream(pair, options) { this._finished = false; this._opposite = null; - if (slabBuffer === null) slabBuffer = new SlabBuffer(); + if (IS_NULL(slabBuffer)) slabBuffer = new SlabBuffer(); this._buffer = slabBuffer; this.once('finish', onCryptoStreamFinish); @@ -144,7 +144,7 @@ CryptoStream.prototype.init = function init() { CryptoStream.prototype._write = function write(data, encoding, cb) { - assert(this._pending === null); + assert(IS_NULL(this._pending)); // Black-hole data if (!this.pair.ssl) return cb(null); @@ -191,7 +191,7 @@ CryptoStream.prototype._write = function write(data, encoding, cb) { // Invoke callback only when all data read from opposite stream if (this._opposite._halfRead) { - assert(this._sslOutCb === null); + assert(IS_NULL(this._sslOutCb)); this._sslOutCb = cb; } else { cb(null); @@ -285,8 +285,8 @@ CryptoStream.prototype._read = function read(size) { } // Try writing pending data - if (this._pending !== null) this._writePending(); - if (this._opposite._pending !== null) this._opposite._writePending(); + if (!IS_NULL(this._pending)) this._writePending(); + if (!IS_NULL(this._opposite._pending)) this._opposite._writePending(); if (bytesRead === 0) { // EOF when cleartext has finished and we have nothing to read @@ -405,7 +405,7 @@ CryptoStream.prototype.end = function(chunk, encoding) { } // Write pending data first - if (this._pending !== null) this._writePending(); + if (!IS_NULL(this._pending)) this._writePending(); this.writable = false; diff --git a/lib/_tls_wrap.js b/lib/_tls_wrap.js index c6b0a3c..bdba9cf 100644 --- a/lib/_tls_wrap.js +++ b/lib/_tls_wrap.js @@ -207,7 +207,7 @@ TLSSocket.prototype.setServername = function(name) { }; TLSSocket.prototype.setSession = function(session) { - if (typeof session === 'string') + if (IS_STRING(session)) session = new Buffer(session, 'binary'); this.ssl.setSession(session); }; @@ -319,10 +319,10 @@ TLSSocket.prototype.getCipher = function(err) { // function Server(/* [options], listener */) { var options, listener; - if (typeof arguments[0] == 'object') { + if (IS_OBJECT(arguments[0])) { options = arguments[0]; listener = arguments[1]; - } else if (typeof arguments[0] == 'function') { + } else if (IS_FUNCTION(arguments[0])) { options = {}; listener = arguments[0]; } @@ -355,7 +355,7 @@ function Server(/* [options], listener */) { var timeout = options.handshakeTimeout || (120 * 1000); - if (typeof timeout !== 'number') { + if (!IS_NUMBER(timeout)) { throw new TypeError('handshakeTimeout must be a number'); } @@ -423,13 +423,13 @@ exports.createServer = function(options, listener) { Server.prototype.setOptions = function(options) { - if (typeof options.requestCert == 'boolean') { + if (IS_BOOLEAN(options.requestCert)) { this.requestCert = options.requestCert; } else { this.requestCert = false; } - if (typeof options.rejectUnauthorized == 'boolean') { + if (IS_BOOLEAN(options.rejectUnauthorized)) { this.rejectUnauthorized = options.rejectUnauthorized; } else { this.rejectUnauthorized = false; @@ -481,7 +481,7 @@ Server.prototype.SNICallback = function(servername) { var ctx; this._contexts.some(function(elem) { - if (servername.match(elem[0]) !== null) { + if (!IS_NULL(servername.match(elem[0]))) { ctx = elem[1]; return true; } @@ -510,9 +510,9 @@ function normalizeConnectArgs(listArgs) { var options = args[0]; var cb = args[1]; - if (typeof listArgs[1] === 'object') { + if (IS_OBJECT(listArgs[1])) { options = util._extend(options, listArgs[1]); - } else if (typeof listArgs[2] === 'object') { + } else if (IS_OBJECT(listArgs[2])) { options = util._extend(options, listArgs[2]); } diff --git a/lib/assert.js b/lib/assert.js index 11fef45..fcd4886 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -51,20 +51,20 @@ assert.AssertionError = function AssertionError(options) { util.inherits(assert.AssertionError, Error); function replacer(key, value) { - if (value === undefined) { + if (IS_UNDEFINED(value)) { return '' + value; } - if (typeof value === 'number' && (isNaN(value) || !isFinite(value))) { + if (IS_NUMBER(value) && (isNaN(value) || !isFinite(value))) { return value.toString(); } - if (typeof value === 'function' || value instanceof RegExp) { + if (IS_FUNCTION(value) || IS_REGEXP(value)) { return value.toString(); } return value; } function truncate(s, n) { - if (typeof s == 'string') { + if (IS_STRING(s)) { return s.length < n ? s : s.slice(0, n); } else { return s; @@ -144,7 +144,7 @@ function _deepEqual(actual, expected) { if (actual === expected) { return true; - } else if (Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) { + } else if (IS_BUFFER(actual) && IS_BUFFER(expected)) { if (actual.length != expected.length) return false; for (var i = 0; i < actual.length; i++) { @@ -155,13 +155,13 @@ function _deepEqual(actual, expected) { // 7.2. If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. - } else if (actual instanceof Date && expected instanceof Date) { + } else if (IS_DATE(actual) && IS_DATE(expected)) { return actual.getTime() === expected.getTime(); // 7.3 If the expected value is a RegExp object, the actual value is // equivalent if it is also a RegExp object with the same source and // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (actual instanceof RegExp && expected instanceof RegExp) { + } else if (IS_REGEXP(actual) && IS_REGEXP(expected)) { return actual.source === expected.source && actual.global === expected.global && actual.multiline === expected.multiline && @@ -170,7 +170,7 @@ function _deepEqual(actual, expected) { // 7.4. Other pairs that do not both pass typeof value == 'object', // equivalence is determined by ==. - } else if (typeof actual != 'object' && typeof expected != 'object') { + } else if (!IS_OBJECT(actual) && !IS_OBJECT(expected)) { return actual == expected; // 7.5 For all other Object pairs, including Array objects, equivalence is @@ -184,16 +184,12 @@ function _deepEqual(actual, expected) { } } -function isUndefinedOrNull(value) { - return value === null || value === undefined; -} - function isArguments(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; } function objEquiv(a, b) { - if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) + if (IS_NULL_OR_UNDEFINED(a) || IS_NULL_OR_UNDEFINED(b)) return false; // an identical 'prototype' property. if (a.prototype !== b.prototype) return false; @@ -281,7 +277,7 @@ function expectedException(actual, expected) { function _throws(shouldThrow, block, expected, message) { var actual; - if (typeof expected === 'string') { + if (IS_STRING(expected)) { message = expected; expected = null; } diff --git a/lib/buffer.js b/lib/buffer.js index deb946f..83f23e9 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -48,34 +48,24 @@ function createPool() { function Buffer(subject, encoding) { - if (!(this instanceof Buffer)) + if (!IS_BUFFER(this)) return new Buffer(subject, encoding); - var type = typeof subject; - - switch (type) { - case 'number': - this.length = subject > 0 ? Math.floor(subject) : 0; - break; - - case 'string': - this.length = Buffer.byteLength(subject, encoding = encoding || 'utf8'); - break; - - case 'object': - this.length = +subject.length > 0 ? Math.floor(+subject.length) : 0; - break; - + if (IS_NUMBER(subject)) + this.length = subject > 0 ? Math.floor(subject) : 0; + else if (IS_STRING(subject)) + this.length = Buffer.byteLength(subject, encoding = encoding || 'utf8'); + else if (IS_OBJECT(subject)) + this.length = +subject.length > 0 ? Math.floor(+subject.length) : 0; + else if (IS_UNDEFINED(subject)) { // undef first arg returns unallocated buffer, also assumes length passed. // this is a stop-gap for now while look for better architecture. // for internal use only. - case 'undefined': - this.length = encoding; - return; - - default: - throw new TypeError('must start with number, buffer, array or string'); + this.length = encoding; + return; } + else + throw new TypeError('must start with number, buffer, array or string'); if (this.length > kMaxLength) throw new RangeError('length > kMaxLength'); @@ -92,14 +82,14 @@ function Buffer(subject, encoding) { alloc(this, this.length); } - if (type !== 'number') { - if (type === 'string') { + if (!IS_NUMBER(subject)) { + if (IS_STRING(subject)) { // FIXME: the number of bytes hasn't changed, so why change the length? this.length = this.write(subject, 0, encoding); } else { - if (subject instanceof Buffer) + if (IS_BUFFER(subject)) this.copy(subject, 0, 0, this.length); - else if (typeof subject.length === 'number' || Array.isArray(subject)) + else if (IS_NUMBER(subject.length) || IS_ARRAY(subject)) for (var i = 0; i < this.length; i++) this[i] = subject[i]; } @@ -118,7 +108,7 @@ function SlowBuffer(length) { // Static methods Buffer.isBuffer = function isBuffer(b) { - return b instanceof Buffer; + return IS_BUFFER(b); }; @@ -144,10 +134,10 @@ Buffer.isEncoding = function(encoding) { Buffer.concat = function(list, length) { - if (!Array.isArray(list)) + if (!IS_ARRAY(list)) throw new TypeError('Usage: Buffer.concat(list[, length])'); - if (length === undefined) { + if (IS_UNDEFINED(length)) { length = 0; for (var i = 0; i < list.length; i++) length += list[i].length; @@ -184,7 +174,7 @@ Buffer.prototype.toString = function(encoding, start, end) { encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8'; start = ~~start; - end = (end === undefined) ? this.length : ~~end; + end = IS_UNDEFINED(end) ? this.length : ~~end; if (start < 0) start = 0; if (end > this.length) end = this.length; @@ -253,7 +243,7 @@ var writeMsg = '.write(string, encoding, offset, length) is deprecated.' + ' Use write(string, offset, length, encoding) instead.'; Buffer.prototype.write = function(string, offset, length, encoding) { // allow write(string, encoding) - if (typeof offset === 'string' && length === undefined) { + if (IS_STRING(offset) && IS_UNDEFINED(length)) { encoding = offset; offset = 0; @@ -286,7 +276,7 @@ Buffer.prototype.write = function(string, offset, length, encoding) { } var remaining = this.length - offset; - if (length === undefined || length > remaining) + if (IS_UNDEFINED(length) || length > remaining) length = remaining; encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8'; @@ -346,7 +336,7 @@ Buffer.prototype.toJSON = function() { Buffer.prototype.slice = function(start, end) { var len = this.length; start = ~~start; - end = (end === undefined) ? len : ~~end; + end = IS_UNDEFINED(end) ? len : ~~end; if (start < 0) { start += len; @@ -371,7 +361,7 @@ Buffer.prototype.slice = function(start, end) { sliceOnto(this, buf, start, end); buf.length = end - start; if (buf.length > 0) - buf.parent = this.parent === undefined ? this : this.parent; + buf.parent = IS_UNDEFINED(this.parent) ? this : this.parent; return buf; }; diff --git a/lib/child_process.js b/lib/child_process.js index 1ca3d8c..cfb40f0 100644 --- a/lib/child_process.js +++ b/lib/child_process.js @@ -39,7 +39,7 @@ function handleWrapGetter(name, callback) { Object.defineProperty(handleWraps, name, { get: function() { - if (cons !== undefined) return cons; + if (!IS_UNDEFINED(cons)) return cons; return cons = callback(); } }); @@ -312,9 +312,9 @@ function getSocketList(type, slave, key) { var INTERNAL_PREFIX = 'NODE_'; function handleMessage(target, message, handle) { var eventName = 'message'; - if (message !== null && - typeof message === 'object' && - typeof message.cmd === 'string' && + if (!IS_NULL(message) && + IS_OBJECT(message) && + IS_STRING(message.cmd) && message.cmd.length > INTERNAL_PREFIX.length && message.cmd.slice(0, INTERNAL_PREFIX.length) === INTERNAL_PREFIX) { eventName = 'internalMessage'; @@ -370,7 +370,7 @@ function setupChannel(target, channel) { target.on('internalMessage', function(message, handle) { // Once acknowledged - continue sending handles. if (message.cmd === 'NODE_HANDLE_ACK') { - assert(Array.isArray(target._handleQueue)); + assert(IS_ARRAY(target._handleQueue)); var queue = target._handleQueue; target._handleQueue = null; queue.forEach(function(args) { @@ -399,7 +399,7 @@ function setupChannel(target, channel) { }); target.send = function(message, handle) { - if (typeof message === 'undefined') { + if (IS_UNDEFINED(message)) { throw new TypeError('message cannot be undefined'); } @@ -512,7 +512,7 @@ exports.fork = function(modulePath /*, args, options*/) { // Get options and args arguments. var options, args, execArgv; - if (Array.isArray(arguments[1])) { + if (IS_ARRAY(arguments[1])) { args = arguments[1]; options = util._extend({}, arguments[2]); } else { @@ -557,7 +557,7 @@ exports._forkChild = function(fd) { exports.exec = function(command /*, options, callback */) { var file, args, options, callback; - if (typeof arguments[1] === 'function') { + if (IS_FUNCTION(arguments[1])) { options = undefined; callback = arguments[1]; } else { @@ -593,11 +593,11 @@ exports.execFile = function(file /* args, options, callback */) { // Parse the parameters. - if (typeof arguments[arguments.length - 1] === 'function') { + if (IS_FUNCTION(arguments[arguments.length - 1])) { callback = arguments[arguments.length - 1]; } - if (Array.isArray(arguments[1])) { + if (IS_ARRAY(arguments[1])) { args = arguments[1]; options = util._extend(options, arguments[2]); } else { @@ -835,14 +835,14 @@ ChildProcess.prototype.spawn = function(options) { stdio = options.stdio || 'pipe'; // Replace shortcut with an array - if (typeof stdio === 'string') { + if (IS_STRING(stdio)) { switch (stdio) { case 'ignore': stdio = ['ignore', 'ignore', 'ignore']; break; case 'pipe': stdio = ['pipe', 'pipe', 'pipe']; break; case 'inherit': stdio = [0, 1, 2]; break; default: throw new TypeError('Incorrect value of stdio option: ' + stdio); } - } else if (!Array.isArray(stdio)) { + } else if (!IS_ARRAY(stdio)) { throw new TypeError('Incorrect value of stdio option: ' + stdio); } @@ -864,16 +864,16 @@ ChildProcess.prototype.spawn = function(options) { } // Defaults - if (stdio === undefined || stdio === null) { + if (IS_NULL_OR_UNDEFINED(stdio)) { stdio = i < 3 ? 'pipe' : 'ignore'; } if (stdio === 'ignore') { acc.push({type: 'ignore'}); - } else if (stdio === 'pipe' || typeof stdio === 'number' && stdio < 0) { + } else if (stdio === 'pipe' || IS_NUMBER(stdio) && stdio < 0) { acc.push({type: 'pipe', handle: createPipe()}); } else if (stdio === 'ipc') { - if (ipc !== undefined) { + if (!IS_UNDEFINED(ipc)) { // Cleanup previously created pipes cleanup(); throw Error('Child process can have only one IPC pipe'); @@ -883,7 +883,7 @@ ChildProcess.prototype.spawn = function(options) { ipcFd = i; acc.push({ type: 'pipe', handle: ipc, ipc: true }); - } else if (typeof stdio === 'number' || typeof stdio.fd === 'number') { + } else if (IS_NUMBER(stdio) || IS_NUMBER(stdio.fd)) { acc.push({ type: 'fd', fd: stdio.fd || stdio }); } else if (getHandleWrapType(stdio) || getHandleWrapType(stdio.handle) || getHandleWrapType(stdio._handle)) { @@ -907,7 +907,7 @@ ChildProcess.prototype.spawn = function(options) { options.stdio = stdio; - if (ipc !== undefined) { + if (!IS_UNDEFINED(ipc)) { // Let child process know about opened IPC channel options.envPairs = options.envPairs || []; options.envPairs.push('NODE_CHANNEL_FD=' + ipcFd); @@ -952,19 +952,19 @@ ChildProcess.prototype.spawn = function(options) { } }); - this.stdin = stdio.length >= 1 && stdio[0].socket !== undefined ? + this.stdin = stdio.length >= 1 && !IS_UNDEFINED(stdio[0].socket) ? stdio[0].socket : null; - this.stdout = stdio.length >= 2 && stdio[1].socket !== undefined ? + this.stdout = stdio.length >= 2 && !IS_UNDEFINED(stdio[1].socket) ? stdio[1].socket : null; - this.stderr = stdio.length >= 3 && stdio[2].socket !== undefined ? + this.stderr = stdio.length >= 3 && !IS_UNDEFINED(stdio[2].socket) ? stdio[2].socket : null; this.stdio = stdio.map(function(stdio) { - return stdio.socket === undefined ? null : stdio.socket; + return IS_UNDEFINED(stdio.socket) ? null : stdio.socket; }); // Add .send() method and start listening for IPC data - if (ipc !== undefined) setupChannel(this, ipc); + if (!IS_UNDEFINED(ipc)) setupChannel(this, ipc); return err; }; @@ -985,7 +985,7 @@ ChildProcess.prototype.kill = function(sig) { signal = constants[sig]; } - if (signal === undefined) { + if (IS_UNDEFINED(signal)) { throw new Error('Unknown signal: ' + sig); } diff --git a/lib/cluster.js b/lib/cluster.js index b585934..6503892 100644 --- a/lib/cluster.js +++ b/lib/cluster.js @@ -68,7 +68,7 @@ function SharedHandle(key, address, port, addressType, backlog, fd) { else rval = net._createServerHandle(address, port, addressType, fd); - if (typeof rval === 'number') + if (IS_NUMBER(rval)) this.errno = rval; else this.handle = rval; @@ -135,7 +135,7 @@ RoundRobinHandle.prototype.add = function(worker, send) { self.handoff(worker); // In case there are connections pending. } - if (this.server === null) return done(); + if (IS_NULL(this.server)) return done(); // Still busy binding. this.server.once('listening', done); this.server.once('error', function(err) { @@ -166,7 +166,7 @@ RoundRobinHandle.prototype.handoff = function(worker) { return; // Worker is closing (or has closed) the server. } var handle = this.handles.shift(); - if (typeof handle === 'undefined') { + if (IS_UNDEFINED(handle)) { this.free.push(worker); // Add to ready queue again. return; } @@ -225,7 +225,7 @@ function masterInit() { 'rr': SCHED_RR }[process.env.NODE_CLUSTER_SCHED_POLICY]; - if (typeof schedulingPolicy === 'undefined') { + if (IS_UNDEFINED(schedulingPolicy)) { // FIXME Round-robin doesn't perform well on Windows right now due to the // way IOCP is wired up. Bert is going to fix that, eventually. schedulingPolicy = (process.platform === 'win32') ? SCHED_NONE : SCHED_RR; @@ -367,7 +367,7 @@ function masterInit() { message.fd]; var key = args.join(':'); var handle = handles[key]; - if (typeof handle === 'undefined') { + if (IS_UNDEFINED(handle)) { var constructor = RoundRobinHandle; // UDP is exempt from round-robin connection balancing for what should // be obvious reasons: it's connectionless. There is nothing to send to @@ -474,7 +474,7 @@ function workerInit() { delete handles[key]; return close.apply(this, arguments); }; - assert(typeof handles[key] === 'undefined'); + assert(IS_UNDEFINED(handles[key])); handles[key] = handle; cb(handle); } @@ -511,7 +511,7 @@ function workerInit() { // the ack by the master process in which we can still receive handles. // onconnection() below handles that by sending those handles back to // the master. - if (typeof key === 'undefined') return; + if (IS_UNDEFINED(key)) return; send({ act: 'close', key: key }); delete handles[key]; key = undefined; @@ -529,7 +529,7 @@ function workerInit() { if (message.sockname) { handle.getsockname = getsockname; // TCP handles only. } - assert(typeof handles[key] === 'undefined'); + assert(IS_UNDEFINED(handles[key])); handles[key] = handle; cb(handle); } @@ -539,7 +539,7 @@ function workerInit() { function onconnection(message, handle) { var key = message.key; var server = handles[key]; - var accepted = (typeof server !== 'undefined'); + var accepted = !IS_UNDEFINED(server); send({ ack: message.seq, accepted: accepted }); if (accepted) server.onconnection(0, handle); } @@ -585,7 +585,7 @@ function internal(worker, cb) { return function(message, handle) { if (message.cmd !== 'NODE_CLUSTER') return; var fn = cb; - if (typeof message.ack !== 'undefined') { + if (!IS_UNDEFINED(message.ack)) { fn = callbacks[message.ack]; delete callbacks[message.ack]; } diff --git a/lib/console.js b/lib/console.js index 66578b6..fd7722f 100644 --- a/lib/console.js +++ b/lib/console.js @@ -25,7 +25,7 @@ function Console(stdout, stderr) { if (!(this instanceof Console)) { return new Console(stdout, stderr); } - if (!stdout || typeof stdout.write !== 'function') { + if (!stdout || !IS_FUNCTION(stdout.write)) { throw new TypeError('Console expects a writable stream instance'); } if (!stderr) { diff --git a/lib/crypto.js b/lib/crypto.js index 90e139a..c450f1c 100644 --- a/lib/crypto.js +++ b/lib/crypto.js @@ -43,7 +43,7 @@ var util = require('util'); // to break them unnecessarily. function toBuf(str, encoding) { encoding = encoding || 'binary'; - if (typeof str === 'string') { + if (IS_STRING(str)) { if (encoding === 'buffer') encoding = 'binary'; str = new Buffer(str, encoding); @@ -100,7 +100,7 @@ exports.createCredentials = function(options, context) { if (options.ciphers) c.context.setCiphers(options.ciphers); if (options.ca) { - if (Array.isArray(options.ca)) { + if (IS_ARRAY(options.ca)) { for (var i = 0, len = options.ca.length; i < len; i++) { c.context.addCACert(options.ca[i]); } @@ -112,7 +112,7 @@ exports.createCredentials = function(options, context) { } if (options.crl) { - if (Array.isArray(options.crl)) { + if (IS_ARRAY(options.crl)) { for (var i = 0, len = options.crl.length; i < len; i++) { c.context.addCRL(options.crl[i]); } @@ -198,7 +198,7 @@ Hash.prototype._flush = function(callback) { Hash.prototype.update = function(data, encoding) { encoding = encoding || exports.DEFAULT_ENCODING; - if (encoding === 'buffer' && typeof data === 'string') + if (encoding === 'buffer' && IS_STRING(data)) encoding = 'binary'; this._binding.update(data, encoding); return this; @@ -539,7 +539,7 @@ DiffieHellman.prototype.setPrivateKey = function(key, encoding) { exports.pbkdf2 = function(password, salt, iterations, keylen, callback) { - if (typeof callback !== 'function') + if (!IS_FUNCTION(callback)) throw new Error('No callback provided to pbkdf2'); return pbkdf2(password, salt, iterations, keylen, callback); diff --git a/lib/dgram.js b/lib/dgram.js index 7f27998..1ac5c27 100644 --- a/lib/dgram.js +++ b/lib/dgram.js @@ -91,7 +91,7 @@ function newHandle(type) { exports._createSocketHandle = function(address, port, addressType, fd) { // Opening an existing fd is not supported for UDP handles. - assert(typeof fd !== 'number' || fd < 0); + assert(!IS_NUMBER(fd) || fd < 0); var handle = newHandle(addressType); @@ -119,7 +119,7 @@ function Socket(type, listener) { this.type = type; this.fd = null; // compatibility hack - if (typeof listener === 'function') + if (IS_FUNCTION(listener)) this.on('message', listener); } util.inherits(Socket, events.EventEmitter); @@ -165,7 +165,7 @@ Socket.prototype.bind = function(/*port, address, callback*/) { this._bindState = BIND_STATE_BINDING; - if (typeof arguments[arguments.length - 1] === 'function') + if (IS_FUNCTION(arguments[arguments.length - 1])) self.once('listening', arguments[arguments.length - 1]); var UDP = process.binding('udp_wrap').UDP; @@ -177,7 +177,7 @@ Socket.prototype.bind = function(/*port, address, callback*/) { var port = arguments[0]; var address = arguments[1]; - if (typeof address === 'function') address = ''; // a.k.a. "any address" + if (IS_FUNCTION(address)) address = ''; // a.k.a. "any address" // resolve address first self._handle.lookup(address, function(err, ip) { @@ -225,10 +225,10 @@ Socket.prototype.sendto = function(buffer, port, address, callback) { - if (typeof offset !== 'number' || typeof length !== 'number') + if (!IS_NUMBER(offset) || !IS_NUMBER(length)) throw new Error('send takes offset and length as args 2 and 3'); - if (typeof address !== 'string') + if (!IS_STRING(address)) throw new Error(this.type + ' sockets must send to port, address'); this.send(buffer, offset, length, port, address, callback); @@ -243,7 +243,7 @@ Socket.prototype.send = function(buffer, callback) { var self = this; - if (!Buffer.isBuffer(buffer)) + if (!IS_BUFFER(buffer)) throw new TypeError('First argument must be a buffer object.'); if (offset >= buffer.length) @@ -335,7 +335,7 @@ Socket.prototype.setBroadcast = function(arg) { Socket.prototype.setTTL = function(arg) { - if (typeof arg !== 'number') { + if (!IS_NUMBER(arg)) { throw new TypeError('Argument must be a number'); } @@ -349,7 +349,7 @@ Socket.prototype.setTTL = function(arg) { Socket.prototype.setMulticastTTL = function(arg) { - if (typeof arg !== 'number') { + if (!IS_NUMBER(arg)) { throw new TypeError('Argument must be a number'); } diff --git a/lib/dns.js b/lib/dns.js index 23bd758..e92b180 100644 --- a/lib/dns.js +++ b/lib/dns.js @@ -61,7 +61,7 @@ function errnoException(err, syscall) { // callback.immediately = true; // } function makeAsync(callback) { - if (typeof callback !== 'function') { + if (!IS_FUNCTION(callback)) { return callback; } return function asyncCallback() { @@ -178,7 +178,7 @@ exports.reverse = resolveMap.PTR = resolver('getHostByAddr'); exports.resolve = function(domain, type_, callback_) { var resolver, callback; - if (typeof type_ == 'string') { + if (IS_STRING(type_)) { resolver = resolveMap[type_]; callback = callback_; } else { @@ -186,7 +186,7 @@ exports.resolve = function(domain, type_, callback_) { callback = type_; } - if (typeof resolver === 'function') { + if (IS_FUNCTION(resolver)) { return resolver(domain, callback); } else { throw new Error('Unknown type "' + type_ + '"'); diff --git a/lib/domain.js b/lib/domain.js index 148d3a2..364d8c7 100644 --- a/lib/domain.js +++ b/lib/domain.js @@ -219,7 +219,7 @@ Domain.prototype.dispose = function() { // so it's quite possible that calling some of these methods // might cause additional exceptions to be thrown. endMethods.forEach(function(method) { - if (typeof m[method] === 'function') { + if (IS_FUNCTION(m[method])) { try { m[method](); } catch (er) {} diff --git a/lib/events.js b/lib/events.js index 9c2ba54..b69dc8f 100644 --- a/lib/events.js +++ b/lib/events.js @@ -49,7 +49,7 @@ EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { - if (typeof n !== 'number' || n < 0) + if (!IS_NUMBER(n) || n < 0) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; @@ -64,8 +64,7 @@ EventEmitter.prototype.emit = function(type) { // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || - (typeof this._events.error === 'object' && - !this._events.error.length)) { + (IS_OBJECT(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (this.domain) { if (!er) er = new TypeError('Uncaught, unspecified "error" event.'); @@ -84,13 +83,13 @@ EventEmitter.prototype.emit = function(type) { handler = this._events[type]; - if (typeof handler === 'undefined') + if (IS_UNDEFINED(handler)) return false; if (this.domain && this !== process) this.domain.enter(); - if (typeof handler === 'function') { + if (IS_FUNCTION(handler)) { switch (arguments.length) { // fast cases case 1: @@ -110,7 +109,7 @@ EventEmitter.prototype.emit = function(type) { args[i - 1] = arguments[i]; handler.apply(this, args); } - } else if (typeof handler === 'object') { + } else if (IS_OBJECT(handler)) { len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) @@ -131,7 +130,7 @@ EventEmitter.prototype.emit = function(type) { EventEmitter.prototype.addListener = function(type, listener) { var m; - if (typeof listener !== 'function') + if (!IS_FUNCTION(listener)) throw TypeError('listener must be a function'); if (!this._events) @@ -140,13 +139,13 @@ EventEmitter.prototype.addListener = function(type, listener) { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) - this.emit('newListener', type, typeof listener.listener === 'function' ? - listener.listener : listener); + this.emit('newListener', type, + IS_FUNCTION(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; - else if (typeof this._events[type] === 'object') + else if (IS_OBJECT(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else @@ -154,9 +153,9 @@ EventEmitter.prototype.addListener = function(type, listener) { this._events[type] = [this._events[type], listener]; // Check for listener leak - if (typeof this._events[type] === 'object' && !this._events[type].warned) { + if (IS_OBJECT(this._events[type]) && !this._events[type].warned) { var m; - if (this._maxListeners !== undefined) { + if (!IS_UNDEFINED(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; @@ -178,7 +177,7 @@ EventEmitter.prototype.addListener = function(type, listener) { EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { - if (typeof listener !== 'function') + if (!IS_FUNCTION(listener)) throw TypeError('listener must be a function'); function g() { @@ -196,7 +195,7 @@ EventEmitter.prototype.once = function(type, listener) { EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; - if (typeof listener !== 'function') + if (!IS_FUNCTION(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) @@ -207,12 +206,12 @@ EventEmitter.prototype.removeListener = function(type, listener) { position = -1; if (list === listener || - (typeof list.listener === 'function' && list.listener === listener)) { + (IS_FUNCTION(list.listener) && list.listener === listener)) { this._events[type] = undefined; if (this._events.removeListener) this.emit('removeListener', type, listener); - } else if (typeof list === 'object') { + } else if (IS_OBJECT(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { @@ -266,7 +265,7 @@ EventEmitter.prototype.removeAllListeners = function(type) { listeners = this._events[type]; - if (typeof listeners === 'function') { + if (IS_FUNCTION(listeners)) { this.removeListener(type, listeners); } else { // LIFO order @@ -282,7 +281,7 @@ EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; - else if (typeof this._events[type] === 'function') + else if (IS_FUNCTION(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); @@ -293,7 +292,7 @@ EventEmitter.listenerCount = function(emitter, type) { var ret; if (!emitter._events || !emitter._events[type]) ret = 0; - else if (typeof emitter._events[type] === 'function') + else if (IS_FUNCTION(emitter._events[type])) ret = 1; else ret = emitter._events[type].length; diff --git a/lib/fs.js b/lib/fs.js index 39d31ca..b1ca7aa 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -81,14 +81,14 @@ function rethrow() { } function maybeCallback(cb) { - return typeof cb === 'function' ? cb : rethrow(); + return IS_FUNCTION(cb) ? cb : rethrow(); } // Ensure that callbacks run in the global context. Only use this function // for callbacks that are passed to the binding layer, callbacks that are // invoked from JS already run in the proper scope. function makeCallback(cb) { - if (typeof cb !== 'function') { + if (!IS_FUNCTION(cb)) { return rethrow(); } @@ -171,13 +171,13 @@ fs.existsSync = function(path) { fs.readFile = function(path, options, callback_) { var callback = maybeCallback(arguments[arguments.length - 1]); - if (typeof options === 'function' || !options) { + if (IS_FUNCTION(options) || !options) { options = { encoding: null, flag: 'r' }; - } else if (typeof options === 'string') { + } else if (IS_STRING(options)) { options = { encoding: options, flag: 'r' }; } else if (!options) { options = { encoding: null, flag: 'r' }; - } else if (typeof options !== 'object') { + } else if (!IS_OBJECT(options)) { throw new TypeError('Bad arguments'); } @@ -260,9 +260,9 @@ fs.readFile = function(path, options, callback_) { fs.readFileSync = function(path, options) { if (!options) { options = { encoding: null, flag: 'r' }; - } else if (typeof options === 'string') { + } else if (IS_STRING(options)) { options = { encoding: options, flag: 'r' }; - } else if (typeof options !== 'object') { + } else if (!IS_OBJECT(options)) { throw new TypeError('Bad arguments'); } @@ -332,7 +332,7 @@ fs.readFileSync = function(path, options) { // Used by binding.open and friends function stringToFlags(flag) { // Only mess with strings - if (typeof flag !== 'string') { + if (!IS_STRING(flag)) { return flag; } @@ -381,16 +381,13 @@ fs.closeSync = function(fd) { }; function modeNum(m, def) { - switch (typeof m) { - case 'number': return m; - case 'string': return parseInt(m, 8); - default: - if (def) { - return modeNum(def); - } else { - return undefined; - } - } + if (IS_NUMBER(m)) + return m; + if (IS_STRING(m)) + return parseInt(m, 8); + if (def) + return modeNum(def); + return undefined; } fs.open = function(path, flags, mode, callback) { @@ -411,7 +408,7 @@ fs.openSync = function(path, flags, mode) { }; fs.read = function(fd, buffer, offset, length, position, callback) { - if (!Buffer.isBuffer(buffer)) { + if (!IS_BUFFER(buffer)) { // legacy string interface (fd, length, position, encoding, callback) var cb = arguments[4], encoding = arguments[3]; @@ -442,7 +439,7 @@ fs.read = function(fd, buffer, offset, length, position, callback) { fs.readSync = function(fd, buffer, offset, length, position) { var legacy = false; - if (!Buffer.isBuffer(buffer)) { + if (!IS_BUFFER(buffer)) { // legacy string interface (fd, length, position, encoding, callback) legacy = true; var encoding = arguments[3]; @@ -466,7 +463,7 @@ fs.readSync = function(fd, buffer, offset, length, position) { }; fs.write = function(fd, buffer, offset, length, position, callback) { - if (!Buffer.isBuffer(buffer)) { + if (!IS_BUFFER(buffer)) { // legacy string interface (fd, data, position, encoding, callback) callback = arguments[4]; position = arguments[2]; @@ -478,7 +475,7 @@ fs.write = function(fd, buffer, offset, length, position, callback) { } if (!length) { - if (typeof callback == 'function') { + if (IS_FUNCTION(callback)) { process.nextTick(function() { callback(undefined, 0); }); @@ -497,7 +494,7 @@ fs.write = function(fd, buffer, offset, length, position, callback) { }; fs.writeSync = function(fd, buffer, offset, length, position) { - if (!Buffer.isBuffer(buffer)) { + if (!IS_BUFFER(buffer)) { // legacy string interface (fd, data, position, encoding) position = arguments[2]; assertEncoding(arguments[3]); @@ -528,14 +525,14 @@ fs.renameSync = function(oldPath, newPath) { }; fs.truncate = function(path, len, callback) { - if (typeof path === 'number') { + if (IS_NUMBER(path)) { // legacy return fs.ftruncate(path, len, callback); } - if (typeof len === 'function') { + if (IS_FUNCTION(len)) { callback = len; len = 0; - } else if (typeof len === 'undefined') { + } else if (IS_UNDEFINED(len)) { len = 0; } callback = maybeCallback(callback); @@ -550,11 +547,11 @@ fs.truncate = function(path, len, callback) { }; fs.truncateSync = function(path, len) { - if (typeof path === 'number') { + if (IS_NUMBER(path)) { // legacy return fs.ftruncateSync(path, len); } - if (typeof len === 'undefined') { + if (IS_UNDEFINED(len)) { len = 0; } // allow error to be thrown, but still close fd. @@ -568,17 +565,17 @@ fs.truncateSync = function(path, len) { }; fs.ftruncate = function(fd, len, callback) { - if (typeof len === 'function') { + if (IS_FUNCTION(len)) { callback = len; len = 0; - } else if (typeof len === 'undefined') { + } else if (IS_UNDEFINED(len)) { len = 0; } binding.ftruncate(fd, len, makeCallback(callback)); }; fs.ftruncateSync = function(fd, len) { - if (typeof len === 'undefined') { + if (IS_UNDEFINED(len)) { len = 0; } return binding.ftruncate(fd, len); @@ -612,7 +609,7 @@ fs.fsyncSync = function(fd) { }; fs.mkdir = function(path, mode, callback) { - if (typeof mode === 'function') callback = mode; + if (IS_FUNCTION(mode)) callback = mode; callback = makeCallback(callback); if (!nullCheck(path, callback)) return; binding.mkdir(pathModule._makeLong(path), @@ -692,7 +689,7 @@ function preprocessSymlinkDestination(path, type) { } fs.symlink = function(destination, path, type_, callback) { - var type = (typeof type_ === 'string' ? type_ : null); + var type = (IS_STRING(type_) ? type_ : null); var callback = makeCallback(arguments[arguments.length - 1]); if (!nullCheck(destination, callback)) return; @@ -705,7 +702,7 @@ fs.symlink = function(destination, path, type_, callback) { }; fs.symlinkSync = function(destination, path, type) { - type = (typeof type === 'string' ? type : null); + type = (IS_STRING(type) ? type : null); nullCheck(destination); nullCheck(path); @@ -843,10 +840,10 @@ fs.chownSync = function(path, uid, gid) { // converts Date or number to a fractional UNIX timestamp function toUnixTimestamp(time) { - if (typeof time == 'number') { + if (IS_NUMBER(time)) { return time; } - if (time instanceof Date) { + if (IS_DATE(time)) { // convert to 123.456 UNIX timestamp return time.getTime() / 1000; } @@ -909,13 +906,13 @@ function writeAll(fd, buffer, offset, length, position, callback) { fs.writeFile = function(path, data, options, callback) { var callback = maybeCallback(arguments[arguments.length - 1]); - if (typeof options === 'function' || !options) { + if (IS_FUNCTION(options) || !options) { options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'w' }; - } else if (typeof options === 'string') { + } else if (IS_STRING(options)) { options = { encoding: options, mode: 438, flag: 'w' }; } else if (!options) { options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'w' }; - } else if (typeof options !== 'object') { + } else if (!IS_OBJECT(options)) { throw new TypeError('Bad arguments'); } @@ -926,7 +923,7 @@ fs.writeFile = function(path, data, options, callback) { if (openErr) { if (callback) callback(openErr); } else { - var buffer = Buffer.isBuffer(data) ? data : new Buffer('' + data, + var buffer = IS_BUFFER(data) ? data : new Buffer('' + data, options.encoding || 'utf8'); var position = /a/.test(flag) ? null : 0; writeAll(fd, buffer, 0, buffer.length, position, callback); @@ -937,9 +934,9 @@ fs.writeFile = function(path, data, options, callback) { fs.writeFileSync = function(path, data, options) { if (!options) { options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'w' }; - } else if (typeof options === 'string') { + } else if (IS_STRING(options)) { options = { encoding: options, mode: 438, flag: 'w' }; - } else if (typeof options !== 'object') { + } else if (!IS_OBJECT(options)) { throw new TypeError('Bad arguments'); } @@ -947,7 +944,7 @@ fs.writeFileSync = function(path, data, options) { var flag = options.flag || 'w'; var fd = fs.openSync(path, flag, options.mode); - if (!Buffer.isBuffer(data)) { + if (!IS_BUFFER(data)) { data = new Buffer('' + data, options.encoding || 'utf8'); } var written = 0; @@ -966,13 +963,13 @@ fs.writeFileSync = function(path, data, options) { fs.appendFile = function(path, data, options, callback_) { var callback = maybeCallback(arguments[arguments.length - 1]); - if (typeof options === 'function' || !options) { + if (IS_FUNCTION(options) || !options) { options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'a' }; - } else if (typeof options === 'string') { + } else if (IS_STRING(options)) { options = { encoding: options, mode: 438, flag: 'a' }; } else if (!options) { options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'a' }; - } else if (typeof options !== 'object') { + } else if (!IS_OBJECT(options)) { throw new TypeError('Bad arguments'); } @@ -984,9 +981,9 @@ fs.appendFile = function(path, data, options, callback_) { fs.appendFileSync = function(path, data, options) { if (!options) { options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'a' }; - } else if (typeof options === 'string') { + } else if (IS_STRING(options)) { options = { encoding: options, mode: 438, flag: 'a' }; - } else if (typeof options !== 'object') { + } else if (!IS_OBJECT(options)) { throw new TypeError('Bad arguments'); } if (!options.flag) @@ -1033,7 +1030,7 @@ fs.watch = function(filename) { var options; var listener; - if ('object' == typeof arguments[1]) { + if (IS_OBJECT(arguments[1])) { options = arguments[1]; listener = arguments[2]; } else { @@ -1041,7 +1038,7 @@ fs.watch = function(filename) { listener = arguments[1]; } - if (options.persistent === undefined) options.persistent = true; + if (IS_UNDEFINED(options.persistent)) options.persistent = true; watcher = new FSWatcher(); watcher.start(filename, options.persistent); @@ -1113,7 +1110,7 @@ fs.watchFile = function(filename) { persistent: true }; - if ('object' == typeof arguments[1]) { + if (IS_OBJECT(arguments[1])) { options = util._extend(options, arguments[1]); listener = arguments[2]; } else { @@ -1140,7 +1137,7 @@ fs.unwatchFile = function(filename, listener) { var stat = statWatchers[filename]; - if (typeof listener === 'function') { + if (IS_FUNCTION(listener)) { stat.removeListener('change', listener); } else { stat.removeAllListeners('change'); @@ -1249,7 +1246,7 @@ fs.realpathSync = function realpathSync(p, cache) { linkTarget = seenLinks[id]; } } - if (linkTarget === null) { + if (IS_NULL(linkTarget)) { fs.statSync(base); linkTarget = fs.readlinkSync(base); } @@ -1271,7 +1268,7 @@ fs.realpathSync = function realpathSync(p, cache) { fs.realpath = function realpath(p, cache, cb) { - if (typeof cb !== 'function') { + if (!IS_FUNCTION(cb)) { cb = maybeCallback(cache); cache = null; } @@ -1432,13 +1429,13 @@ function ReadStream(path, options) { options.autoClose : true; this.pos = undefined; - if (this.start !== undefined) { - if ('number' !== typeof this.start) { + if (!IS_UNDEFINED(this.start)) { + if (!IS_NUMBER(this.start)) { throw TypeError('start must be a Number'); } - if (this.end === undefined) { + if (IS_UNDEFINED(this.end)) { this.end = Infinity; - } else if ('number' !== typeof this.end) { + } else if (!IS_NUMBER(this.end)) { throw TypeError('end must be a Number'); } @@ -1449,7 +1446,7 @@ function ReadStream(path, options) { this.pos = this.start; } - if (typeof this.fd !== 'number') + if (!IS_NUMBER(this.fd)) this.open(); this.on('end', function() { @@ -1480,7 +1477,7 @@ ReadStream.prototype.open = function() { }; ReadStream.prototype._read = function(n) { - if (typeof this.fd !== 'number') + if (!IS_NUMBER(this.fd)) return this.once('open', function() { this._read(n); }); @@ -1501,7 +1498,7 @@ ReadStream.prototype._read = function(n) { var toRead = Math.min(pool.length - pool.used, n); var start = pool.used; - if (this.pos !== undefined) + if (!IS_UNDEFINED(this.pos)) toRead = Math.min(this.end - this.pos + 1, toRead); // already read everything we were supposed to read! @@ -1514,7 +1511,7 @@ ReadStream.prototype._read = function(n) { fs.read(this.fd, pool, pool.used, toRead, this.pos, onread); // move the pool positions, and internal position for reading. - if (this.pos !== undefined) + if (!IS_UNDEFINED(this.pos)) this.pos += toRead; pool.used += toRead; @@ -1540,7 +1537,7 @@ ReadStream.prototype.destroy = function() { return; this.destroyed = true; - if ('number' === typeof this.fd) + if (IS_NUMBER(this.fd)) this.close(); }; @@ -1549,8 +1546,8 @@ ReadStream.prototype.close = function(cb) { var self = this; if (cb) this.once('close', cb); - if (this.closed || 'number' !== typeof this.fd) { - if ('number' !== typeof this.fd) { + if (this.closed || !IS_NUMBER(this.fd)) { + if (!IS_NUMBER(this.fd)) { this.once('open', close); return; } @@ -1598,8 +1595,8 @@ function WriteStream(path, options) { this.pos = undefined; this.bytesWritten = 0; - if (this.start !== undefined) { - if ('number' !== typeof this.start) { + if (!IS_UNDEFINED(this.start)) { + if (!IS_NUMBER(this.start)) { throw TypeError('start must be a Number'); } if (this.start < 0) { @@ -1609,7 +1606,7 @@ function WriteStream(path, options) { this.pos = this.start; } - if ('number' !== typeof this.fd) + if (!IS_NUMBER(this.fd)) this.open(); // dispose on finish. @@ -1634,10 +1631,10 @@ WriteStream.prototype.open = function() { WriteStream.prototype._write = function(data, encoding, cb) { - if (!Buffer.isBuffer(data)) + if (!IS_BUFFER(data)) return this.emit('error', new Error('Invalid data')); - if (typeof this.fd !== 'number') + if (!IS_NUMBER(this.fd)) return this.once('open', function() { this._write(data, encoding, cb); }); @@ -1652,7 +1649,7 @@ WriteStream.prototype._write = function(data, encoding, cb) { cb(); }); - if (this.pos !== undefined) + if (!IS_UNDEFINED(this.pos)) this.pos += data.length; }; @@ -1686,10 +1683,10 @@ SyncWriteStream.prototype.write = function(data, arg1, arg2) { // parse arguments if (arg1) { - if (typeof arg1 === 'string') { + if (IS_STRING(arg1)) { encoding = arg1; cb = arg2; - } else if (typeof arg1 === 'function') { + } else if (IS_FUNCTION(arg1)) { cb = arg1; } else { throw new Error('bad arg'); @@ -1698,7 +1695,7 @@ SyncWriteStream.prototype.write = function(data, arg1, arg2) { assertEncoding(encoding); // Change strings to buffers. SLOW - if (typeof data == 'string') { + if (IS_STRING(data)) { data = new Buffer(data, encoding); } diff --git a/lib/https.js b/lib/https.js index afbdef1..4ffc1e6 100644 --- a/lib/https.js +++ b/lib/https.js @@ -60,21 +60,21 @@ exports.createServer = function(opts, requestListener) { // HTTPS agents. function createConnection(port, host, options) { - if (typeof port === 'object') { + if (IS_OBJECT(port)) { options = port; - } else if (typeof host === 'object') { + } else if (IS_OBJECT(host)) { options = host; - } else if (typeof options === 'object') { + } else if (IS_OBJECT(options)) { options = options; } else { options = {}; } - if (typeof port === 'number') { + if (IS_NUMBER(port)) { options.port = port; } - if (typeof host === 'string') { + if (IS_STRING(host)) { options.host = host; } @@ -115,7 +115,7 @@ Agent.prototype.getName = function(options) { name += options.pfx; name += ':'; - if (options.rejectUnauthorized !== undefined) + if (!IS_UNDEFINED(options.rejectUnauthorized)) name += options.rejectUnauthorized; return name; diff --git a/lib/module.js b/lib/module.js index d34ce10..ec0e761 100644 --- a/lib/module.js +++ b/lib/module.js @@ -352,7 +352,7 @@ Module.prototype.load = function(filename) { Module.prototype.require = function(path) { - assert(typeof path === 'string', 'path must be a string'); + assert(IS_STRING(path), 'path must be a string'); assert(path, 'missing path'); return Module._load(path, this); }; diff --git a/lib/net.js b/lib/net.js index 0b250ae..ddce74b 100644 --- a/lib/net.js +++ b/lib/net.js @@ -57,7 +57,7 @@ function createHandle(fd) { var debug = util.debuglog('net'); function isPipeName(s) { - return typeof s === 'string' && toNumber(s) === false; + return IS_STRING(s) && toNumber(s) === false; } @@ -90,7 +90,7 @@ exports.connect = exports.createConnection = function() { function normalizeConnectArgs(args) { var options = {}; - if (typeof args[0] === 'object') { + if (IS_OBJECT(args[0])) { // connect(options, [cb]) options = args[0]; } else if (isPipeName(args[0])) { @@ -99,13 +99,13 @@ function normalizeConnectArgs(args) { } else { // connect(port, [host], [cb]) options.port = args[0]; - if (typeof args[1] === 'string') { + if (IS_STRING(args[1])) { options.host = args[1]; } } var cb = args[args.length - 1]; - return (typeof cb === 'function') ? [options, cb] : [options]; + return IS_FUNCTION(cb) ? [options, cb] : [options]; } exports._normalizeConnectArgs = normalizeConnectArgs; @@ -135,20 +135,16 @@ function Socket(options) { this._hadError = false; this._handle = null; - switch (typeof options) { - case 'number': - options = { fd: options }; // Legacy interface. - break; - case 'undefined': - options = {}; - break; - } + if (IS_NUMBER(options)) + options = { fd: options }; // Legacy interface. + else if (IS_UNDEFINED(options)) + options = {}; stream.Duplex.call(this, options); if (options.handle) { this._handle = options.handle; // private - } else if (typeof options.fd !== 'undefined') { + } else if (!IS_UNDEFINED(options.fd)) { this._handle = createHandle(options.fd); this._handle.open(options.fd); this.readable = options.readable !== false; @@ -263,7 +259,7 @@ function onSocketEnd() { // of the other side sending a FIN. The standard 'write after end' // is overly vague, and makes it seem like the user's code is to blame. function writeAfterFIN(chunk, encoding, cb) { - if (typeof encoding === 'function') { + if (IS_FUNCTION(encoding)) { cb = encoding; encoding = null; } @@ -273,7 +269,7 @@ function writeAfterFIN(chunk, encoding, cb) { var self = this; // TODO: defer error events consistently everywhere, not just the cb self.emit('error', er); - if (typeof cb === 'function') { + if (IS_FUNCTION(cb)) { process.nextTick(function() { cb(er); }); @@ -326,7 +322,7 @@ Socket.prototype._onTimeout = function() { Socket.prototype.setNoDelay = function(enable) { // backwards compatibility: assume true when `enable` is omitted if (this._handle && this._handle.setNoDelay) - this._handle.setNoDelay(typeof enable === 'undefined' ? true : !!enable); + this._handle.setNoDelay(IS_UNDEFINED(enable) ? true : !!enable); }; @@ -605,7 +601,7 @@ Socket.prototype.__defineGetter__('localPort', function() { Socket.prototype.write = function(chunk, encoding, cb) { - if (typeof chunk !== 'string' && !Buffer.isBuffer(chunk)) + if (!IS_STRING(chunk) && !IS_BUFFER(chunk)) throw new TypeError('invalid data'); return stream.Duplex.prototype.write.apply(this, arguments); }; @@ -650,7 +646,7 @@ Socket.prototype._writeGeneric = function(writev, data, encoding, cb) { // Retain chunks if (err === 0) req._chunks = chunks; } else { - var enc = Buffer.isBuffer(data) ? 'buffer' : encoding; + var enc = IS_BUFFER(data) ? 'buffer' : encoding; err = createWriteReq(req, this._handle, data, enc); } @@ -732,14 +728,14 @@ Socket.prototype.__defineGetter__('bytesWritten', function() { encoding = this._pendingEncoding; state.buffer.forEach(function(el) { - if (Buffer.isBuffer(el.chunk)) + if (IS_BUFFER(el.chunk)) bytes += el.chunk.length; else bytes += Buffer.byteLength(el.chunk, el.encoding); }); if (data) { - if (Buffer.isBuffer(data)) + if (IS_BUFFER(data)) bytes += data.length; else bytes += Buffer.byteLength(data, encoding); @@ -817,7 +813,7 @@ Socket.prototype.connect = function(options, cb) { if (this.write !== Socket.prototype.write) this.write = Socket.prototype.write; - if (typeof options !== 'object') { + if (!IS_OBJECT(options)) { // Old API: // connect(port, [host], [cb]) // connect(path, [cb]); @@ -844,7 +840,7 @@ Socket.prototype.connect = function(options, cb) { initSocketHandle(this); } - if (typeof cb === 'function') { + if (IS_FUNCTION(cb)) { self.once('connect', cb); } @@ -952,13 +948,13 @@ function Server(/* [ options, ] listener */) { var options; - if (typeof arguments[0] == 'function') { + if (IS_FUNCTION(arguments[0])) { options = {}; self.on('connection', arguments[0]); } else { options = arguments[0] || {}; - if (typeof arguments[1] == 'function') { + if (IS_FUNCTION(arguments[1])) { self.on('connection', arguments[1]); } } @@ -998,7 +994,7 @@ var createServerHandle = exports._createServerHandle = // assign handle in listen, and clean up if bind or listen fails var handle; - if (typeof fd === 'number' && fd >= 0) { + if (IS_NUMBER(fd) && fd >= 0) { try { handle = createHandle(fd); } @@ -1051,7 +1047,7 @@ Server.prototype._listen2 = function(address, port, addressType, backlog, fd) { if (!self._handle) { debug('_listen2: create a handle'); var rval = createServerHandle(address, port, addressType, fd); - if (typeof rval === 'number') { + if (IS_NUMBER(rval)) { var error = errnoException(rval, 'listen'); process.nextTick(function() { self.emit('error', error); @@ -1126,7 +1122,7 @@ Server.prototype.listen = function() { var self = this; var lastArg = arguments[arguments.length - 1]; - if (typeof lastArg == 'function') { + if (IS_FUNCTION(lastArg)) { self.once('listening', lastArg); } @@ -1138,11 +1134,11 @@ Server.prototype.listen = function() { var TCP = process.binding('tcp_wrap').TCP; - if (arguments.length == 0 || typeof arguments[0] == 'function') { + if (arguments.length == 0 || IS_FUNCTION(arguments[0])) { // Bind to a random port. listen(self, '0.0.0.0', 0, null, backlog); - } else if (arguments[0] && typeof arguments[0] === 'object') { + } else if (arguments[0] && IS_OBJECT(arguments[0])) { var h = arguments[0]; if (h._handle) { h = h._handle; @@ -1152,7 +1148,7 @@ Server.prototype.listen = function() { if (h instanceof TCP) { self._handle = h; listen(self, null, -1, -1, backlog); - } else if (typeof h.fd === 'number' && h.fd >= 0) { + } else if (IS_NUMBER(h.fd) && h.fd >= 0) { listen(self, null, null, null, backlog, h.fd); } else { throw new Error('Invalid listen argument: ' + h); @@ -1162,9 +1158,9 @@ Server.prototype.listen = function() { var pipeName = self._pipeName = arguments[0]; listen(self, pipeName, -1, -1, backlog); - } else if (typeof arguments[1] == 'undefined' || - typeof arguments[1] == 'function' || - typeof arguments[1] == 'number') { + } else if (IS_UNDEFINED(arguments[1]) || + IS_FUNCTION(arguments[1]) || + IS_NUMBER(arguments[1])) { // The first argument is the port, no IP given. listen(self, '0.0.0.0', port, 4, backlog); @@ -1351,11 +1347,11 @@ if (process.platform === 'win32') { var simultaneousAccepts; exports._setSimultaneousAccepts = function(handle) { - if (typeof handle === 'undefined') { + if (IS_UNDEFINED(handle)) { return; } - if (typeof simultaneousAccepts === 'undefined') { + if (IS_UNDEFINED(simultaneousAccepts)) { simultaneousAccepts = (process.env.NODE_MANY_ACCEPTS && process.env.NODE_MANY_ACCEPTS !== '0'); } diff --git a/lib/path.js b/lib/path.js index 5cef72f..bd5e437 100644 --- a/lib/path.js +++ b/lib/path.js @@ -112,7 +112,7 @@ if (isWindows) { } // Skip empty and invalid entries - if (typeof path !== 'string') { + if (!IS_STRING(path)) { throw new TypeError('Arguments to path.resolve must be strings'); } else if (!path) { continue; @@ -214,7 +214,7 @@ if (isWindows) { // windows version exports.join = function() { function f(p) { - if (typeof p !== 'string') { + if (!IS_STRING(p)) { throw new TypeError('Arguments to path.join must be strings'); } return p; @@ -323,7 +323,7 @@ if (isWindows) { var path = (i >= 0) ? arguments[i] : process.cwd(); // Skip empty and invalid entries - if (typeof path !== 'string') { + if (!IS_STRING(path)) { throw new TypeError('Arguments to path.resolve must be strings'); } else if (!path) { continue; @@ -374,7 +374,7 @@ if (isWindows) { exports.join = function() { var paths = Array.prototype.slice.call(arguments, 0); return exports.normalize(paths.filter(function(p, index) { - if (typeof p !== 'string') { + if (!IS_STRING(p)) { throw new TypeError('Arguments to path.join must be strings'); } return p; @@ -476,7 +476,7 @@ exports.existsSync = util.deprecate(function(path) { if (isWindows) { exports._makeLong = function(path) { // Note: this will *probably* throw somewhere. - if (typeof path !== 'string') + if (!IS_STRING(path)) return path; if (!path) { diff --git a/lib/querystring.js b/lib/querystring.js index 0ab739a..ce9853d 100644 --- a/lib/querystring.js +++ b/lib/querystring.js @@ -114,33 +114,27 @@ QueryString.escape = function(str) { }; var stringifyPrimitive = function(v) { - switch (typeof v) { - case 'string': - return v; - - case 'boolean': - return v ? 'true' : 'false'; - - case 'number': - return isFinite(v) ? v : ''; - - default: - return ''; - } + if (IS_STRING(v)) + return v; + if (IS_BOOLEAN(v)) + return v ? 'true' : 'false'; + if (IS_NUMBER(v)) + return isFinite(v) ? v : ''; + return ''; }; QueryString.stringify = QueryString.encode = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; - if (obj === null) { + if (IS_NULL(obj)) { obj = undefined; } - if (typeof obj === 'object') { + if (IS_OBJECT(obj)) { return Object.keys(obj).map(function(k) { var ks = QueryString.escape(stringifyPrimitive(k)) + eq; - if (Array.isArray(obj[k])) { + if (IS_ARRAY(obj[k])) { return obj[k].map(function(v) { return ks + QueryString.escape(stringifyPrimitive(v)); }).join(sep); @@ -162,7 +156,7 @@ QueryString.parse = QueryString.decode = function(qs, sep, eq, options) { eq = eq || '='; var obj = {}; - if (typeof qs !== 'string' || qs.length === 0) { + if (!IS_STRING(qs) || qs.length === 0) { return obj; } @@ -170,7 +164,7 @@ QueryString.parse = QueryString.decode = function(qs, sep, eq, options) { qs = qs.split(sep); var maxKeys = 1000; - if (options && typeof options.maxKeys === 'number') { + if (options && IS_NUMBER(options.maxKeys)) { maxKeys = options.maxKeys; } @@ -203,7 +197,7 @@ QueryString.parse = QueryString.decode = function(qs, sep, eq, options) { if (!hasOwnProperty(obj, k)) { obj[k] = v; - } else if (Array.isArray(obj[k])) { + } else if (IS_ARRAY(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; diff --git a/lib/readline.js b/lib/readline.js index 3280115..f203530 100644 --- a/lib/readline.js +++ b/lib/readline.js @@ -63,13 +63,13 @@ function Interface(input, output, completer, terminal) { completer = completer || function() { return []; }; - if (typeof completer !== 'function') { + if (!IS_FUNCTION(completer)) { throw new TypeError('Argument \'completer\' must be a function'); } // backwards compat; check the isTTY prop of the output stream // when `terminal` was not specified - if (typeof terminal == 'undefined') { + if (IS_UNDEFINED(terminal)) { terminal = !!output.isTTY; } @@ -154,7 +154,7 @@ Interface.prototype.setPrompt = function(prompt) { Interface.prototype._setRawMode = function(mode) { - if (typeof this.input.setRawMode === 'function') { + if (IS_FUNCTION(this.input.setRawMode)) { return this.input.setRawMode(mode); } }; @@ -172,7 +172,7 @@ Interface.prototype.prompt = function(preserveCursor) { Interface.prototype.question = function(query, cb) { - if (typeof cb === 'function') { + if (IS_FUNCTION(cb)) { if (this._questionCallback) { this.prompt(); } else { @@ -290,7 +290,7 @@ Interface.prototype.write = function(d, key) { // \r\n, \n, or \r followed by something other than \n var lineEnding = /\r?\n|\r(?!\n)/; Interface.prototype._normalWrite = function(b) { - if (b === undefined) { + if (IS_UNDEFINED(b)) { return; } var string = this._decoder.write(b); @@ -843,7 +843,7 @@ Interface.prototype._ttyWrite = function(s, key) { break; default: - if (Buffer.isBuffer(s)) + if (IS_BUFFER(s)) s = s.toString('utf-8'); if (s) { @@ -944,8 +944,8 @@ function emitKey(stream, s) { }, parts; - if (Buffer.isBuffer(s)) { - if (s[0] > 127 && s[1] === undefined) { + if (IS_BUFFER(s)) { + if (s[0] > 127 && IS_UNDEFINED(s[1])) { s[0] -= 128; s = '\x1b' + s.toString(stream.encoding || 'utf-8'); } else { @@ -1124,7 +1124,7 @@ function emitKey(stream, s) { } // Don't emit a key if no name was found - if (key.name === undefined) { + if (IS_UNDEFINED(key.name)) { key = undefined; } @@ -1143,13 +1143,13 @@ function emitKey(stream, s) { */ function cursorTo(stream, x, y) { - if (typeof x !== 'number' && typeof y !== 'number') + if (!IS_NUMBER(x) && !IS_NUMBER(y)) return; - if (typeof x !== 'number') + if (!IS_NUMBER(x)) throw new Error("Can't set cursor row without also setting it's column"); - if (typeof y !== 'number') { + if (!IS_NUMBER(y)) { stream.write('\x1b[' + (x + 1) + 'G'); } else { stream.write('\x1b[' + (y + 1) + ';' + (x + 1) + 'H'); diff --git a/lib/repl.js b/lib/repl.js index 5980bef..2fd5821 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -83,7 +83,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) { EventEmitter.call(this); var options, input, output, dom; - if (typeof prompt == 'object') { + if (IS_OBJECT(prompt)) { // an options object was given options = prompt; stream = options.stream || options.socket; @@ -94,7 +94,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) { ignoreUndefined = options.ignoreUndefined; prompt = options.prompt; dom = options.domain; - } else if (typeof prompt != 'string') { + } else if (!IS_STRING(prompt)) { throw new Error('An options Object, or a prompt String are required'); } else { options = {}; @@ -160,7 +160,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) { self.resetContext(); self.bufferedCommand = ''; - self.prompt = (prompt != undefined ? prompt : '> '); + self.prompt = !IS_UNDEFINED(prompt) ? prompt : '> '; function complete(text, callback) { self.complete(text, callback); @@ -180,7 +180,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) { // figure out which "writer" function to use self.writer = options.writer || exports.writer; - if (typeof options.useColors === 'undefined') { + if (IS_UNDEFINED(options.useColors)) { options.useColors = rli.terminal; } self.useColors = !!options.useColors; @@ -256,9 +256,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) { function(e, ret) { if (e && !isSyntaxError(e)) return finish(e); - if (typeof ret === 'function' && - /^[\r\n\s]*function/.test(evalCmd) || - e) { + if (IS_FUNCTION(ret) && /^[\r\n\s]*function/.test(evalCmd) || e) { // Now as statement without parens. self.eval(evalCmd, self.context, 'repl', finish); } else { @@ -300,7 +298,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) { self.bufferedCommand = ''; // If we got any output - print it (if no error) - if (!e && (!self.ignoreUndefined || ret !== undefined)) { + if (!e && (!self.ignoreUndefined || !IS_UNDEFINED(ret))) { self.context._ = ret; self.outputStream.write(self.writer(ret) + '\n'); } @@ -422,7 +420,7 @@ var simpleExpressionRE = // getter code. REPLServer.prototype.complete = function(line, callback) { // There may be local variables to evaluate, try a nested REPL - if (this.bufferedCommand != undefined && this.bufferedCommand.length) { + if (!IS_UNDEFINED(this.bufferedCommand) && this.bufferedCommand.length) { // Get a new array of inputed lines var tmp = this.lines.slice(); // Kill off all function declarations to push all local variables into @@ -564,7 +562,7 @@ REPLServer.prototype.complete = function(line, callback) { this.eval('.scope', this.context, 'repl', function(err, globals) { if (err || !globals) { addStandardGlobals(completionGroups, filter); - } else if (Array.isArray(globals[0])) { + } else if (IS_ARRAY(globals[0])) { // Add grouped globals globals.forEach(function(group) { completionGroups.push(group); @@ -581,19 +579,19 @@ REPLServer.prototype.complete = function(line, callback) { // if (e) console.log(e); if (obj != null) { - if (typeof obj === 'object' || typeof obj === 'function') { + if (IS_OBJECT(obj) || IS_FUNCTION(obj)) { memberGroups.push(Object.getOwnPropertyNames(obj)); } // works for non-objects try { var sentinel = 5; var p; - if (typeof obj === 'object' || typeof obj === 'function') { + if (IS_OBJECT(obj) || IS_FUNCTION(obj)) { p = Object.getPrototypeOf(obj); } else { p = obj.constructor ? obj.constructor.prototype : null; } - while (p !== null) { + while (!IS_NULL(p)) { memberGroups.push(Object.getOwnPropertyNames(p)); p = Object.getPrototypeOf(p); // Circular refs possible? Let's guard against that. @@ -692,9 +690,9 @@ REPLServer.prototype.parseREPLKeyword = function(keyword, rest) { REPLServer.prototype.defineCommand = function(keyword, cmd) { - if (typeof cmd === 'function') { + if (IS_FUNCTION(cmd)) { cmd = {action: cmd}; - } else if (typeof cmd.action !== 'function') { + } else if (!IS_FUNCTION(cmd.action)) { throw new Error('bad argument, action must be a function'); } this.commands['.' + keyword] = cmd; diff --git a/lib/smalloc.js b/lib/smalloc.js index b0226a0..b6e9093 100644 --- a/lib/smalloc.js +++ b/lib/smalloc.js @@ -39,15 +39,15 @@ function alloc(n, obj) { if (n > kMaxLength) throw new RangeError('n > kMaxLength'); - if (Array.isArray(obj)) + if (IS_ARRAY(obj)) throw new TypeError('Arrays are not supported'); - return smalloc.alloc(obj === undefined ? {} : obj, n); + return smalloc.alloc(IS_UNDEFINED(obj) ? {} : obj, n); } function dispose(obj) { - if (obj instanceof Buffer) + if (IS_BUFFER(obj)) throw new TypeError('obj cannot be a Buffer'); smalloc.dispose(obj); } diff --git a/lib/stream.js b/lib/stream.js index 098ff61..5d8021e 100644 --- a/lib/stream.js +++ b/lib/stream.js @@ -84,7 +84,7 @@ Stream.prototype.pipe = function(dest, options) { if (didOnEnd) return; didOnEnd = true; - if (typeof dest.destroy === 'function') dest.destroy(); + if (IS_FUNCTION(dest.destroy)) dest.destroy(); } // don't leave dangling pipes when there are errors. diff --git a/lib/tls.js b/lib/tls.js index 6d2f59e..a0d31bf 100644 --- a/lib/tls.js +++ b/lib/tls.js @@ -51,7 +51,7 @@ exports.getCiphers = function() { // ("\x06spdy/2\x08http/1.1\x08http/1.0") exports.convertNPNProtocols = function convertNPNProtocols(NPNProtocols, out) { // If NPNProtocols is Array - translate it into buffer - if (Array.isArray(NPNProtocols)) { + if (IS_ARRAY(NPNProtocols)) { var buff = new Buffer(NPNProtocols.reduce(function(p, c) { return p + 1 + Buffer.byteLength(c); }, 0)); @@ -68,7 +68,7 @@ exports.convertNPNProtocols = function convertNPNProtocols(NPNProtocols, out) { } // If it's already a Buffer - store it - if (Buffer.isBuffer(NPNProtocols)) { + if (IS_BUFFER(NPNProtocols)) { out.NPNProtocols = NPNProtocols; } }; @@ -166,7 +166,7 @@ exports.checkServerIdentity = function checkServerIdentity(host, cert) { // RFC6125 if (matchCN) { var commonNames = cert.subject.CN; - if (Array.isArray(commonNames)) { + if (IS_ARRAY(commonNames)) { for (var i = 0, k = commonNames.length; i < k; ++i) { dnsNames.push(regexpify(commonNames[i], true)); } @@ -194,7 +194,7 @@ exports.parseCertString = function parseCertString(s) { var key = parts[i].slice(0, sepIndex); var value = parts[i].slice(sepIndex + 1); if (key in out) { - if (!Array.isArray(out[key])) { + if (!IS_ARRAY(out[key])) { out[key] = [out[key]]; } out[key].push(value); diff --git a/lib/url.js b/lib/url.js index 4903026..f10ba5f 100644 --- a/lib/url.js +++ b/lib/url.js @@ -94,7 +94,7 @@ var protocolPattern = /^([a-z0-9.+-]+:)/i, querystring = require('querystring'); function urlParse(url, parseQueryString, slashesDenoteHost) { - if (url && typeof(url) === 'object' && url instanceof Url) return url; + if (url && IS_OBJECT(url) && url instanceof Url) return url; var u = new Url; u.parse(url, parseQueryString, slashesDenoteHost); @@ -102,7 +102,7 @@ function urlParse(url, parseQueryString, slashesDenoteHost) { } Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { - if (typeof url !== 'string') { + if (!IS_STRING(url)) { throw new TypeError("Parameter 'url' must be a string, not " + typeof url); } @@ -340,7 +340,7 @@ function urlFormat(obj) { // If it's an obj, this is a no-op. // this way, you can call url_format() on strings // to clean up potentially wonky urls. - if (typeof(obj) === 'string') obj = urlParse(obj); + if (IS_STRING(obj)) obj = urlParse(obj); if (!(obj instanceof Url)) return Url.prototype.format.call(obj); return obj.format(); } @@ -370,8 +370,7 @@ Url.prototype.format = function() { } } - if (this.query && typeof this.query === 'object' && - Object.keys(this.query).length) { + if (this.query && IS_OBJECT(this.query) && Object.keys(this.query).length) { query = querystring.stringify(this.query); } @@ -414,7 +413,7 @@ function urlResolveObject(source, relative) { } Url.prototype.resolveObject = function(relative) { - if (typeof relative === 'string') { + if (IS_STRING(relative)) { var rel = new Url(); rel.parse(relative, false, true); relative = rel; @@ -554,7 +553,7 @@ Url.prototype.resolveObject = function(relative) { srcPath = srcPath.concat(relPath); result.search = relative.search; result.query = relative.query; - } else if (relative.search !== null && relative.search !== undefined) { + } else if (!IS_NULL_OR_UNDEFINED(relative.search)) { // just pull out the search. // like href='?foo'. // Put this after the other two cases because it simplifies the booleans @@ -573,7 +572,7 @@ Url.prototype.resolveObject = function(relative) { result.search = relative.search; result.query = relative.query; //to support http.request - if (result.pathname !== null || result.search !== null) { + if (!IS_NULL(result.pathname) || !IS_NULL(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } @@ -667,7 +666,7 @@ Url.prototype.resolveObject = function(relative) { } //to support request.http - if (result.pathname !== null || result.search !== null) { + if (!IS_NULL(result.pathname) || !IS_NULL(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } diff --git a/lib/util.js b/lib/util.js index fae4593..993e363 100644 --- a/lib/util.js +++ b/lib/util.js @@ -21,7 +21,7 @@ var formatRegExp = /%[sdj%]/g; exports.format = function(f) { - if (typeof f !== 'string') { + if (!IS_STRING(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); @@ -44,7 +44,7 @@ exports.format = function(f) { } }); for (var x = args[i]; i < len; x = args[++i]) { - if (x === null || typeof x !== 'object') { + if (IS_NULL(x) || !IS_OBJECT(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); @@ -117,7 +117,7 @@ function inspect(obj, opts) { // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; - if (typeof opts === 'boolean') { + if (IS_BOOLEAN(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { @@ -125,10 +125,10 @@ function inspect(obj, opts) { exports._extend(ctx, opts); } // set default options - if (typeof ctx.showHidden === 'undefined') ctx.showHidden = false; - if (typeof ctx.depth === 'undefined') ctx.depth = 2; - if (typeof ctx.colors === 'undefined') ctx.colors = false; - if (typeof ctx.customInspect === 'undefined') ctx.customInspect = true; + if (IS_UNDEFINED(ctx.showHidden)) ctx.showHidden = false; + if (IS_UNDEFINED(ctx.depth)) ctx.depth = 2; + if (IS_UNDEFINED(ctx.colors)) ctx.colors = false; + if (IS_UNDEFINED(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } @@ -197,13 +197,15 @@ function arrayToHash(array) { function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it - if (ctx.customInspect && value && typeof value.inspect === 'function' && + if (ctx.customInspect && + value && + IS_FUNCTION(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes); - if ('string' !== typeof ret) { + if (!IS_STRING(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; @@ -225,7 +227,7 @@ function formatValue(ctx, value, recurseTimes) { // Some type of object without properties can be shortcutted. if (keys.length === 0) { - if (typeof value === 'function') { + if (IS_FUNCTION(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } @@ -249,7 +251,7 @@ function formatValue(ctx, value, recurseTimes) { } // Make functions say that they are functions - if (typeof value === 'function') { + if (IS_FUNCTION(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } @@ -299,26 +301,21 @@ function formatValue(ctx, value, recurseTimes) { function formatPrimitive(ctx, value) { - switch (typeof value) { - case 'undefined': - return ctx.stylize('undefined', 'undefined'); - - case 'string': - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - - case 'number': - return ctx.stylize('' + value, 'number'); - - case 'boolean': - return ctx.stylize('' + value, 'boolean'); - } + if (IS_UNDEFINED(value)) + return ctx.stylize('undefined', 'undefined'); + if (IS_STRING(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (IS_NUMBER(value)) + return ctx.stylize('' + value, 'number'); + if (IS_BOOLEAN(value)) + return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. - if (value === null) { + if (IS_NULL(value)) return ctx.stylize('null', 'null'); - } } @@ -366,7 +363,7 @@ function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { - if (recurseTimes === null) { + if (IS_NULL(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); @@ -386,7 +383,7 @@ function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { str = ctx.stylize('[Circular]', 'special'); } } - if (typeof name === 'undefined') { + if (IS_UNDEFINED(name)) { if (array && key.match(/^\d+$/)) { return str; } @@ -430,25 +427,25 @@ function reduceToSingleString(output, base, braces) { // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { - return Array.isArray(ar); + return IS_ARRAY(ar); } exports.isArray = isArray; function isRegExp(re) { - return typeof re === 'object' && objectToString(re) === '[object RegExp]'; + return IS_OBJECT(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isDate(d) { - return typeof d === 'object' && objectToString(d) === '[object Date]'; + return IS_OBJECT(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { - return typeof e === 'object' && objectToString(e) === '[object Error]'; + return IS_OBJECT(e) && objectToString(e) === '[object Error]'; } exports.isError = isError; @@ -509,7 +506,7 @@ exports.inherits = function(ctor, superCtor) { exports._extend = function(origin, add) { // Don't do anything if add isn't an object - if (!add || typeof add !== 'object') return origin; + if (!add || !IS_OBJECT(add)) return origin; var keys = Object.keys(add); var i = keys.length; @@ -604,7 +601,7 @@ exports.pump = exports.deprecate(function(readStream, writeStream, callback) { var uv; exports._errnoException = function(err, syscall) { - if (typeof uv === 'undefined') uv = process.binding('uv'); + if (IS_UNDEFINED(uv)) uv = process.binding('uv'); var errname = uv.errname(err); var e = new Error(syscall + ' ' + errname); e.code = errname; diff --git a/lib/vm.js b/lib/vm.js index eb17cc0..f521444 100644 --- a/lib/vm.js +++ b/lib/vm.js @@ -33,7 +33,7 @@ function Script(code, ctx, filename) { // bind all methods to this Script object Object.keys(binding.NodeScript.prototype).forEach(function(f) { - if (typeof binding.NodeScript.prototype[f] === 'function') { + if (IS_FUNCTION(binding.NodeScript.prototype[f])) { this[f] = function() { if (!(this instanceof Script)) { throw new TypeError('invalid call to ' + f); diff --git a/lib/zlib.js b/lib/zlib.js index e41d27a..855df06 100644 --- a/lib/zlib.js +++ b/lib/zlib.js @@ -108,7 +108,7 @@ exports.createUnzip = function(o) { // Convenience methods. // compress/decompress a string or buffer in one step. exports.deflate = function(buffer, opts, callback) { - if (typeof opts === 'function') { + if (IS_FUNCTION(opts)) { callback = opts; opts = {}; } @@ -116,7 +116,7 @@ exports.deflate = function(buffer, opts, callback) { }; exports.gzip = function(buffer, opts, callback) { - if (typeof opts === 'function') { + if (IS_FUNCTION(opts)) { callback = opts; opts = {}; } @@ -124,7 +124,7 @@ exports.gzip = function(buffer, opts, callback) { }; exports.deflateRaw = function(buffer, opts, callback) { - if (typeof opts === 'function') { + if (IS_FUNCTION(opts)) { callback = opts; opts = {}; } @@ -132,7 +132,7 @@ exports.deflateRaw = function(buffer, opts, callback) { }; exports.unzip = function(buffer, opts, callback) { - if (typeof opts === 'function') { + if (IS_FUNCTION(opts)) { callback = opts; opts = {}; } @@ -140,7 +140,7 @@ exports.unzip = function(buffer, opts, callback) { }; exports.inflate = function(buffer, opts, callback) { - if (typeof opts === 'function') { + if (IS_FUNCTION(opts)) { callback = opts; opts = {}; } @@ -148,7 +148,7 @@ exports.inflate = function(buffer, opts, callback) { }; exports.gunzip = function(buffer, opts, callback) { - if (typeof opts === 'function') { + if (IS_FUNCTION(opts)) { callback = opts; opts = {}; } @@ -156,7 +156,7 @@ exports.gunzip = function(buffer, opts, callback) { }; exports.inflateRaw = function(buffer, opts, callback) { - if (typeof opts === 'function') { + if (IS_FUNCTION(opts)) { callback = opts; opts = {}; } @@ -305,7 +305,7 @@ function Zlib(opts, mode) { } if (opts.dictionary) { - if (!Buffer.isBuffer(opts.dictionary)) { + if (!IS_BUFFER(opts.dictionary)) { throw new Error('Invalid dictionary: it should be a Buffer instance'); } } @@ -327,10 +327,10 @@ function Zlib(opts, mode) { }; var level = exports.Z_DEFAULT_COMPRESSION; - if (typeof opts.level === 'number') level = opts.level; + if (IS_NUMBER(opts.level)) level = opts.level; var strategy = exports.Z_DEFAULT_STRATEGY; - if (typeof opts.strategy === 'number') strategy = opts.strategy; + if (IS_NUMBER(opts.strategy)) strategy = opts.strategy; this._binding.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, @@ -390,7 +390,7 @@ Zlib.prototype._flush = function(callback) { Zlib.prototype.flush = function(kind, callback) { var ws = this._writableState; - if (typeof kind === 'function' || (kind === undefined && !callback)) { + if (IS_FUNCTION(kind) || (IS_UNDEFINED(kind) && !callback)) { callback = kind; kind = binding.Z_FULL_FLUSH; } @@ -435,7 +435,7 @@ Zlib.prototype._transform = function(chunk, encoding, cb) { var ending = ws.ending || ws.ended; var last = ending && (!chunk || ws.length === chunk.length); - if (chunk !== null && !Buffer.isBuffer(chunk)) + if (!IS_NULL(chunk) && !IS_BUFFER(chunk)) return cb(new Error('invalid input')); // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag. diff --git a/node.gyp b/node.gyp index a6f7256..ecf21f2 100644 --- a/node.gyp +++ b/node.gyp @@ -388,6 +388,7 @@ '<(python)', 'tools/js2c.py', '<@(_outputs)', + 'src/macros.py', '<@(_inputs)', ], }, diff --git a/src/macros.py b/src/macros.py new file mode 100644 index 0000000..39d05c9 --- /dev/null +++ b/src/macros.py @@ -0,0 +1,16 @@ +macro IS_BOOLEAN(arg) = (typeof(arg) === 'boolean'); +macro IS_NULL(arg) = (arg === null); +macro IS_NULL_OR_UNDEFINED(arg) = (arg == null); +macro IS_NUMBER(arg) = (typeof(arg) === 'number'); +macro IS_STRING(arg) = (typeof(arg) === 'string'); +macro IS_SYMBOL(arg) = (typeof(arg) === 'symbol'); +macro IS_UNDEFINED(arg) = (typeof(arg) === 'undefined'); + +# These macros follow the semantics of V8's %_Is*() functions. +macro IS_ARRAY(arg) = (Array.isArray(arg)); +macro IS_DATE(arg) = ((arg) instanceof Date); +macro IS_FUNCTION(arg) = (typeof(arg) === 'function'); +macro IS_OBJECT(arg) = (typeof(arg) === 'object'); +macro IS_REGEXP(arg) = ((arg) instanceof RegExp); + +macro IS_BUFFER(arg) = ((arg) instanceof Buffer);