From 7091275cbf22df06c275dcb475b8bcbc54016efe Mon Sep 17 00:00:00 2001 From: Joey Parrish Date: Thu, 13 Sep 2018 15:59:40 -0700 Subject: [PATCH] Replace indexOf with includes, startsWith This replaces almost every instance of indexOf on both String and Array. There are very few places where we really wanted an index. Mostly, indexOf was used to check for inclusion. Change-Id: I08e299768b6ffdb4bfc30b39b5d82a058c6d1b56 --- demo/asset_section.js | 8 ++--- demo/common/assets.js | 6 ++-- demo/common/controls.js | 4 +-- demo/info_section.js | 2 +- demo/service_worker.js | 5 ++- docs/tutorials/upgrade-v2-0.md | 2 +- docs/tutorials/upgrade-v2-1.md | 2 +- docs/tutorials/upgrade-v2-2.md | 2 +- karma.conf.js | 2 +- lib/cast/cast_receiver.js | 2 +- lib/cast/cast_sender.js | 6 ++-- lib/dash/content_protection.js | 2 +- lib/dash/dash_parser.js | 6 ++-- lib/hls/hls_parser.js | 7 ++-- lib/hls/manifest_text_parser.js | 9 +++-- lib/media/drm_engine.js | 31 ++++++++--------- lib/media/media_source_engine.js | 2 +- lib/media/streaming_engine.js | 2 +- lib/offline/offline_manifest_parser.js | 2 +- lib/player.js | 12 +++---- lib/polyfill/indexed_db.js | 2 +- lib/polyfill/input_event.js | 2 +- lib/polyfill/mediasource.js | 10 +++--- lib/text/ttml_text_parser.js | 12 +++---- lib/text/vtt_text_parser.js | 5 ++- lib/util/array_utils.js | 48 +++++--------------------- lib/util/object_utils.js | 6 ++-- lib/util/stream_utils.js | 6 ++-- test/cast/cast_receiver_integration.js | 6 ++-- test/cast/cast_receiver_unit.js | 14 ++++---- test/cast/cast_utils_unit.js | 6 ++-- test/hls/hls_live_unit.js | 2 +- test/media/drm_engine_unit.js | 2 +- test/media/media_source_engine_unit.js | 2 +- test/offline/storage_unit.js | 3 +- test/player_external.js | 6 ++-- test/player_unit.js | 4 +-- test/test/util/test_scheme.js | 2 +- test/util/array_utils_unit.js | 14 -------- 39 files changed, 107 insertions(+), 159 deletions(-) diff --git a/demo/asset_section.js b/demo/asset_section.js index d81ada013..724f9a541 100644 --- a/demo/asset_section.js +++ b/demo/asset_section.js @@ -66,13 +66,13 @@ shakaDemo.setupAssets_ = function() { } let mimeTypes = []; - if (asset.features.indexOf(shakaAssets.Feature.WEBM) >= 0) { + if (asset.features.includes(shakaAssets.Feature.WEBM)) { mimeTypes.push('video/webm'); } - if (asset.features.indexOf(shakaAssets.Feature.MP4) >= 0) { + if (asset.features.includes(shakaAssets.Feature.MP4)) { mimeTypes.push('video/mp4'); } - if (asset.features.indexOf(shakaAssets.Feature.MP2TS) >= 0) { + if (asset.features.includes(shakaAssets.Feature.MP2TS)) { mimeTypes.push('video/mp2t'); } if (!mimeTypes.some( @@ -348,7 +348,7 @@ shakaDemo.load = function() { } // Disallow the casting of offline content. - let isOffline = asset.manifestUri.indexOf('offline:') == 0; + let isOffline = asset.manifestUri.startsWith('offline:'); shakaDemo.controls_.allowCast(!isOffline); (asset.extraText || []).forEach(function(extraText) { diff --git a/demo/common/assets.js b/demo/common/assets.js index fde8d303f..ddd76428c 100644 --- a/demo/common/assets.js +++ b/demo/common/assets.js @@ -235,13 +235,13 @@ shakaAssets.UplynkResponseFilter = function(type, response) { shakaAssets.UplynkRequestFilter = function(type, request) { if (type == shaka.net.NetworkingEngine.RequestType.LICENSE) { // Modify the license request URL based on our cookie. - if (request.uris[0].indexOf('wv') !== -1 && + if (request.uris[0].includes('wv') && shakaAssets.uplynk_prefix) { request.uris[0] = shakaAssets.uplynk_prefix.concat('/wv'); - } else if (request.uris[0].indexOf('ck') !== -1 && + } else if (request.uris[0].includes('ck') && shakaAssets.uplynk_prefix) { request.uris[0] = shakaAssets.uplynk_prefix.concat('/ck'); - } else if (request.uris[0].indexOf('pr') !== -1 && + } else if (request.uris[0].includes('pr') && shakaAssets.uplynk_prefix) { request.uris[0] = shakaAssets.uplynk_prefix.concat('/pr'); } diff --git a/demo/common/controls.js b/demo/common/controls.js index 7eaab2e30..9708602fb 100644 --- a/demo/common/controls.js +++ b/demo/common/controls.js @@ -210,10 +210,10 @@ ShakaControls.prototype.onScreenRotation_ = function() { this.video_.readyState == 0 || this.castProxy_.isCasting()) return; - if (screen.orientation.type.indexOf('landscape') >= 0 && + if (screen.orientation.type.includes('landscape') && !document.fullscreenElement) { this.videoContainer_.requestFullscreen(); - } else if (screen.orientation.type.indexOf('portrait') >= 0 && + } else if (screen.orientation.type.includes('portrait') && document.fullscreenElement) { document.exitFullscreen(); } diff --git a/demo/info_section.js b/demo/info_section.js index 61804ecd1..beb0b9999 100644 --- a/demo/info_section.js +++ b/demo/info_section.js @@ -155,7 +155,7 @@ shakaDemo.updateTrackOptions_ = function(list, tracks, languageAndRole) { tracks = tracks.filter(function(track) { let langMatch = track.language == language; - let roleMatch = role == '' || track.roles.indexOf(role) > -1; + let roleMatch = role == '' || track.roles.includes(role); return langMatch && roleMatch; }); diff --git a/demo/service_worker.js b/demo/service_worker.js index e0f9643ed..16538aa5e 100644 --- a/demo/service_worker.js +++ b/demo/service_worker.js @@ -40,7 +40,7 @@ const CACHE_NAME = 'shaka-player-v2'; const CACHE_NAME_PREFIX = 'shaka-player'; -console.assert(CACHE_NAME.indexOf(CACHE_NAME_PREFIX) == 0, +console.assert(CACHE_NAME.startsWith(CACHE_NAME_PREFIX), 'Cache name does not match prefix!'); @@ -150,8 +150,7 @@ function onActivate(event) { // Return true on all the caches we want to clean up. // Note that caches are shared across the origin, so only remove // caches we are sure we created. - if (cacheName.indexOf(CACHE_NAME_PREFIX) == 0 && - cacheName != CACHE_NAME) { + if (cacheName.startsWith(CACHE_NAME_PREFIX) && cacheName != CACHE_NAME) { return true; } return false; diff --git a/docs/tutorials/upgrade-v2-0.md b/docs/tutorials/upgrade-v2-0.md index c2c98b5ac..67b5df5ec 100644 --- a/docs/tutorials/upgrade-v2-0.md +++ b/docs/tutorials/upgrade-v2-0.md @@ -500,7 +500,7 @@ function retryOnSpecificHttpErrorsCallback(error) { if (error.code == shaka.util.Error.Code.BAD_HTTP_STATUS) { var statusCode = error.data[1]; var retryCodes = [ 502, 503, 504, 520 ]; - if (retryCodes.indexOf(statusCode) >= 0) { + if (retryCodes.includes(statusCode)) { player.retryStreaming(); } } diff --git a/docs/tutorials/upgrade-v2-1.md b/docs/tutorials/upgrade-v2-1.md index b7cef76ab..e3624974e 100644 --- a/docs/tutorials/upgrade-v2-1.md +++ b/docs/tutorials/upgrade-v2-1.md @@ -293,7 +293,7 @@ function retryOnSpecificHttpErrorsCallback(error) { if (error.code == shaka.util.Error.Code.BAD_HTTP_STATUS) { var statusCode = error.data[1]; var retryCodes = [ 502, 503, 504, 520 ]; - if (retryCodes.indexOf(statusCode) >= 0) { + if (retryCodes.includes(statusCode)) { player.retryStreaming(); } } diff --git a/docs/tutorials/upgrade-v2-2.md b/docs/tutorials/upgrade-v2-2.md index c18f1e497..e179a2e25 100644 --- a/docs/tutorials/upgrade-v2-2.md +++ b/docs/tutorials/upgrade-v2-2.md @@ -177,7 +177,7 @@ function retryOnSpecificHttpErrorsCallback(error) { if (error.code == shaka.util.Error.Code.BAD_HTTP_STATUS) { var statusCode = error.data[1]; var retryCodes = [ 502, 503, 504, 520 ]; - if (retryCodes.indexOf(statusCode) >= 0) { + if (retryCodes.includes(statusCode)) { player.retryStreaming(); } } diff --git a/karma.conf.js b/karma.conf.js index 28cd7c632..667c784b5 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -44,7 +44,7 @@ module.exports = function(config) { // Find the settings JSON object in the command arguments var args = process.argv; - var settingsIndex = args.indexOf('--settings') + var settingsIndex = args.indexOf('--settings'); var settings = settingsIndex >= 0 ? JSON.parse(args[settingsIndex + 1]) : {}; if (settings.browsers && settings.browsers.length == 1 && diff --git a/lib/cast/cast_receiver.js b/lib/cast/cast_receiver.js index e47506846..4487bdeab 100644 --- a/lib/cast/cast_receiver.js +++ b/lib/cast/cast_receiver.js @@ -175,7 +175,7 @@ shaka.cast.CastReceiver.prototype.init_ = function() { // that don't exist, in uncompiled mode we check if the hosting browser is a // Chromecast before starting the receiver manager. We wouldn't do browser // detection except for debugging, so only do this in uncompiled mode. - let isChromecast = navigator.userAgent.indexOf('CrKey') >= 0; + let isChromecast = navigator.userAgent.includes('CrKey'); if (isChromecast) { manager.start(); } diff --git a/lib/cast/cast_sender.js b/lib/cast/cast_sender.js index caf1b8ef1..d6bca926a 100644 --- a/lib/cast/cast_sender.js +++ b/lib/cast/cast_sender.js @@ -320,7 +320,7 @@ shaka.cast.CastSender.prototype.get = function(targetName, property) { 'Unexpected target name'); const CastUtils = shaka.cast.CastUtils; if (targetName == 'video') { - if (CastUtils.VideoVoidMethods.indexOf(property) >= 0) { + if (CastUtils.VideoVoidMethods.includes(property)) { return this.remoteCall_.bind(this, targetName, property); } } else if (targetName == 'player') { @@ -334,10 +334,10 @@ shaka.cast.CastSender.prototype.get = function(targetName, property) { return () => undefined; } } - if (CastUtils.PlayerVoidMethods.indexOf(property) >= 0) { + if (CastUtils.PlayerVoidMethods.includes(property)) { return this.remoteCall_.bind(this, targetName, property); } - if (CastUtils.PlayerPromiseMethods.indexOf(property) >= 0) { + if (CastUtils.PlayerPromiseMethods.includes(property)) { return this.remoteAsyncCall_.bind(this, targetName, property); } if (CastUtils.PlayerGetterMethods[property]) { diff --git a/lib/dash/content_protection.js b/lib/dash/content_protection.js index 7472a34ab..407ab9cdd 100644 --- a/lib/dash/content_protection.js +++ b/lib/dash/content_protection.js @@ -333,7 +333,7 @@ shaka.dash.ContentProtection.parseElements_ = function(elems) { schemeUri = schemeUri.toLowerCase(); if (keyId) { keyId = keyId.replace(/-/g, '').toLowerCase(); - if (keyId.indexOf(' ') >= 0) { + if (keyId.includes(' ')) { throw new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, diff --git a/lib/dash/dash_parser.js b/lib/dash/dash_parser.js index 8f96d88ed..2a8b05661 100644 --- a/lib/dash/dash_parser.js +++ b/lib/dash/dash_parser.js @@ -669,7 +669,7 @@ shaka.dash.DashParser.prototype.parsePeriods_ = function( // See https://github.com/google/shaka-player/issues/963 let periodId = context.period.id; goog.asserts.assert(periodId, 'Period IDs should not be null!'); - if (this.periodIds_.indexOf(periodId) == -1) { + if (!this.periodIds_.includes(periodId)) { this.periodIds_.push(periodId); // If this is an update, call filterNewPeriod and add it to the manifest. @@ -1019,7 +1019,7 @@ shaka.dash.DashParser.prototype.parseAdaptationSet_ = function(context, elem) { // key. let channel; let language; - if (captionStr.indexOf('=') == -1) { + if (!captionStr.includes('=')) { channel = (captionId++).toString(); language = captionStr; } else { @@ -1396,7 +1396,7 @@ shaka.dash.DashParser.prototype.emsgSchemeIdUris_ = function( let schemeIdUris = emsgSchemeIdUris.slice(); for (let event of inBandEventStreams) { let schemeIdUri = event.getAttribute('schemeIdUri'); - if (schemeIdUris.indexOf(schemeIdUri) == -1) { + if (!schemeIdUris.includes(schemeIdUri)) { schemeIdUris.push(schemeIdUri); } } diff --git a/lib/hls/hls_parser.js b/lib/hls/hls_parser.js index c952fac8d..039152177 100644 --- a/lib/hls/hls_parser.js +++ b/lib/hls/hls_parser.js @@ -35,6 +35,7 @@ goog.require('shaka.media.SegmentReference'); goog.require('shaka.net.DataUriPlugin'); goog.require('shaka.net.NetworkingEngine'); goog.require('shaka.text.TextEngine'); +goog.require('shaka.util.ArrayUtils'); goog.require('shaka.util.DataViewReader'); goog.require('shaka.util.Error'); goog.require('shaka.util.Functional'); @@ -538,7 +539,7 @@ shaka.hls.HlsParser.prototype.createVariantsForTag_ = function(tag, playlist) { } // Remove this entry from the list of codecs that belong to audio/video. - codecs.splice(codecs.indexOf(textCodecs), 1); + shaka.util.ArrayUtils.remove(codecs, textCodecs); } let promises = mediaTags.map(function(tag) { @@ -1432,7 +1433,7 @@ shaka.hls.HlsParser.prototype.getStartTime_ = } else if (mimeType == 'video/mp2t') { return this.getStartTimeFromTsSegment_(responses[0].data); } else if (mimeType == 'application/mp4' || - mimeType.indexOf('text/') == 0) { + mimeType.startsWith('text/')) { return this.getStartTimeFromTextSegment_( mimeType, codecs, responses[0].data); } else { @@ -1993,7 +1994,7 @@ shaka.hls.HlsParser.widevineDrmParser_ = function(drmTag) { // Keep 'SAMPLE-AES-CENC' for backward compatibility. Deprecate it in a // future release. const VALID_METHODS = ['SAMPLE-AES', 'SAMPLE-AES-CTR', 'SAMPLE-AES-CENC']; - if (VALID_METHODS.indexOf(method) < 0) { + if (!VALID_METHODS.includes(method)) { shaka.log.error('Widevine in HLS is only supported with [', VALID_METHODS.join(', '), '], not', method); return null; diff --git a/lib/hls/manifest_text_parser.js b/lib/hls/manifest_text_parser.js index 354c82125..9bcdfa57a 100644 --- a/lib/hls/manifest_text_parser.js +++ b/lib/hls/manifest_text_parser.js @@ -75,7 +75,7 @@ shaka.hls.ManifestTextParser.prototype.parsePlaylist = function(data, uri) { // These tags won't actually be used, so don't increment the global id. this.globalId_ -= 1; - if (MEDIA_PLAYLIST_TAGS.indexOf(tag.name) >= 0) { + if (MEDIA_PLAYLIST_TAGS.includes(tag.name)) { playlistType = shaka.hls.PlaylistType.MEDIA; break; } else if (tag.name == 'EXT-X-STREAM-INF') { @@ -94,7 +94,7 @@ shaka.hls.ManifestTextParser.prototype.parsePlaylist = function(data, uri) { } let tag = this.parseTag_(lines[i]); - if (SEGMENT_TAGS.indexOf(tag.name) >= 0) { + if (SEGMENT_TAGS.includes(tag.name)) { if (playlistType != shaka.hls.PlaylistType.MEDIA) { // Only media playlists should contain segment tags throw new shaka.util.Error( @@ -142,8 +142,7 @@ shaka.hls.ManifestTextParser.prototype.parseSegments_ = lines.forEach((line) => { if (/^(#EXT)/.test(line)) { let tag = this.parseTag_(line); - if (shaka.hls.ManifestTextParser.MEDIA_PLAYLIST_TAGS - .indexOf(tag.name) >= 0) { + if (shaka.hls.ManifestTextParser.MEDIA_PLAYLIST_TAGS.includes(tag.name)) { playlistTags.push(tag); } else { segmentTags.push(tag); @@ -205,7 +204,7 @@ shaka.hls.ManifestTextParser.parseTag = function(id, word) { let data = blocks[2]; let attributes = []; - if (data && data.indexOf('=') >= 0) { + if (data && data.includes('=')) { let parser = new shaka.util.TextParser(data); let blockAttrs; diff --git a/lib/media/drm_engine.js b/lib/media/drm_engine.js index a70d76cef..c703ad043 100644 --- a/lib/media/drm_engine.js +++ b/lib/media/drm_engine.js @@ -757,7 +757,7 @@ shaka.media.DrmEngine.prototype.queryMediaKeys_ = function( if (this.destroyed_) return Promise.reject(); // TODO: Remove once Edge has released a fix for https://bit.ly/2IcEgv0 - let isEdge = navigator.userAgent.indexOf('Edge/') >= 0; + let isEdge = navigator.userAgent.includes('Edge/'); // Store the capabilities of the key system. let realConfig = mediaKeySystemAccess.getConfiguration(); @@ -1015,18 +1015,18 @@ shaka.media.DrmEngine.prototype.processDrmInfos_ = drmInfos.forEach((drmInfo) => { // Aliases: - const ArrayUtils = shaka.util.ArrayUtils; const Uint8ArrayUtils = shaka.util.Uint8ArrayUtils; // Build an array of unique license servers. - if (licenseServers.indexOf(drmInfo.licenseServerUri) == -1) { + if (!licenseServers.includes(drmInfo.licenseServerUri)) { licenseServers.push(drmInfo.licenseServerUri); } // Build an array of unique server certs. if (drmInfo.serverCertificate) { - if (ArrayUtils.indexOf(serverCerts, drmInfo.serverCertificate, - Uint8ArrayUtils.equal) == -1) { + const found = serverCerts.some( + (cert) => Uint8ArrayUtils.equal(cert, drmInfo.serverCertificate)); + if (!found) { serverCerts.push(drmInfo.serverCertificate); } } @@ -1034,8 +1034,9 @@ shaka.media.DrmEngine.prototype.processDrmInfos_ = // Build an array of unique init datas. if (drmInfo.initData) { drmInfo.initData.forEach((initDataOverride) => { - if (ArrayUtils.indexOf(initDatas, initDataOverride, - initDataOverrideEqual) == -1) { + const found = initDatas.some( + (initData) => initDataOverrideEqual(initData, initDataOverride)); + if (!found) { initDatas.push(initDataOverride); } }); @@ -1043,7 +1044,7 @@ shaka.media.DrmEngine.prototype.processDrmInfos_ = if (drmInfo.keyIds) { for (let i = 0; i < drmInfo.keyIds.length; ++i) { - if (keyIds.indexOf(drmInfo.keyIds[i]) == -1) { + if (!keyIds.includes(drmInfo.keyIds[i])) { keyIds.push(drmInfo.keyIds[i]); } } @@ -1114,9 +1115,7 @@ shaka.media.DrmEngine.prototype.loadOfflineSession_ = function(sessionId) { if (this.destroyed_) return; if (!present) { - let i = this.activeSessions_.indexOf(activeSession); - goog.asserts.assert(i >= 0, 'Session must be in the array'); - this.activeSessions_.splice(i, 1); + shaka.util.ArrayUtils.remove(this.activeSessions_, activeSession); this.onError_(new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, @@ -1136,9 +1135,7 @@ shaka.media.DrmEngine.prototype.loadOfflineSession_ = function(sessionId) { }.bind(this), function(error) { if (this.destroyed_) return; - let i = this.activeSessions_.indexOf(activeSession); - goog.asserts.assert(i >= 0, 'Session must be in the array'); - this.activeSessions_.splice(i, 1); + shaka.util.ArrayUtils.remove(this.activeSessions_, activeSession); this.onError_(new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, @@ -1353,7 +1350,7 @@ shaka.media.DrmEngine.prototype.unpackPlayReadyRequest_ = function(request) { let xml = shaka.util.StringUtils.fromUTF16( request.body, true /* littleEndian */, true /* noThrow */); - if (xml.indexOf('PlayReadyKeyMessage') == -1) { + if (!xml.includes('PlayReadyKeyMessage')) { // This does not appear to be a wrapped message as on IE and Edge. Some // clients do not need this unwrapping, so we will assume this is one of // them. Note that "xml" at this point probably looks like random garbage, @@ -1585,13 +1582,13 @@ shaka.media.DrmEngine.probeSupport = function() { // Edge bug: https://bit.ly/2IeKzho let sessionTypes = access.getConfiguration().sessionTypes; let persistentState = sessionTypes ? - sessionTypes.indexOf('persistent-license') >= 0 : false; + sessionTypes.includes('persistent-license') : false; // Tizen 3.0 doesn't support persistent licenses, but reports that it // does. It doesn't fail until you call update() with a license // response, which is way too late. // This is a work-around for #894. - if (navigator.userAgent.indexOf('Tizen 3') >= 0) { + if (navigator.userAgent.includes('Tizen 3')) { persistentState = false; } diff --git a/lib/media/media_source_engine.js b/lib/media/media_source_engine.js index f54913af0..e7d2a09ce 100644 --- a/lib/media/media_source_engine.js +++ b/lib/media/media_source_engine.js @@ -986,7 +986,7 @@ shaka.media.MediaSourceEngine.prototype.enqueueBlockingOperation_ = this.queues_[contentType].length == 1, 'Should be at most one item in queue!'); goog.asserts.assert( - allWaiters.indexOf(this.queues_[contentType][0].p) != -1, + allWaiters.includes(this.queues_[contentType][0].p), 'The item in queue should be one of our waiters!'); this.queues_[contentType].shift(); } diff --git a/lib/media/streaming_engine.js b/lib/media/streaming_engine.js index ffbaff847..27c89eeb0 100644 --- a/lib/media/streaming_engine.js +++ b/lib/media/streaming_engine.js @@ -1790,7 +1790,7 @@ shaka.media.StreamingEngine.prototype.parseEMSG_ = function( // See DASH sec. 5.10.3.3.1 // If a DASH client detects an event message box with a scheme that is not // defined in MPD, the client is expected to ignore it. - if (emsgSchemeIdUris.indexOf(schemeId) != -1) { + if (emsgSchemeIdUris.includes(schemeId)) { // See DASH sec. 5.10.4.1 // A special scheme in DASH used to signal manifest updates. if (schemeId == 'urn:mpeg:dash:event:2012') { diff --git a/lib/offline/offline_manifest_parser.js b/lib/offline/offline_manifest_parser.js index bc91c359c..4fc86801b 100644 --- a/lib/offline/offline_manifest_parser.js +++ b/lib/offline/offline_manifest_parser.js @@ -105,7 +105,7 @@ shaka.offline.OfflineManifestParser.prototype.onExpirationUpdated = function( let manifests = await cell.getManifests([uri.key()]); let manifest = manifests[0]; - let foundSession = manifest.sessionIds.indexOf(sessionId) >= 0; + let foundSession = manifest.sessionIds.includes(sessionId); let newExpiration = manifest.expiration == undefined || manifest.expiration > expiration; diff --git a/lib/player.js b/lib/player.js index 41d174074..ab3dece2f 100644 --- a/lib/player.js +++ b/lib/player.js @@ -1636,7 +1636,7 @@ shaka.Player.prototype.getTextTracks = function() { this.activeStreams_.get(currentPeriod, ContentType.TEXT)) .filter(function(track) { // Don't show any tracks that are being loaded still. - return this.loadingTextStreamIds_.indexOf(track.id) < 0; + return !this.loadingTextStreamIds_.includes(track.id); }.bind(this)); }; @@ -2412,7 +2412,7 @@ shaka.Player.prototype.defaultStreamingFailureCallback_ = function(error) { shaka.util.Error.Code.TIMEOUT, ]; - if (this.isLive() && retryErrorCodes.indexOf(error.code) >= 0) { + if (this.isLive() && retryErrorCodes.includes(error.code)) { error.severity = shaka.util.Error.Severity.RECOVERABLE; shaka.log.warning('Live streaming error. Retrying automatically...'); @@ -3206,7 +3206,7 @@ shaka.Player.prototype.onKeyStatus_ = function(keyStatusMap) { if (stream.keyId) { let keyStatus = keyStatusMap[isGlobalStatus ? '00' : stream.keyId]; variant.allowedByKeySystem = - !!keyStatus && restrictedStatuses.indexOf(keyStatus) < 0; + !!keyStatus && !restrictedStatuses.includes(keyStatus); } if (originalAllowed != variant.allowedByKeySystem) { @@ -3332,11 +3332,11 @@ shaka.Player.prototype.checkRestrictedVariants_ = function(variants) { if (stream.keyId) { let keyStatus = keyStatusMap[isGlobalStatus ? '00' : stream.keyId]; if (!keyStatus) { - if (missingKeys.indexOf(stream.keyId) < 0) { + if (!missingKeys.includes(stream.keyId)) { missingKeys.push(stream.keyId); } - } else if (restrictedStatuses.indexOf(keyStatus) >= 0) { - if (badKeyStatuses.indexOf(keyStatus) < 0) { + } else if (restrictedStatuses.includes(keyStatus)) { + if (!badKeyStatuses.includes(keyStatus)) { badKeyStatuses.push(keyStatus); } } diff --git a/lib/polyfill/indexed_db.js b/lib/polyfill/indexed_db.js index 0bd1f56ed..6e9a461f9 100644 --- a/lib/polyfill/indexed_db.js +++ b/lib/polyfill/indexed_db.js @@ -36,7 +36,7 @@ shaka.polyfill.IndexedDB.install = function() { shaka.log.debug('IndexedDB.install'); let agent = navigator.userAgent; - if (agent && agent.indexOf('CrKey') >= 0) { + if (agent && agent.includes('CrKey')) { shaka.log.debug('Removing IndexedDB from ChromeCast'); delete window.indexedDB; goog.asserts.assert( diff --git a/lib/polyfill/input_event.js b/lib/polyfill/input_event.js index 5d0453303..703847e36 100644 --- a/lib/polyfill/input_event.js +++ b/lib/polyfill/input_event.js @@ -40,7 +40,7 @@ shaka.polyfill.InputEvent.install = function() { // send a patch. // This matches IE11, but not Edge. Edge does not have this problem. - if (navigator.userAgent.indexOf('Trident/') < 0) { + if (!navigator.userAgent.includes('Trident/')) { // Not IE, so don't patch anything. return; } diff --git a/lib/polyfill/mediasource.js b/lib/polyfill/mediasource.js index 3dee9c8c7..b33d6f412 100644 --- a/lib/polyfill/mediasource.js +++ b/lib/polyfill/mediasource.js @@ -47,7 +47,7 @@ shaka.polyfill.MediaSource.install = function() { shaka.log.info('Patching Chromecast MSE bugs.'); // Chromecast cannot make accurate determinations via isTypeSupported. shaka.polyfill.MediaSource.patchCastIsTypeSupported_(); - } else if (navigator.vendor && navigator.vendor.indexOf('Apple') >= 0) { + } else if (navigator.vendor && navigator.vendor.includes('Apple')) { let version = navigator.appVersion; // TS content is broken on Safari in general. @@ -55,20 +55,20 @@ shaka.polyfill.MediaSource.install = function() { // and https://bugs.webkit.org/show_bug.cgi?id=165342 shaka.polyfill.MediaSource.rejectTsContent_(); - if (version.indexOf('Version/8') >= 0) { + if (version.includes('Version/8')) { // Safari 8 does not implement appendWindowEnd. If we ignore the // incomplete MSE implementation, some content (especially multi-period) // will fail to play correctly. The best we can do is blacklist Safari 8. shaka.log.info('Blacklisting Safari 8 MSE.'); shaka.polyfill.MediaSource.blacklist_(); - } else if (version.indexOf('Version/9') >= 0) { + } else if (version.includes('Version/9')) { shaka.log.info('Patching Safari 9 MSE bugs.'); // Safari 9 does not correctly implement abort() on SourceBuffer. // Calling abort() causes a decoder failure, rather than resetting the // decode timestamp as called for by the spec. // Bug filed: https://bugs.webkit.org/show_bug.cgi?id=160316 shaka.polyfill.MediaSource.stubAbort_(); - } else if (version.indexOf('Version/10') >= 0) { + } else if (version.includes('Version/10')) { shaka.log.info('Patching Safari 10 MSE bugs.'); // Safari 10 does not correctly implement abort() on SourceBuffer. // Calling abort() before appending a segment causes that segment to be @@ -78,7 +78,7 @@ shaka.polyfill.MediaSource.install = function() { // Safari 10 fires spurious 'updateend' events after endOfStream(). // Bug filed: https://bugs.webkit.org/show_bug.cgi?id=165336 shaka.polyfill.MediaSource.patchEndOfStreamEvents_(); - } else if (version.indexOf('Version/11') >= 0) { + } else if (version.includes('Version/11')) { shaka.log.info('Patching Safari 11 MSE bugs.'); // Safari 11 does not correctly implement abort() on SourceBuffer. // Calling abort() before appending a segment causes that segment to be diff --git a/lib/text/ttml_text_parser.js b/lib/text/ttml_text_parser.js index f0da023dc..d5c47cfa3 100644 --- a/lib/text/ttml_text_parser.js +++ b/lib/text/ttml_text_parser.js @@ -561,34 +561,34 @@ shaka.text.TtmlTextParser.addTextDecoration_ = function(cue, decoration) { for (let i = 0; i < values.length; i++) { switch (values[i]) { case 'underline': - if (cue.textDecoration.indexOf(Cue.textDecoration.UNDERLINE) < 0) { + if (!cue.textDecoration.includes(Cue.textDecoration.UNDERLINE)) { cue.textDecoration.push(Cue.textDecoration.UNDERLINE); } break; case 'noUnderline': - if (cue.textDecoration.indexOf(Cue.textDecoration.UNDERLINE) >= 0) { + if (cue.textDecoration.includes(Cue.textDecoration.UNDERLINE)) { shaka.util.ArrayUtils.remove(cue.textDecoration, Cue.textDecoration.UNDERLINE); } break; case 'lineThrough': - if (cue.textDecoration.indexOf(Cue.textDecoration.LINE_THROUGH) < 0) { + if (!cue.textDecoration.includes(Cue.textDecoration.LINE_THROUGH)) { cue.textDecoration.push(Cue.textDecoration.LINE_THROUGH); } break; case 'noLineThrough': - if (cue.textDecoration.indexOf(Cue.textDecoration.LINE_THROUGH) >= 0) { + if (cue.textDecoration.includes(Cue.textDecoration.LINE_THROUGH)) { shaka.util.ArrayUtils.remove(cue.textDecoration, Cue.textDecoration.LINE_THROUGH); } break; case 'overline': - if (cue.textDecoration.indexOf(Cue.textDecoration.OVERLINE) < 0) { + if (!cue.textDecoration.includes(Cue.textDecoration.OVERLINE)) { cue.textDecoration.push(Cue.textDecoration.OVERLINE); } break; case 'noOverline': - if (cue.textDecoration.indexOf(Cue.textDecoration.OVERLINE) >= 0) { + if (cue.textDecoration.includes(Cue.textDecoration.OVERLINE)) { shaka.util.ArrayUtils.remove(cue.textDecoration, Cue.textDecoration.OVERLINE); } diff --git a/lib/text/vtt_text_parser.js b/lib/text/vtt_text_parser.js index b9efbad39..e3d38f501 100644 --- a/lib/text/vtt_text_parser.js +++ b/lib/text/vtt_text_parser.js @@ -68,7 +68,7 @@ shaka.text.VttTextParser.prototype.parseMedia = function(data, time) { // In case the attempt below doesn't work out, assume an offset of 0. offset = 0; - if (blocks[0].indexOf('X-TIMESTAMP-MAP') >= 0) { + if (blocks[0].includes('X-TIMESTAMP-MAP')) { // https://bit.ly/2K92l7y // The 'X-TIMESTAMP-MAP' header is used in HLS to align text with // the rest of the media. @@ -181,8 +181,7 @@ shaka.text.VttTextParser.parseCue_ = function(text, timeOffset, regions) { } let id = null; - let index = text[0].indexOf('-->'); - if (index < 0) { + if (!text[0].includes('-->')) { id = text[0]; text.splice(0, 1); } diff --git a/lib/util/array_utils.js b/lib/util/array_utils.js index eebb444ec..24f2ad5ba 100644 --- a/lib/util/array_utils.js +++ b/lib/util/array_utils.js @@ -56,8 +56,8 @@ shaka.util.ArrayUtils.removeDuplicates = function(array, compareFn) { let result = []; for (const item of array) { - const idx = shaka.util.ArrayUtils.indexOf(result, item, compareFn); - if (idx == -1) { + const found = result.some((other) => compareFn(item, other)); + if (!found) { result.push(item); } } @@ -65,26 +65,6 @@ shaka.util.ArrayUtils.removeDuplicates = function(array, compareFn) { }; -/** - * Find an item in an array. For use when comparison of entries via == will - * not suffice. - * @param {!Array.} array - * @param {T} value - * @param {function(T, T): boolean} compareFn A function which will be used to - * compare items in the array. - * @return {number} The index, or -1 if not found. - * @template T - */ -shaka.util.ArrayUtils.indexOf = function(array, value, compareFn) { - for (let i = 0; i < array.length; ++i) { - if (compareFn(array[i], value)) { - return i; - } - } - return -1; -}; - - /** * Remove given element from array (assumes no duplicates). * @param {!Array.} array @@ -117,38 +97,26 @@ shaka.util.ArrayUtils.count = function(array, check) { }; -/** - * Create a copy of another array. - * - * @param {!Array.} array - * @return {!Array.} - * @template T - */ -shaka.util.ArrayUtils.copy = function(array) { - return array.map((x) => x); -}; - - /** * Determines if the given arrays contain the same elements. * * @param {!Array.} a * @param {!Array.} b - * @param {function(T, T):boolean=} comp + * @param {function(T, T):boolean=} compareFn * @return {boolean} * @template T */ -shaka.util.ArrayUtils.hasSameElements = function(a, b, comp = undefined) { - if (!comp) { - comp = shaka.util.ArrayUtils.defaultEquals; +shaka.util.ArrayUtils.hasSameElements = function(a, b, compareFn) { + if (!compareFn) { + compareFn = shaka.util.ArrayUtils.defaultEquals; } if (a.length != b.length) { return false; } - let copy = b.slice(0); + let copy = b.slice(); for (const item of a) { - const idx = shaka.util.ArrayUtils.indexOf(copy, item, comp); + const idx = copy.findIndex((other) => compareFn(item, other)); if (idx == -1) { return false; } diff --git a/lib/util/object_utils.js b/lib/util/object_utils.js index 0fe73ee72..2944d60ad 100644 --- a/lib/util/object_utils.js +++ b/lib/util/object_utils.js @@ -30,7 +30,7 @@ shaka.util.ObjectUtils = class { * @return {T} */ static cloneObject(arg) { - let seenObjects = []; + let seenObjects = new Set(); // This recursively clones the value |val|, using the captured variable // |seenObjects| to track the objects we have already cloned. let clone = function(val) { @@ -55,7 +55,7 @@ shaka.util.ObjectUtils = class { return val; } - if (seenObjects.indexOf(val) >= 0) { + if (seenObjects.has(val)) { return null; } @@ -64,7 +64,7 @@ shaka.util.ObjectUtils = class { return null; } - seenObjects.push(val); + seenObjects.add(val); let ret = isArray ? [] : {}; // Note |name| will equal a number for arrays. for (let name in val) { diff --git a/lib/util/stream_utils.js b/lib/util/stream_utils.js index 4c9964d15..dc0142d52 100644 --- a/lib/util/stream_utils.js +++ b/lib/util/stream_utils.js @@ -714,8 +714,8 @@ shaka.util.StreamUtils.filterStreamsByLanguageAndRole = function( shaka.util.StreamUtils.filterVariantsByRole_ = function(variants, preferredRole) { return variants.filter(function(variant) { - return (variant.audio && variant.audio.roles.indexOf(preferredRole) >= 0) || - (variant.video && variant.video.roles.indexOf(preferredRole) >= 0); + return (variant.audio && variant.audio.roles.includes(preferredRole)) || + (variant.video && variant.video.roles.includes(preferredRole)); }); }; @@ -731,7 +731,7 @@ shaka.util.StreamUtils.filterVariantsByRole_ = shaka.util.StreamUtils.filterTextStreamsByRole_ = function(textStreams, preferredRole) { return textStreams.filter(function(stream) { - return stream.roles.indexOf(preferredRole) >= 0; + return stream.roles.includes(preferredRole); }); }; diff --git a/test/cast/cast_receiver_integration.js b/test/cast/cast_receiver_integration.js index 1d6020702..78e93d63f 100644 --- a/test/cast/cast_receiver_integration.js +++ b/test/cast/cast_receiver_integration.js @@ -96,10 +96,10 @@ describe('CastReceiver', function() { // ability to use modern APIs there that may not be available on all of the // browsers our library supports. Because of this, CastReceiver tests will // only be run on Chrome and Chromecast. - isChromecast = navigator.userAgent.indexOf('CrKey') >= 0; - let isEdge = navigator.userAgent.indexOf('Edge/') >= 0; + isChromecast = navigator.userAgent.includes('CrKey'); + let isEdge = navigator.userAgent.includes('Edge/'); // Edge also has "Chrome/" in its user agent string. - isChrome = navigator.userAgent.indexOf('Chrome/') >= 0 && !isEdge; + isChrome = navigator.userAgent.includes('Chrome/') && !isEdge; // Don't do any more work here if the tests will not end up running. if (!isChromecast && !isChrome) return; diff --git a/test/cast/cast_receiver_unit.js b/test/cast/cast_receiver_unit.js index 1fae37113..b649e50a1 100644 --- a/test/cast/cast_receiver_unit.js +++ b/test/cast/cast_receiver_unit.js @@ -70,10 +70,10 @@ describe('CastReceiver', function() { // ability to use modern APIs there that may not be available on all of the // browsers our library supports. Because of this, CastReceiver tests will // only be run on Chrome and Chromecast. - isChromecast = navigator.userAgent.indexOf('CrKey') >= 0; - let isEdge = navigator.userAgent.indexOf('Edge/') >= 0; + isChromecast = navigator.userAgent.includes('CrKey'); + let isEdge = navigator.userAgent.includes('Edge/'); // Edge also has "Chrome/" in its user agent string. - isChrome = navigator.userAgent.indexOf('Chrome/') >= 0 && !isEdge; + isChrome = navigator.userAgent.includes('Chrome/') && !isEdge; // Don't do any more work here if the tests will not end up running. if (!isChromecast && !isChrome) return; @@ -800,8 +800,8 @@ describe('CastReceiver', function() { fakeIncomingMessage(message, mockGenericMessageBus); expect(mockGenericMessageBus.broadcast.calls.count()).toEqual(1); - expect(mockGenericMessageBus.broadcast.calls.argsFor(0)[0].indexOf( - '"requestId":0,"type":"MEDIA_STATUS"') != -1).toBe(true); + expect(mockGenericMessageBus.broadcast.calls.argsFor(0)[0].includes( + '"requestId":0,"type":"MEDIA_STATUS"')).toBe(true); })); it('play', checkAndRun(() => { @@ -894,10 +894,10 @@ describe('CastReceiver', function() { fakeIncomingMessage(message, mockGenericMessageBus); expect(mockGenericMessageBus.broadcast.calls.count()).toEqual(1); - expect(mockGenericMessageBus.broadcast.calls.argsFor(0)[0].indexOf( + expect(mockGenericMessageBus.broadcast.calls.argsFor(0)[0].includes( '"requestId":0,' + '"type":"INVALID_REQUEST",' + - '"reason":"INVALID_COMMAND"') != -1) + '"reason":"INVALID_COMMAND"')) .toBe(true); })); }); diff --git a/test/cast/cast_utils_unit.js b/test/cast/cast_utils_unit.js index 5f8fa09f5..2f4871c96 100644 --- a/test/cast/cast_utils_unit.js +++ b/test/cast/cast_utils_unit.js @@ -53,17 +53,17 @@ describe('CastUtils', function() { let playerMembers = Object.keys(shaka.Player.prototype).filter( function(name) { // Private members end with _. - return ignoredMembers.indexOf(name) < 0 && + return !ignoredMembers.includes(name) && name.substr(name.length - 1) != '_'; }); // To make debugging easier, don't check that they are equal; instead check // that neither has any extra entries. let extraCastMembers = castMembers.filter(function(name) { - return playerMembers.indexOf(name) < 0; + return !playerMembers.includes(name); }); let extraPlayerMembers = playerMembers.filter(function(name) { - return castMembers.indexOf(name) < 0; + return !castMembers.includes(name); }); expect(extraCastMembers).toEqual([]); expect(extraPlayerMembers).toEqual([]); diff --git a/test/hls/hls_live_unit.js b/test/hls/hls_live_unit.js index 0f0305e43..84786ded9 100644 --- a/test/hls/hls_live_unit.js +++ b/test/hls/hls_live_unit.js @@ -591,7 +591,7 @@ describe('HlsParser live', function() { fakeNetEngine.setResponseFilter(function(type, response) { // Simulate a redirect by changing the response URI - if (response.uri.indexOf('test:/redirected/') == 0) return; + if (response.uri.startsWith('test:/redirected/')) return; response.uri = response.uri.replace('test:/', 'test:/redirected/'); }); diff --git a/test/media/drm_engine_unit.js b/test/media/drm_engine_unit.js index 4f7149604..98ad092a1 100644 --- a/test/media/drm_engine_unit.js +++ b/test/media/drm_engine_unit.js @@ -1997,7 +1997,7 @@ describe('DrmEngine', function() { } function fakeRequestMediaKeySystemAccess(acceptableKeySystems, keySystem) { - if (acceptableKeySystems.indexOf(keySystem) < 0) { + if (!acceptableKeySystems.includes(keySystem)) { return Promise.reject(); } mockMediaKeySystemAccess.keySystem = keySystem; diff --git a/test/media/media_source_engine_unit.js b/test/media/media_source_engine_unit.js index 7791cd955..4a40ed1f8 100644 --- a/test/media/media_source_engine_unit.js +++ b/test/media/media_source_engine_unit.js @@ -1104,7 +1104,7 @@ describe('MediaSourceEngine', function() { function captureEvents(object, targetEventNames) { object.addEventListener.and.callFake(function(eventName, listener) { - if (targetEventNames.indexOf(eventName) != -1) { + if (targetEventNames.includes(eventName)) { object[eventName] = listener; } }); diff --git a/test/offline/storage_unit.js b/test/offline/storage_unit.js index 3fcf8b580..32262cddb 100644 --- a/test/offline/storage_unit.js +++ b/test/offline/storage_unit.js @@ -517,8 +517,7 @@ describe('Storage', function() { * * @type {!Array.} */ - const remainingProgress = - shaka.util.ArrayUtils.copy(expectedProgressSteps); + const remainingProgress = expectedProgressSteps.slice(); const progressCallback = (content, progress) => { expect(progress).toBeCloseTo(remainingProgress.shift()); diff --git a/test/player_external.js b/test/player_external.js index 53a13e906..31e9017ec 100644 --- a/test/player_external.js +++ b/test/player_external.js @@ -102,10 +102,10 @@ describe('Player', function() { if (asset.features) { let mimeTypes = []; - if (asset.features.indexOf(Feature.WEBM) >= 0) { + if (asset.features.includes(Feature.WEBM)) { mimeTypes.push('video/webm'); } - if (asset.features.indexOf(Feature.MP4) >= 0) { + if (asset.features.includes(Feature.MP4)) { mimeTypes.push('video/mp4'); } if (!mimeTypes.some( @@ -147,7 +147,7 @@ describe('Player', function() { await player.load(asset.manifestUri); if (asset.features) { - const isLive = asset.features.indexOf(Feature.LIVE) >= 0; + const isLive = asset.features.includes(Feature.LIVE); expect(player.isLive()).toEqual(isLive); } video.play(); diff --git a/test/player_unit.js b/test/player_unit.js index d8a2ac78a..f581f6c66 100644 --- a/test/player_unit.js +++ b/test/player_unit.js @@ -2392,7 +2392,7 @@ describe('Player', function() { beforeEach(function() { // overriding for good / bad codecs. window.MediaSource.isTypeSupported = function(mimeType) { - return mimeType.indexOf('good') >= 0; + return mimeType.includes('good'); }; }); @@ -3386,7 +3386,7 @@ describe('Player', function() { function stringContaining(substring) { return { asymmetricMatch: function(actual) { - return actual.indexOf(substring) >= 0; + return actual.includes(substring); }, }; } diff --git a/test/test/util/test_scheme.js b/test/test/util/test_scheme.js index 8efae2c0d..c2a938646 100644 --- a/test/test/util/test_scheme.js +++ b/test/test/util/test_scheme.js @@ -318,7 +318,7 @@ shaka.test.TestScheme.createManifests = function(shaka, suffix) { * @return {shaka.test.IStreamGenerator} */ function createStreamGenerator(metadata) { - if (metadata.segmentUri.indexOf('.ts') != -1) { + if (metadata.segmentUri.includes('.ts')) { return new windowShaka.test.TSVodStreamGenerator( metadata.segmentUri); } diff --git a/test/util/array_utils_unit.js b/test/util/array_utils_unit.js index 132f9ba39..2e4e45ac8 100644 --- a/test/util/array_utils_unit.js +++ b/test/util/array_utils_unit.js @@ -42,20 +42,6 @@ describe('ArrayUtils', function() { }); }); - describe('indexOf', function() { - it('will find a matching element', function() { - let arr = ['aaa', 'bbb', 'ccc']; - let comparator = function(a, b) { return a[0] === b[0]; }; - expect(ArrayUtils.indexOf(arr, 'bat', comparator)).toBe(1); - }); - - it('will return -1 if not found', function() { - let arr = ['aaa', 'bbb', 'ccc']; - let comparator = function(a, b) { return a[0] === b[0]; }; - expect(ArrayUtils.indexOf(arr, 'zoo', comparator)).toBe(-1); - }); - }); - describe('hasSameElements', function() { it('determines same elements', () => { expectEqual([], []);