Skip to content

Instantly share code, notes, and snippets.

@toky-nomena
Last active September 18, 2024 18:13
Show Gist options
  • Save toky-nomena/23ad9fe887b49a6b75a32330fd039191 to your computer and use it in GitHub Desktop.
Save toky-nomena/23ad9fe887b49a6b75a32330fd039191 to your computer and use it in GitHub Desktop.
function filterFn<T>(element: T | undefined): element is T {
return element !== undefined;
}
function sortMessagesByBindings(messages: (Message | null | undefined)[], bindings: string[]): Message[] {
// Helper function to get the last component of a string
const getLastComponent = (str: string): string => {
const parts = str.split('.');
return parts[parts.length - 1] || '';
};
// Create an array of last components from bindings
const bindingLastComponents = bindings.map(getLastComponent);
// Filter out falsy values, then sort messages based on the order of last components in bindings
return messages.filter(x => filterFn(x)).sort((a, b) => {
const aLast = getLastComponent(a.source);
const bLast = getLastComponent(b.source);
const aIndex = bindingLastComponents.indexOf(aLast);
const bIndex = bindingLastComponents.indexOf(bLast);
return aIndex === bIndex ? aLast.localeCompare(bLast) : aIndex - bIndex;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment