Skip to content

Instantly share code, notes, and snippets.

@mbilalsiddique1
Created October 9, 2024 10:12
Show Gist options
  • Save mbilalsiddique1/5fd84a417f4b4a9f25ca5737a976ba50 to your computer and use it in GitHub Desktop.
Save mbilalsiddique1/5fd84a417f4b4a9f25ca5737a976ba50 to your computer and use it in GitHub Desktop.
Flexible Array and String Sort Utility
function sort(input, ...sortArgs) {
// Handles both null and undefined
if (input == null) return [];
if (typeof input === 'string') {
return input.split(',').sort(...sortArgs);
}
if (Array.isArray(input)) {
return input.slice().sort(...sortArgs);
}
console.error("Input must be a string, array, null, or undefined");
}
// const result1 = sort("Blue,Humpback,Beluga");
// console.log(result1);
// const result2 = sort([42, 7, 18, 92]);
// console.log(result2);
// const result3 = sort([42, 7, 18, 92], (a, b) => b - a);
// console.log(result3);
// const result4 = sort(null);
// console.log(result4);
// const result5 = sort(undefined);
// console.log(result5);
// sort(123);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment