This commit is contained in:
Douglas Barone 2022-06-20 12:40:49 +00:00
parent 3e9005f542
commit 2c6405edc9

View File

@ -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
}