It is necessary to create a function that would create an array with a repeating ending
I wrote such a function, but I understand that it is absolutely not optimal. Is it possible to solve the problem in another way?
const getArr = (arrayLength, patternLength, repeatedTailLength) => {
const arr = Array.from(Array(patternLength), (_, index) => index 1 );
const repeatedTailNumbers = arr.slice(patternLength - repeatedTailLength);
const tailsCount = Math.floor((arrayLength - patternLength) / repeatedTailLength);
const tailsOdd = arrayLength - (tailsCount * repeatedTailLength patternLength);
let result = [...arr];
for(let i = 1; i <= tailsCount; i ) {
result = [...result, ...repeatedTailNumbers]
}
for(let i = 0; i < tailsOdd; i ) {
result.push(repeatedTailNumbers[i]);
}
return result;
}
console.log(getArr(27, 9, 4));
[
1, 2, 3, 4, 5, 6, 7, 8, 9,
6, 7, 8, 9,
6, 7, 8, 9,
6, 7, 8, 9,
6, 7, 8, 9,
6, 7
]
CodePudding user response:
You could get the parts in advance and map the items.
const getArr = (arrayLength, patternLength, repeatedTailLength) => {
const
pattern = Array.from({ length: patternLength }, (_, i) => i 1),
tail = pattern.slice(-repeatedTailLength);
return Array.from(
{ length: arrayLength },
(_, i) => i < pattern.length
? pattern[i]
: tail[(i - pattern.length) % tail.length]
);
}
console.log(...getArr(26, 9, 4));
CodePudding user response:
var tr = (count, last, times) => {
let total = []
for (let i = 1; i <= count; i ) {
if(total.length == count) return total
if(i > last) i = i-times
total.push(i)
}
}
console.log(tr(26, 9, 4))