Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lib: prefer logical assignment #55044

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion benchmark/_http-benchmarkers.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ class TestDoubleBenchmarker {
}

create(options) {
process.env.duration = process.env.duration || options.duration || 5;
process.env.duration ||= options.duration || 5;

const scheme = options.scheme || 'http';
const env = {
Expand Down
10 changes: 4 additions & 6 deletions benchmark/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,7 @@ class Benchmark {
}
const [, key, value] = match;
if (configs[key] !== undefined) {
if (!cliOptions[key])
cliOptions[key] = [];
cliOptions[key] ||= [];
cliOptions[key].push(
// Infer the type from the config object and parse accordingly
typeof configs[key][0] === 'number' ? +value : value,
Expand Down Expand Up @@ -177,10 +176,9 @@ class Benchmark {

http(options, cb) {
const http_options = { ...options };
http_options.benchmarker = http_options.benchmarker ||
this.config.benchmarker ||
this.extra_options.benchmarker ||
http_benchmarkers.default_http_benchmarker;
http_options.benchmarker ||= this.config.benchmarker ||
this.extra_options.benchmarker ||
http_benchmarkers.default_http_benchmarker;
http_benchmarkers.run(
http_options, (error, code, used_benchmarker, result, elapsed) => {
if (cb) {
Expand Down
4 changes: 2 additions & 2 deletions benchmark/es/defaultparams-bench.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ const bench = common.createBenchmark(main, {
});

function oldStyleDefaults(x, y) {
x = x || 1;
y = y || 2;
x ||= 1;
y ||= 2;
assert.strictEqual(x, 1);
assert.strictEqual(y, 2);
}
Expand Down
18 changes: 6 additions & 12 deletions benchmark/perf_hooks/resourcetiming.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,12 @@ function createTimingInfo({
finalConnectionTimingInfo = null,
}) {
if (finalConnectionTimingInfo !== null) {
finalConnectionTimingInfo.domainLookupStartTime =
finalConnectionTimingInfo.domainLookupStartTime || 0;
finalConnectionTimingInfo.domainLookupEndTime =
finalConnectionTimingInfo.domainLookupEndTime || 0;
finalConnectionTimingInfo.connectionStartTime =
finalConnectionTimingInfo.connectionStartTime || 0;
finalConnectionTimingInfo.connectionEndTime =
finalConnectionTimingInfo.connectionEndTime || 0;
finalConnectionTimingInfo.secureConnectionStartTime =
finalConnectionTimingInfo.secureConnectionStartTime || 0;
finalConnectionTimingInfo.ALPNNegotiatedProtocol =
finalConnectionTimingInfo.ALPNNegotiatedProtocol || [];
finalConnectionTimingInfo.domainLookupStartTime ||= 0;
finalConnectionTimingInfo.domainLookupEndTime ||= 0;
finalConnectionTimingInfo.connectionStartTime ||= 0;
finalConnectionTimingInfo.connectionEndTime ||= 0;
finalConnectionTimingInfo.secureConnectionStartTime ||= 0;
finalConnectionTimingInfo.ALPNNegotiatedProtocol ||= [];
}
return {
startTime,
Expand Down
2 changes: 1 addition & 1 deletion benchmark/zlib/deflate.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const bench = common.createBenchmark(main, {

function main({ n, method, inputLen }) {
// Default method value for testing.
method = method || 'deflate';
method ||= 'deflate';
const chunk = Buffer.alloc(inputLen, 'a');

switch (method) {
Expand Down
2 changes: 1 addition & 1 deletion benchmark/zlib/inflate.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const bench = common.createBenchmark(main, {

function main({ n, method, inputLen }) {
// Default method value for tests.
method = method || 'inflate';
method ||= 'inflate';
const chunk = zlib.deflateSync(Buffer.alloc(inputLen, 'a'));

let i = 0;
Expand Down
1 change: 1 addition & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ export default [
ignorePattern: '.*',
},
}],
'logical-assignment-operators': ['error', 'always', { enforceForIfStatements: true }],
'default-case-last': 'error',
'dot-notation': 'error',
'eqeqeq': ['error', 'smart'],
Expand Down
12 changes: 3 additions & 9 deletions lib/_http_agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -246,9 +246,7 @@ Agent.prototype.addRequest = function addRequest(req, options, port/* legacy */,
normalizeServerName(options, req);

const name = this.getName(options);
if (!this.sockets[name]) {
this.sockets[name] = [];
}
this.sockets[name] ||= [];

const freeSockets = this.freeSockets[name];
let socket;
Expand Down Expand Up @@ -284,9 +282,7 @@ Agent.prototype.addRequest = function addRequest(req, options, port/* legacy */,
} else {
debug('wait for socket');
// We are over limit so we'll add it to the queue.
if (!this.requests[name]) {
this.requests[name] = [];
}
this.requests[name] ||= [];

// Used to create sockets for pending requests from different origin
req[kRequestOptions] = options;
Expand All @@ -313,9 +309,7 @@ Agent.prototype.createSocket = function createSocket(req, options, cb) {
const oncreate = once((err, s) => {
if (err)
return cb(err);
if (!this.sockets[name]) {
this.sockets[name] = [];
}
this.sockets[name] ||= [];
this.sockets[name].push(s);
this.totalSocketCount++;
debug('sockets', name, this.sockets[name].length, this.totalSocketCount);
Expand Down
4 changes: 2 additions & 2 deletions lib/_http_client.js
Original file line number Diff line number Diff line change
Expand Up @@ -347,8 +347,8 @@ function ClientRequest(input, options, cb) {
opts = { ...optsWithoutSignal };
if (opts.socketPath) {
opts.path = opts.socketPath;
} else if (opts.path) {
opts.path = undefined;
} else {
opts.path &&= undefined;
}
}
if (typeof opts.createConnection === 'function') {
Expand Down
12 changes: 4 additions & 8 deletions lib/_http_server.js
Original file line number Diff line number Diff line change
Expand Up @@ -357,8 +357,7 @@ function writeHead(statusCode, reason, obj) {
this.statusMessage = reason;
} else {
// writeHead(statusCode[, headers])
if (!this.statusMessage)
this.statusMessage = STATUS_CODES[statusCode] || 'unknown';
this.statusMessage ||= STATUS_CODES[statusCode] || 'unknown';
obj ??= reason;
}
this.statusCode = statusCode;
Expand Down Expand Up @@ -510,9 +509,7 @@ function storeHTTPOptions(options) {

function setupConnectionsTracking() {
// Start connection handling
if (!this[kConnections]) {
this[kConnections] = new ConnectionsList();
}
this[kConnections] ||= new ConnectionsList();

if (this[kConnectionsCheckingInterval]) {
clearInterval(this[kConnectionsCheckingInterval]);
Expand Down Expand Up @@ -923,8 +920,7 @@ function onParserExecuteCommon(server, socket, parser, state, ret, d) {
const req = parser.incoming;
debug('SERVER upgrade or connect', req.method);

if (!d)
d = parser.getCurrentBuffer();
d ||= parser.getCurrentBuffer();

socket.removeListener('data', state.onData);
socket.removeListener('end', state.onEnd);
Expand Down Expand Up @@ -962,7 +958,7 @@ function onParserExecuteCommon(server, socket, parser, state, ret, d) {
}

function clearIncoming(req) {
req = req || this;
req ||= this;
const parser = req.socket?.parser;
// Reset the .incoming property so that the request object can be gc'ed.
if (parser && parser.incoming === req) {
Expand Down
5 changes: 2 additions & 3 deletions lib/_tls_common.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ const {
} = require('internal/tls/secure-context');

function toV(which, v, def) {
if (v == null) v = def;
v ??= def;
if (v === 'TLSv1') return TLS1_VERSION;
if (v === 'TLSv1.1') return TLS1_1_VERSION;
if (v === 'TLSv1.2') return TLS1_2_VERSION;
Expand Down Expand Up @@ -94,8 +94,7 @@ function SecureContext(secureProtocol, secureOptions, minVersion, maxVersion) {
}

function createSecureContext(options) {
if (!options) options = kEmptyObject;

options ||= kEmptyObject;
const {
honorCipherOrder,
minVersion,
Expand Down
2 changes: 1 addition & 1 deletion lib/_tls_wrap.js
Original file line number Diff line number Diff line change
Expand Up @@ -1328,7 +1328,7 @@ function Server(options, listener) {
listener = options;
options = kEmptyObject;
} else if (options == null || typeof options === 'object') {
options = options ?? kEmptyObject;
options ??= kEmptyObject;
} else {
throw new ERR_INVALID_ARG_TYPE('options', 'Object', options);
}
Expand Down
2 changes: 1 addition & 1 deletion lib/assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -750,7 +750,7 @@ function internalMatch(string, regexp, message, fn) {
const generatedMessage = !message;

// 'The input was expected to not match the regular expression ' +
message = message || (typeof string !== 'string' ?
message ||= (typeof string !== 'string' ?
'The "string" argument must be of type string. Received type ' +
`${typeof string} (${inspect(string)})` :
(match ?
Expand Down
2 changes: 1 addition & 1 deletion lib/async_hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ class AsyncResource {
}

static bind(fn, type, thisArg) {
type = type || fn.name;
type ||= fn.name;
return (new AsyncResource(type || 'bound-anonymous-fn')).bind(fn, thisArg);
}
}
Expand Down
22 changes: 8 additions & 14 deletions lib/child_process.js
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ function fork(modulePath, args = [], options) {
validateObject(options, 'options');
}
options = { __proto__: null, ...options, shell: false };
options.execPath = options.execPath || process.execPath;
options.execPath ||= process.execPath;
validateArgumentNullCheck(options.execPath, 'options.execPath');

// Prepare arguments for fork:
Expand Down Expand Up @@ -272,19 +272,15 @@ function normalizeExecFileArgs(file, args, options, callback) {
args = null;
}

if (args == null) {
args = [];
}
args ??= [];

if (typeof options === 'function') {
callback = options;
} else if (options != null) {
validateObject(options, 'options');
}

if (options == null) {
options = kEmptyObject;
}
options ??= kEmptyObject;

if (callback != null) {
validateFunction(callback, 'callback');
Expand Down Expand Up @@ -415,13 +411,11 @@ function execFile(file, args, options, callback) {
if (args?.length)
cmd += ` ${ArrayPrototypeJoin(args, ' ')}`;

if (!ex) {
ex = genericNodeError(`Command failed: ${cmd}\n${stderr}`, {
code: code < 0 ? getSystemErrorName(code) : code,
killed: child.killed || killed,
signal: signal,
});
}
ex ||= genericNodeError(`Command failed: ${cmd}\n${stderr}`, {
code: code < 0 ? getSystemErrorName(code) : code,
killed: child.killed || killed,
signal: signal,
});

ex.cmd = cmd;
callback(ex, stdout, stderr);
Expand Down
3 changes: 1 addition & 2 deletions lib/dgram.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,7 @@ const SEND_BUFFER = false;
// Lazily loaded
let _cluster = null;
function lazyLoadCluster() {
if (!_cluster) _cluster = require('cluster');
return _cluster;
return _cluster ??= require('cluster');
}

function Socket(type, listener) {
Expand Down
4 changes: 2 additions & 2 deletions lib/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ EventEmitter.init = function(opts) {
this[kShapeMode] = true;
}

this._maxListeners = this._maxListeners || undefined;
this._maxListeners ||= undefined;


if (opts?.captureRejections) {
Expand Down Expand Up @@ -457,7 +457,7 @@ EventEmitter.prototype.emit = function emit(type, ...args) {
if (events !== undefined) {
if (doError && events[kErrorMonitor] !== undefined)
this.emit(kErrorMonitor, ...args);
doError = (doError && events.error === undefined);
doError &&= events.error === undefined;
} else if (!doError)
return false;

Expand Down
5 changes: 1 addition & 4 deletions lib/internal/assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@

let error;
function lazyError() {
if (!error) {
error = require('internal/errors').codes.ERR_INTERNAL_ASSERTION;
}
return error;
return error ??= require('internal/errors').codes.ERR_INTERNAL_ASSERTION;
}

function assert(value, message) {
Expand Down
3 changes: 1 addition & 2 deletions lib/internal/bootstrap/switches/is_not_main_thread.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@ const {

let workerStdio;
function lazyWorkerStdio() {
if (!workerStdio) workerStdio = createWorkerStdio();
return workerStdio;
return workerStdio ??= createWorkerStdio();
}

function getStdout() { return lazyWorkerStdio().stdout; }
Expand Down
7 changes: 2 additions & 5 deletions lib/internal/child_process.js
Original file line number Diff line number Diff line change
Expand Up @@ -852,8 +852,7 @@ function setupChannel(target, channel, serializationMode) {

if (err === 0) {
if (handle) {
if (!this._handleQueue)
this._handleQueue = [];
this._handleQueue ||= [];
if (obj?.postSend)
obj.postSend(message, handle, options, callback, target);
}
Expand Down Expand Up @@ -1009,9 +1008,7 @@ function getValidStdio(stdio, sync) {
}

// Defaults
if (stdio == null) {
stdio = i < 3 ? 'pipe' : 'ignore';
}
stdio ??= i < 3 ? 'pipe' : 'ignore';

if (stdio === 'ignore') {
ArrayPrototypePush(acc, { type: 'ignore' });
Expand Down
4 changes: 1 addition & 3 deletions lib/internal/cluster/child.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,9 +167,7 @@ function rr(message, { indexesKey, index }, cb) {
let fakeHandle = null;

function ref() {
if (!fakeHandle) {
fakeHandle = setInterval(noop, TIMEOUT_MAX);
}
fakeHandle ||= setInterval(noop, TIMEOUT_MAX);
}

function unref() {
Expand Down
3 changes: 1 addition & 2 deletions lib/internal/cluster/primary.js
Original file line number Diff line number Diff line change
Expand Up @@ -301,8 +301,7 @@ function queryServer(worker, message) {
handles.set(key, handle);
}

if (!handle.data)
handle.data = message.data;
handle.data ||= message.data;

// Set custom server data
handle.add(worker, (errno, reply, handle) => {
Expand Down
6 changes: 2 additions & 4 deletions lib/internal/console/constructor.js
Original file line number Diff line number Diff line change
Expand Up @@ -203,8 +203,7 @@ ObjectDefineProperties(Console.prototype, {
enumerable: false,
configurable: true,
get() {
if (!stdout) stdout = object.stdout;
return stdout;
return stdout ||= object.stdout;
},
set(value) { stdout = value; },
},
Expand All @@ -213,8 +212,7 @@ ObjectDefineProperties(Console.prototype, {
enumerable: false,
configurable: true,
get() {
if (!stderr) { stderr = object.stderr; }
return stderr;
return stderr ||= object.stderr;
},
set(value) { stderr = value; },
},
Expand Down
Loading
Loading