Skip to content

Commit 7178588

Browse files
author
Aviv Keller
authored
lib: prefer logical assignment
PR-URL: #55044 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Chemi Atlow <[email protected]> Reviewed-By: Yagiz Nizipli <[email protected]> Reviewed-By: Trivikram Kamat <[email protected]> Reviewed-By: LiviaMedeiros <[email protected]>
1 parent 09d10b5 commit 7178588

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

73 files changed

+177
-301
lines changed

benchmark/_http-benchmarkers.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ class TestDoubleBenchmarker {
110110
}
111111

112112
create(options) {
113-
process.env.duration = process.env.duration || options.duration || 5;
113+
process.env.duration ||= options.duration || 5;
114114

115115
const scheme = options.scheme || 'http';
116116
const env = {

benchmark/common.js

+4-6
Original file line numberDiff line numberDiff line change
@@ -113,8 +113,7 @@ class Benchmark {
113113
}
114114
const [, key, value] = match;
115115
if (configs[key] !== undefined) {
116-
if (!cliOptions[key])
117-
cliOptions[key] = [];
116+
cliOptions[key] ||= [];
118117
cliOptions[key].push(
119118
// Infer the type from the config object and parse accordingly
120119
typeof configs[key][0] === 'number' ? +value : value,
@@ -177,10 +176,9 @@ class Benchmark {
177176

178177
http(options, cb) {
179178
const http_options = { ...options };
180-
http_options.benchmarker = http_options.benchmarker ||
181-
this.config.benchmarker ||
182-
this.extra_options.benchmarker ||
183-
http_benchmarkers.default_http_benchmarker;
179+
http_options.benchmarker ||= this.config.benchmarker ||
180+
this.extra_options.benchmarker ||
181+
http_benchmarkers.default_http_benchmarker;
184182
http_benchmarkers.run(
185183
http_options, (error, code, used_benchmarker, result, elapsed) => {
186184
if (cb) {

benchmark/es/defaultparams-bench.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ const bench = common.createBenchmark(main, {
99
});
1010

1111
function oldStyleDefaults(x, y) {
12-
x = x || 1;
13-
y = y || 2;
12+
x ||= 1;
13+
y ||= 2;
1414
assert.strictEqual(x, 1);
1515
assert.strictEqual(y, 2);
1616
}

benchmark/perf_hooks/resourcetiming.js

+6-12
Original file line numberDiff line numberDiff line change
@@ -21,18 +21,12 @@ function createTimingInfo({
2121
finalConnectionTimingInfo = null,
2222
}) {
2323
if (finalConnectionTimingInfo !== null) {
24-
finalConnectionTimingInfo.domainLookupStartTime =
25-
finalConnectionTimingInfo.domainLookupStartTime || 0;
26-
finalConnectionTimingInfo.domainLookupEndTime =
27-
finalConnectionTimingInfo.domainLookupEndTime || 0;
28-
finalConnectionTimingInfo.connectionStartTime =
29-
finalConnectionTimingInfo.connectionStartTime || 0;
30-
finalConnectionTimingInfo.connectionEndTime =
31-
finalConnectionTimingInfo.connectionEndTime || 0;
32-
finalConnectionTimingInfo.secureConnectionStartTime =
33-
finalConnectionTimingInfo.secureConnectionStartTime || 0;
34-
finalConnectionTimingInfo.ALPNNegotiatedProtocol =
35-
finalConnectionTimingInfo.ALPNNegotiatedProtocol || [];
24+
finalConnectionTimingInfo.domainLookupStartTime ||= 0;
25+
finalConnectionTimingInfo.domainLookupEndTime ||= 0;
26+
finalConnectionTimingInfo.connectionStartTime ||= 0;
27+
finalConnectionTimingInfo.connectionEndTime ||= 0;
28+
finalConnectionTimingInfo.secureConnectionStartTime ||= 0;
29+
finalConnectionTimingInfo.ALPNNegotiatedProtocol ||= [];
3630
}
3731
return {
3832
startTime,

benchmark/zlib/deflate.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ const bench = common.createBenchmark(main, {
1010

1111
function main({ n, method, inputLen }) {
1212
// Default method value for testing.
13-
method = method || 'deflate';
13+
method ||= 'deflate';
1414
const chunk = Buffer.alloc(inputLen, 'a');
1515

1616
switch (method) {

benchmark/zlib/inflate.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ const bench = common.createBenchmark(main, {
1010

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

1616
let i = 0;

eslint.config.mjs

+1
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,7 @@ export default [
144144
ignorePattern: '.*',
145145
},
146146
}],
147+
'logical-assignment-operators': ['error', 'always', { enforceForIfStatements: true }],
147148
'default-case-last': 'error',
148149
'dot-notation': 'error',
149150
'eqeqeq': ['error', 'smart'],

lib/_http_agent.js

+3-9
Original file line numberDiff line numberDiff line change
@@ -246,9 +246,7 @@ Agent.prototype.addRequest = function addRequest(req, options, port/* legacy */,
246246
normalizeServerName(options, req);
247247

248248
const name = this.getName(options);
249-
if (!this.sockets[name]) {
250-
this.sockets[name] = [];
251-
}
249+
this.sockets[name] ||= [];
252250

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

291287
// Used to create sockets for pending requests from different origin
292288
req[kRequestOptions] = options;
@@ -313,9 +309,7 @@ Agent.prototype.createSocket = function createSocket(req, options, cb) {
313309
const oncreate = once((err, s) => {
314310
if (err)
315311
return cb(err);
316-
if (!this.sockets[name]) {
317-
this.sockets[name] = [];
318-
}
312+
this.sockets[name] ||= [];
319313
this.sockets[name].push(s);
320314
this.totalSocketCount++;
321315
debug('sockets', name, this.sockets[name].length, this.totalSocketCount);

lib/_http_client.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -347,8 +347,8 @@ function ClientRequest(input, options, cb) {
347347
opts = { ...optsWithoutSignal };
348348
if (opts.socketPath) {
349349
opts.path = opts.socketPath;
350-
} else if (opts.path) {
351-
opts.path = undefined;
350+
} else {
351+
opts.path &&= undefined;
352352
}
353353
}
354354
if (typeof opts.createConnection === 'function') {

lib/_http_server.js

+4-8
Original file line numberDiff line numberDiff line change
@@ -357,8 +357,7 @@ function writeHead(statusCode, reason, obj) {
357357
this.statusMessage = reason;
358358
} else {
359359
// writeHead(statusCode[, headers])
360-
if (!this.statusMessage)
361-
this.statusMessage = STATUS_CODES[statusCode] || 'unknown';
360+
this.statusMessage ||= STATUS_CODES[statusCode] || 'unknown';
362361
obj ??= reason;
363362
}
364363
this.statusCode = statusCode;
@@ -510,9 +509,7 @@ function storeHTTPOptions(options) {
510509

511510
function setupConnectionsTracking() {
512511
// Start connection handling
513-
if (!this[kConnections]) {
514-
this[kConnections] = new ConnectionsList();
515-
}
512+
this[kConnections] ||= new ConnectionsList();
516513

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

926-
if (!d)
927-
d = parser.getCurrentBuffer();
923+
d ||= parser.getCurrentBuffer();
928924

929925
socket.removeListener('data', state.onData);
930926
socket.removeListener('end', state.onEnd);
@@ -962,7 +958,7 @@ function onParserExecuteCommon(server, socket, parser, state, ret, d) {
962958
}
963959

964960
function clearIncoming(req) {
965-
req = req || this;
961+
req ||= this;
966962
const parser = req.socket?.parser;
967963
// Reset the .incoming property so that the request object can be gc'ed.
968964
if (parser && parser.incoming === req) {

lib/_tls_common.js

+2-3
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ const {
5757
} = require('internal/tls/secure-context');
5858

5959
function toV(which, v, def) {
60-
if (v == null) v = def;
60+
v ??= def;
6161
if (v === 'TLSv1') return TLS1_VERSION;
6262
if (v === 'TLSv1.1') return TLS1_1_VERSION;
6363
if (v === 'TLSv1.2') return TLS1_2_VERSION;
@@ -94,8 +94,7 @@ function SecureContext(secureProtocol, secureOptions, minVersion, maxVersion) {
9494
}
9595

9696
function createSecureContext(options) {
97-
if (!options) options = kEmptyObject;
98-
97+
options ||= kEmptyObject;
9998
const {
10099
honorCipherOrder,
101100
minVersion,

lib/_tls_wrap.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -1328,7 +1328,7 @@ function Server(options, listener) {
13281328
listener = options;
13291329
options = kEmptyObject;
13301330
} else if (options == null || typeof options === 'object') {
1331-
options = options ?? kEmptyObject;
1331+
options ??= kEmptyObject;
13321332
} else {
13331333
throw new ERR_INVALID_ARG_TYPE('options', 'Object', options);
13341334
}

lib/assert.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -750,7 +750,7 @@ function internalMatch(string, regexp, message, fn) {
750750
const generatedMessage = !message;
751751

752752
// 'The input was expected to not match the regular expression ' +
753-
message = message || (typeof string !== 'string' ?
753+
message ||= (typeof string !== 'string' ?
754754
'The "string" argument must be of type string. Received type ' +
755755
`${typeof string} (${inspect(string)})` :
756756
(match ?

lib/async_hooks.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,7 @@ class AsyncResource {
269269
}
270270

271271
static bind(fn, type, thisArg) {
272-
type = type || fn.name;
272+
type ||= fn.name;
273273
return (new AsyncResource(type || 'bound-anonymous-fn')).bind(fn, thisArg);
274274
}
275275
}

lib/child_process.js

+8-14
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ function fork(modulePath, args = [], options) {
138138
validateObject(options, 'options');
139139
}
140140
options = { __proto__: null, ...options, shell: false };
141-
options.execPath = options.execPath || process.execPath;
141+
options.execPath ||= process.execPath;
142142
validateArgumentNullCheck(options.execPath, 'options.execPath');
143143

144144
// Prepare arguments for fork:
@@ -272,19 +272,15 @@ function normalizeExecFileArgs(file, args, options, callback) {
272272
args = null;
273273
}
274274

275-
if (args == null) {
276-
args = [];
277-
}
275+
args ??= [];
278276

279277
if (typeof options === 'function') {
280278
callback = options;
281279
} else if (options != null) {
282280
validateObject(options, 'options');
283281
}
284282

285-
if (options == null) {
286-
options = kEmptyObject;
287-
}
283+
options ??= kEmptyObject;
288284

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

418-
if (!ex) {
419-
ex = genericNodeError(`Command failed: ${cmd}\n${stderr}`, {
420-
code: code < 0 ? getSystemErrorName(code) : code,
421-
killed: child.killed || killed,
422-
signal: signal,
423-
});
424-
}
414+
ex ||= genericNodeError(`Command failed: ${cmd}\n${stderr}`, {
415+
code: code < 0 ? getSystemErrorName(code) : code,
416+
killed: child.killed || killed,
417+
signal: signal,
418+
});
425419

426420
ex.cmd = cmd;
427421
callback(ex, stdout, stderr);

lib/dgram.js

+1-2
Original file line numberDiff line numberDiff line change
@@ -96,8 +96,7 @@ const SEND_BUFFER = false;
9696
// Lazily loaded
9797
let _cluster = null;
9898
function lazyLoadCluster() {
99-
if (!_cluster) _cluster = require('cluster');
100-
return _cluster;
99+
return _cluster ??= require('cluster');
101100
}
102101

103102
function Socket(type, listener) {

lib/events.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -338,7 +338,7 @@ EventEmitter.init = function(opts) {
338338
this[kShapeMode] = true;
339339
}
340340

341-
this._maxListeners = this._maxListeners || undefined;
341+
this._maxListeners ||= undefined;
342342

343343

344344
if (opts?.captureRejections) {
@@ -458,7 +458,7 @@ EventEmitter.prototype.emit = function emit(type, ...args) {
458458
if (events !== undefined) {
459459
if (doError && events[kErrorMonitor] !== undefined)
460460
this.emit(kErrorMonitor, ...args);
461-
doError = (doError && events.error === undefined);
461+
doError &&= events.error === undefined;
462462
} else if (!doError)
463463
return false;
464464

lib/internal/assert.js

+1-4
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,7 @@
22

33
let error;
44
function lazyError() {
5-
if (!error) {
6-
error = require('internal/errors').codes.ERR_INTERNAL_ASSERTION;
7-
}
8-
return error;
5+
return error ??= require('internal/errors').codes.ERR_INTERNAL_ASSERTION;
96
}
107

118
function assert(value, message) {

lib/internal/bootstrap/switches/is_not_main_thread.js

+1-2
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,7 @@ const {
3737

3838
let workerStdio;
3939
function lazyWorkerStdio() {
40-
if (!workerStdio) workerStdio = createWorkerStdio();
41-
return workerStdio;
40+
return workerStdio ??= createWorkerStdio();
4241
}
4342

4443
function getStdout() { return lazyWorkerStdio().stdout; }

lib/internal/child_process.js

+2-5
Original file line numberDiff line numberDiff line change
@@ -853,8 +853,7 @@ function setupChannel(target, channel, serializationMode) {
853853

854854
if (err === 0) {
855855
if (handle) {
856-
if (!this._handleQueue)
857-
this._handleQueue = [];
856+
this._handleQueue ||= [];
858857
if (obj?.postSend)
859858
obj.postSend(message, handle, options, callback, target);
860859
}
@@ -1010,9 +1009,7 @@ function getValidStdio(stdio, sync) {
10101009
}
10111010

10121011
// Defaults
1013-
if (stdio == null) {
1014-
stdio = i < 3 ? 'pipe' : 'ignore';
1015-
}
1012+
stdio ??= i < 3 ? 'pipe' : 'ignore';
10161013

10171014
if (stdio === 'ignore') {
10181015
ArrayPrototypePush(acc, { type: 'ignore' });

lib/internal/cluster/child.js

+1-3
Original file line numberDiff line numberDiff line change
@@ -167,9 +167,7 @@ function rr(message, { indexesKey, index }, cb) {
167167
let fakeHandle = null;
168168

169169
function ref() {
170-
if (!fakeHandle) {
171-
fakeHandle = setInterval(noop, TIMEOUT_MAX);
172-
}
170+
fakeHandle ||= setInterval(noop, TIMEOUT_MAX);
173171
}
174172

175173
function unref() {

lib/internal/cluster/primary.js

+1-2
Original file line numberDiff line numberDiff line change
@@ -301,8 +301,7 @@ function queryServer(worker, message) {
301301
handles.set(key, handle);
302302
}
303303

304-
if (!handle.data)
305-
handle.data = message.data;
304+
handle.data ||= message.data;
306305

307306
// Set custom server data
308307
handle.add(worker, (errno, reply, handle) => {

lib/internal/console/constructor.js

+2-4
Original file line numberDiff line numberDiff line change
@@ -201,8 +201,7 @@ ObjectDefineProperties(Console.prototype, {
201201
enumerable: false,
202202
configurable: true,
203203
get() {
204-
if (!stdout) stdout = object.stdout;
205-
return stdout;
204+
return stdout ||= object.stdout;
206205
},
207206
set(value) { stdout = value; },
208207
},
@@ -211,8 +210,7 @@ ObjectDefineProperties(Console.prototype, {
211210
enumerable: false,
212211
configurable: true,
213212
get() {
214-
if (!stderr) { stderr = object.stderr; }
215-
return stderr;
213+
return stderr ||= object.stderr;
216214
},
217215
set(value) { stderr = value; },
218216
},

0 commit comments

Comments
 (0)