Skip to content

Instantly share code, notes, and snippets.

@ggsalas
Created May 28, 2019 13:52
Show Gist options
  • Save ggsalas/a4e96adaa74352173bf0d8d4b59e67de to your computer and use it in GitHub Desktop.
Save ggsalas/a4e96adaa74352173bf0d8d4b59e67de to your computer and use it in GitHub Desktop.
multiple selection array, inspired on selection of gmail list of emails
// Reusable function to select multimple itens
// with start and end element
// array: array of elements to select
// selection: previously selected elements
// start: first element selected
// end: last element selected
function multipleSelect(array, selection, start, end) {
const startIndex = array.findIndex(item => item == start)
const endIndex = array.findIndex(item => item == end)
const min = startIndex < endIndex
? selection.includes(start) ? startIndex + 1 : startIndex
: endIndex
const max = (startIndex > endIndex ? startIndex : endIndex) + 1
const currentSelection = array.slice(min, max)
const selectedItems = () => {
const itemsToAdd = currentSelection.filter(e => (
!selection.includes(e)
))
const itemsToRemove = currentSelection.filter(e => (
selection.includes(e)
))
if (itemsToAdd.length > itemsToRemove.length) {
return [...selection, ...itemsToAdd]
} else {
return selection.filter(e => (
!itemsToRemove.includes(e)
))
}
}
return selectedItems()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment