Skip to content

Commit

Permalink
feat(time-ranges): make TimeRanges iteratable if Symbol.iterator exis…
Browse files Browse the repository at this point in the history
…ts (#7330)
  • Loading branch information
gkatsev authored Jul 27, 2021
1 parent 2ad4d60 commit ad9546c
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
22 changes: 16 additions & 6 deletions src/js/utils/time-ranges.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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');
Expand All @@ -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;
}

/**
Expand Down
19 changes: 19 additions & 0 deletions test/unit/utils/time-ranges.test.js
Original file line number Diff line number Diff line change
@@ -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');

Expand Down Expand Up @@ -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');
});

0 comments on commit ad9546c

Please sign in to comment.