Skip to content

Instantly share code, notes, and snippets.

@casschin
Created December 5, 2019 02:43
Show Gist options
  • Save casschin/4b77e945ebc66d3557ee12ab08011f19 to your computer and use it in GitHub Desktop.
Save casschin/4b77e945ebc66d3557ee12ab08011f19 to your computer and use it in GitHub Desktop.
reordering function
// function that will allow you to move an item within a list and will reposition the other items accordingly
type ListItem = {
label: string;
pos: number;
}
const list = [
{
label: "a",
pos: 0
},
{
label: "b",
pos: 1
},
{
label: "c",
pos: 2
},
{
label: "d",
pos: 3
},
{
label: "e",
pos: 4
},
{
label: "f",
pos: 5
},
{
label: "g",
pos: 6
},
{
label: "h",
pos: 7
}
];
function getIsBetweenRange(number: number, rangeStart: number, rangeEnd: number): boolean {
return (
number > Math.min(rangeStart, rangeEnd) &&
number < Math.max(rangeStart, rangeEnd)
);
}
function sortArrayOfObjectsByKey(array: ListItem[], sortKey: string, isAscending: boolean = true): ListItem[] {
return [...array].sort((a, b): number => {
const aValue = a[sortKey];
const bValue = b[sortKey];
if (aValue > bValue) return isAscending ? 1 : -1;
if (aValue < bValue) return isAscending ? -1 : 1;
return 0
})
}
function moveTo(array: ListItem[], from: number, to: number): ListItem[] {
// if item is not moving anywhere
// no changes are necessary
if (from === to) return array;
return array.map(item => {
const { label, pos } = item;
// if current item is the one that is explicitly moving
// set the new position
if (pos === from) {
return {
label,
pos: to
};
}
// if current item is within the range of movement
// or
// is in the position where the item is moving to
// shift it
if (getIsBetweenRange(pos, from, to) || pos === to) {
// if the moving item is moving up, shift other items down
// if the moving item is moving down, shift other items up
return { ...item, pos: from < to ? pos - 1 : pos + 1 };
}
// otherwise, the item is outside the range of movement
// keep it in its current position
return item;
});
}
const newList = moveTo(list, 2, 6);
sortArrayOfObjectsByKey(newList, 'pos').forEach(item => {
const { label, pos } = item;
console.log(label, pos);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment