@dominicstop/utils
Version:
Yet another event emitter written in typescript.
41 lines (40 loc) • 1.2 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getIndexInCyclicArray = getIndexInCyclicArray;
exports.getItemInCyclicArray = getItemInCyclicArray;
exports.copyArrayWithCyclicOffset = copyArrayWithCyclicOffset;
function getIndexInCyclicArray(count, index) {
return (index < 0)
? ((index % count) + count) % count
: index % count;
}
;
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];
}
;
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;
}
;