From e2c961ab20319ca0732d5b435fe0ed305e0f3713 Mon Sep 17 00:00:00 2001 From: Gary Katsevman Date: Mon, 19 Jul 2021 18:41:44 -0400 Subject: [PATCH 1/2] feat(time-ranges): make iteratable if Symbo.iterator exists --- src/js/utils/time-ranges.js | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/js/utils/time-ranges.js b/src/js/utils/time-ranges.js index 392e0de617..0627eae45d 100644 --- a/src/js/utils/time-ranges.js +++ b/src/js/utils/time-ranges.js @@ -2,6 +2,7 @@ * @file time-ranges.js * @module time-ranges */ +import window from 'global/window'; /** * Returns the time for the specified index at the start or end @@ -94,8 +95,10 @@ function getRange(fnName, valueIndex, ranges, rangeIndex) { * An array of time ranges. */ function createTimeRangesObj(ranges) { + let timeRangesObj; + if (ranges === undefined || ranges.length === 0) { - return { + timeRangesObj = { length: 0, start() { throw new Error('This TimeRanges object is empty'); @@ -104,12 +107,19 @@ function createTimeRangesObj(ranges) { throw new Error('This TimeRanges object is empty'); } }; + } else { + timeRangesObj = { + length: ranges.length, + start: getRange.bind(null, 'start', 0, ranges), + end: getRange.bind(null, 'end', 1, ranges) + }; } - return { - length: ranges.length, - start: getRange.bind(null, 'start', 0, ranges), - end: getRange.bind(null, 'end', 1, ranges) - }; + + if (window.Symbol && window.Symbol.iterator) { + timeRangesObj[window.Symbol.iterator] = () => (ranges || []).values(); + } + + return timeRangesObj; } /** From f291a11687b0ce81295377629b95bd4c382c104a Mon Sep 17 00:00:00 2001 From: Gary Katsevman Date: Tue, 27 Jul 2021 12:11:03 -0400 Subject: [PATCH 2/2] add a small test for the TimeRange iterator --- test/unit/utils/time-ranges.test.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/test/unit/utils/time-ranges.test.js b/test/unit/utils/time-ranges.test.js index 9421c898be..3c40e779c8 100644 --- a/test/unit/utils/time-ranges.test.js +++ b/test/unit/utils/time-ranges.test.js @@ -1,5 +1,6 @@ /* eslint-env qunit */ import { createTimeRanges, createTimeRange } from '../../../src/js/utils/time-ranges.js'; +import window from 'global/window'; QUnit.module('time-ranges'); @@ -76,3 +77,21 @@ QUnit.test('should throw without being given an index', function(assert) { 'end throws if no index is given' ); }); + +let testOrSkip = 'skip'; + +if (window.Symbol && window.Symbol.iterator) { + testOrSkip = 'test'; +} +QUnit[testOrSkip]('Array.from works on our time ranges object', function(assert) { + const trRepresentation = [ + [0, 10], + [20, 30] + ]; + let tr = createTimeRanges(trRepresentation); + + assert.deepEqual(Array.from(tr), trRepresentation, 'we got back what we put in'); + + tr = createTimeRanges(0, 10); + assert.deepEqual(Array.from(tr), [[0, 10]], 'we got back a ranges representation'); +});