diff --git a/lib/internal/event_target.js b/lib/internal/event_target.js index 8c4ea11a14ed8b..21d3774a586a7f 100644 --- a/lib/internal/event_target.js +++ b/lib/internal/event_target.js @@ -2,12 +2,13 @@ const { ArrayFrom, + Boolean, Error, Map, + NumberIsInteger, Object, Set, Symbol, - NumberIsNaN, SymbolToStringTag, } = primordials; @@ -15,10 +16,10 @@ const { codes: { ERR_INVALID_ARG_TYPE, ERR_EVENT_RECURSION, - ERR_OUT_OF_RANGE, ERR_MISSING_ARGS } } = require('internal/errors'); +const { validateInteger, validateObject } = require('internal/validators'); const { customInspectSymbol } = require('internal/util'); const { inspect } = require('util'); @@ -54,11 +55,10 @@ class Event { constructor(type, options) { - if (arguments.length === 0) { + if (arguments.length === 0) throw new ERR_MISSING_ARGS('type'); - } - if (options != null && typeof options !== 'object') - throw new ERR_INVALID_ARG_TYPE('options', 'object', options); + if (options != null) + validateObject(options, 'options'); const { cancelable, bubbles, composed } = { ...options }; this.#cancelable = !!cancelable; this.#bubbles = !!bubbles; @@ -80,7 +80,7 @@ class Event { return name; const opts = Object.assign({}, options, { - dept: options.depth === null ? null : options.depth - 1 + depth: NumberIsInteger(options.depth) ? options.depth - 1 : options.depth }); return `${name} ${inspect({ @@ -296,7 +296,7 @@ class EventTarget { this.#emitting.delete(event.type); event[kTarget] = undefined; - return event.defaultPrevented === true ? false : true; + return event.defaultPrevented !== true; } [customInspectSymbol](depth, options) { @@ -305,7 +305,7 @@ class EventTarget { return name; const opts = Object.assign({}, options, { - dept: options.depth === null ? null : options.depth - 1 + depth: NumberIsInteger(options.depth) ? options.depth - 1 : options.depth }); return `${name} ${inspect({}, opts)}`; @@ -350,9 +350,7 @@ class NodeEventTarget extends EventTarget { } setMaxListeners(n) { - if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { - throw new ERR_OUT_OF_RANGE('n', 'a non-negative number', n); - } + validateInteger(n, 'n', 0); this.#maxListeners = n; return this; } @@ -430,20 +428,13 @@ function validateListener(listener) { } function validateEventListenerOptions(options) { - if (typeof options === 'boolean') { - options = { capture: options }; - } - if (options == null || typeof options !== 'object') - throw new ERR_INVALID_ARG_TYPE('options', 'object', options); - const { - once = false, - capture = false, - passive = false, - } = options; + if (typeof options === 'boolean') + return { capture: options }; + validateObject(options, 'options'); return { - once: !!once, - capture: !!capture, - passive: !!passive, + once: Boolean(options.once), + capture: Boolean(options.capture), + passive: Boolean(options.passive), }; }