diff --git a/server/src/utils/distributedCopy.js b/server/src/utils/distributedCopy.js new file mode 100644 index 0000000..101c6e3 --- /dev/null +++ b/server/src/utils/distributedCopy.js @@ -0,0 +1,25 @@ +/** + * Retrieve a fixed number of elements from an array, evenly distributed but + * always including the first and last elements. + * + * @param {Array} items - The array to operate on. + * @param {number} take - The number of elements to extract. + * @returns {Array} + */ +export function distributedCopy(items, take) { + if (items.length < take) { + return items + } + + const elements = [items[0]] + const totalItems = items.length - 2 + const interval = Math.floor(totalItems / (take - 2)) + + for (let i = 1; i < take - 1; i++) { + elements.push(items[i * interval]) + } + + elements.push(items[items.length - 1]) + + return elements +}