gpt4 book ai didi

javascript - 更好的做法 : Always get a range of 6 Items out of an array

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:37:08 24 4
gpt4 key购买 nike

我需要一些算法方面的帮助。

我想从数组中提取 6 项的范围。起点是给定的索引,如果可能的话,我想让项目在给定的索引之前和之后均匀地分开。

我已经做到了,但我正在寻找一种比仅仅移动范围更优雅的方法。我怎样才能改进我的代码?

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17];
const area = 7;
const currentIndex = 5;
const arrayLength = array.length;


let rangeBegin = currentIndex - Math.floor((area - 1) / 2);
let rangeEnd = currentIndex + Math.ceil((area - 1) / 2);

if (rangeBegin < 0) {
const offset = -rangeBegin;
rangeBegin += offset;
rangeEnd += offset;
}

if (rangeEnd >= arrayLength) {
const offset = rangeEnd - arrayLength;
rangeBegin -= offset;
rangeEnd -= offset;
}
slicedArray = array.slice(rangeBegin, rangeEnd);

console.log(slicedArray)

https://playcode.io/377252?tabs=script.js,preview,console

最佳答案

您可以通过减去一半大小来移动索引,并为负索引取最大值,为大于数组长度减去所需子数组大小的索引取最小值。

 value  array                           index  adj  max  min
----- ------------------------------ ----- --- --- ---
v
2 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 1 -1 0 0
[ ]

v
5 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 4 2 2 2
[ ]

vv
10 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 9 7 7 5
[ ]

function getSub(array, index, size) {
if (size >= array.length) return array;
var pivot = Math.floor(index - (size - 1) / 2),
max = Math.max(pivot, 0),
min = Math.min(max, array.length - size);
return array.slice(min, min + size);
}

console.log(...getSub([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1, 5));
console.log(...getSub([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 4, 5));
console.log(...getSub([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 9, 5));

console.log(...getSub([1, 2, 3, 4], 1, 5));
console.log(...getSub([1, 2, 3, 4], 4, 5));
console.log(...getSub([1, 2, 3, 4], 9, 5));

关于javascript - 更好的做法 : Always get a range of 6 Items out of an array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57070155/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com