@dominicstop/utils
Version:
Yet another event emitter written in typescript.
36 lines (35 loc) • 976 B
JavaScript
export function getIndexInCyclicArray(count, index) {
return (index < 0)
? ((index % count) + count) % count
: index % count;
}
;
export function getItemInCyclicArray(array, index) {
if (array.length === 0) {
throw new Error("Array must not be empty");
}
;
const indexNormalized = getIndexInCyclicArray(array.length, index);
return array[indexNormalized];
}
;
export function copyArrayWithCyclicOffset(sourceArray, offset) {
if (sourceArray.length === 0) {
return [];
}
;
const normalizedOffset = getIndexInCyclicArray(sourceArray.length, offset);
if (normalizedOffset === 0) {
return sourceArray;
}
;
const newArray = [];
for (let index = 0; index < sourceArray.length; index++) {
const sourceIndex = index + normalizedOffset;
const element = sourceArray[sourceIndex % sourceArray.length];
newArray.push(element);
}
;
return newArray;
}
;