2022-09-09 18:44:52 -07:00
|
|
|
import type { PickAlgorithm } from './types';
|
|
|
|
|
|
|
|
type Opts = {
|
|
|
|
/** Number of iterations until the next item is picked. */
|
2023-02-15 13:26:27 -08:00
|
|
|
interval: number
|
2022-09-09 18:44:52 -07:00
|
|
|
};
|
|
|
|
|
2022-09-09 18:47:51 -07:00
|
|
|
/** Picks the next item every iteration. */
|
2022-09-09 20:26:36 -07:00
|
|
|
const linearAlgorithm: PickAlgorithm = (items, iteration, rawOpts) => {
|
|
|
|
const opts = normalizeOpts(rawOpts);
|
2022-09-13 09:57:28 -07:00
|
|
|
const itemIndex = items ? Math.floor(iteration / opts.interval) % items.length : 0;
|
2022-09-09 18:44:52 -07:00
|
|
|
const item = items ? items[itemIndex] : undefined;
|
2022-09-09 18:47:51 -07:00
|
|
|
const showItem = (iteration + 1) % opts.interval === 0;
|
2022-09-09 18:44:52 -07:00
|
|
|
|
|
|
|
return showItem ? item : undefined;
|
|
|
|
};
|
|
|
|
|
2022-09-09 20:26:36 -07:00
|
|
|
const normalizeOpts = (opts: unknown): Opts => {
|
|
|
|
const { interval } = (opts && typeof opts === 'object' ? opts : {}) as Record<any, unknown>;
|
|
|
|
|
|
|
|
return {
|
|
|
|
interval: typeof interval === 'number' ? interval : 20,
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
2022-09-09 18:44:52 -07:00
|
|
|
export {
|
|
|
|
linearAlgorithm,
|
|
|
|
};
|