Skip to content

Commit 52d9ecf

Browse files
committed
feat(core utils): Add threshold_list helper for intersection observers.
1 parent 12c980b commit 52d9ecf

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

src/core/utils.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -689,6 +689,25 @@ const date_diff = (date_1, date_2) => {
689689
return Math.floor((utc_1 - utc_2) / _MS_PER_DAY);
690690
};
691691

692+
/**
693+
* Build intersection observer threshold list.
694+
*
695+
* See: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#building_the_array_of_threshold_ratios
696+
*
697+
* @param {Number} num_steps - The number of steps to use.
698+
*
699+
* @returns {Array} - Returns the threshold list.
700+
*/
701+
const threshold_list = (num_steps = 0) => {
702+
let thresholds = [];
703+
704+
for (let i = 1.0; i <= num_steps; i++) {
705+
thresholds.push(i / num_steps);
706+
}
707+
thresholds.push(0);
708+
return thresholds.sort();
709+
};
710+
692711
var utils = {
693712
jqueryPlugin: jqueryPlugin,
694713
escapeRegExp: escapeRegExp,
@@ -720,6 +739,7 @@ var utils = {
720739
is_iso_date_time: is_iso_date_time,
721740
is_iso_date: is_iso_date,
722741
date_diff: date_diff,
742+
threshold_list: threshold_list,
723743
getCSSValue: dom.get_css_value, // BBB: moved to dom. TODO: Remove in upcoming version.
724744
};
725745

src/core/utils.test.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -780,3 +780,34 @@ describe("date_diff ...", function () {
780780
expect(utils.date_diff(date_1, date_2)).toBe(1);
781781
});
782782
});
783+
784+
describe("threshold_list ...", function () {
785+
it("returns a list with 0 for num_steps 0", () => {
786+
expect(utils.threshold_list(0)).toEqual([0]);
787+
});
788+
789+
it("returns a list of thresholds for num_steps 2", () => {
790+
expect(utils.threshold_list(2)).toEqual([0, 0.5, 1]);
791+
});
792+
793+
it("returns a list of thresholds for num_steps 4", () => {
794+
expect(utils.threshold_list(4)).toEqual([0, 0.25, 0.5, 0.75, 1]);
795+
});
796+
797+
it("returns a list of thresholds for num_steps 5", () => {
798+
expect(utils.threshold_list(5)).toEqual([0, 0.2, 0.4, 0.6, 0.8, 1]);
799+
});
800+
801+
it("returns a list of thresholds for num_steps 10", () => {
802+
expect(utils.threshold_list(10)).toEqual([
803+
0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1,
804+
]);
805+
});
806+
807+
it("returns a list of thresholds for num_steps 20", () => {
808+
expect(utils.threshold_list(20)).toEqual([
809+
0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65,
810+
0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1,
811+
]);
812+
});
813+
});

0 commit comments

Comments
 (0)