UNPKG

typedash

Version:

modern, type-safe collection of utility functions

1 lines 2.69 kB
{"version":3,"file":"orderBy-Dx7yOnI6.cjs","names":["castArray"],"sources":["../src/functions/orderBy/orderBy.ts"],"sourcesContent":["import type { Primitive } from 'type-fest';\n\nimport type { KeysOfUnion, Many, Maybe } from '../../types';\nimport { castArray } from '../castArray';\n\n/**\n * Sorts an array of objects by one or more properties, in ascending or descending order.\n * @param array The array of objects to sort.\n * @param iterators The property or properties to sort by. Can be a key of `TValue` or a function that returns a comparable value.\n * @param orders The order or orders to sort by. Can be \"asc\" or \"desc\". Defaults to \"asc\".\n * @returns A new array of objects sorted by the specified properties and orders.\n */\nexport function orderBy<TValue>(\n array: Maybe<readonly TValue[]>,\n iterators: Many<OrderByIterator<TValue>>,\n orders?: Many<Order>\n): TValue[] {\n if (array == null) return [];\n\n const normalizedIteratees = castArray(iterators).map((iteratee) =>\n typeof iteratee === 'function'\n ? iteratee\n : (value: TValue) => value[iteratee]\n );\n\n const normalizedOrders = castArray(orders);\n\n return [...array].sort((a, b) => {\n for (const [index, iteratee] of normalizedIteratees.entries()) {\n const normalizedOrder = normalizedOrders[index] ?? 'asc';\n const order = normalizedOrder === 'desc' ? -1 : 1;\n\n const aValue = iteratee(a);\n const bValue = iteratee(b);\n\n if (\n // biome-ignore lint/style/noNonNullAssertion: JS can compare null and undefined using `<` and\n aValue! < bValue!\n ) {\n return -1 * order;\n }\n\n if (\n // biome-ignore lint/style/noNonNullAssertion: JS can compare null and undefined using `<` and\n aValue! > bValue!\n ) {\n return 1 * order;\n }\n }\n\n return 0;\n });\n}\n\ntype Order = 'asc' | 'desc';\n\ntype OrderByIterator<TValue> =\n | ((value: TValue) => ComparableValue)\n | KeysOfUnion<TValue>;\n\ntype ComparableValue =\n | Exclude<Primitive, symbol>\n | { [Symbol.toPrimitive](): Primitive }\n | { valueOf(): Primitive }\n | { toString(): string }\n | { [Symbol.toStringTag]: string };\n"],"mappings":";;;;;;;;;;AAYA,SAAgB,QACd,OACA,WACA,QACU;AACV,KAAI,SAAS,KAAM,QAAO,EAAE;CAE5B,MAAM,sBAAsBA,4BAAU,UAAU,CAAC,KAAK,aACpD,OAAO,aAAa,aAChB,YACC,UAAkB,MAAM,UAC9B;CAED,MAAM,mBAAmBA,4BAAU,OAAO;AAE1C,QAAO,CAAC,GAAG,MAAM,CAAC,MAAM,GAAG,MAAM;AAC/B,OAAK,MAAM,CAAC,OAAO,aAAa,oBAAoB,SAAS,EAAE;GAE7D,MAAM,SADkB,iBAAiB,UAAU,WACjB,SAAS,KAAK;GAEhD,MAAM,SAAS,SAAS,EAAE;GAC1B,MAAM,SAAS,SAAS,EAAE;AAE1B,OAEE,SAAU,OAEV,QAAO,KAAK;AAGd,OAEE,SAAU,OAEV,QAAO,IAAI;;AAIf,SAAO;GACP"}