I've tried posting this question on StackOverflow but they told me to try it here since it's not so specific. I'd like to know the name of the algorithm or technique of following implementation. I wonder if this thing present in standard libraries of other languages (my implementation is in Javascript).
Consider a function that takes collection/iterable and index which should return items that surround / are close to the index (including the item at the index). The number of returned items can be specified as well.
This is the output of the function:
const ary = [3, 4, 5, 7, 8, 20, 21, 23, 600, 120]
// Get item on index and four another items surrounding it
const result = getCollectionAround(ary, 5, 4)
// -> console.log(result)
[7, 8, 20, 21, 23]
The trick is to return items from this function even if the index is last / first one (which means getting item on last index and four before it). You should always be getting the correct amount of items back even if you're hitting the beginning/end of the array (this means that you have to make up for it by appending/prepending additional items).
This is the implementation
getCollectionAround(collection, referenceIndex, amount) {
const totalCount = collection.length
const requestedCount = Math.floor(totalCount * amount)
let startIndex = Math.max(0, Math.round(referenceIndex - (requestedCount / 2)))
if (startIndex + requestedCount > collection.length) {
startIndex = Math.max(0, collection.length - requestedCount - 1)
}
// NOTE: + 1 include last index
return collection.slice(startIndex, startIndex + 1 + requestedCount)
}
Thanks for any leads. The reason for asking is because I might be using this a lot and I'd rather use some lightweight JS library (or at least module from it) that would do this for me or maybe create my own package for it if there is none.