{"version":3,"file":"sorting.mjs","sources":["../../lib/utils/sorting.ts"],"sourcesContent":["/**\n * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors\n * SPDX-License-Identifier: AGPL-3.0-or-later\n */\n\nimport { getCanonicalLocale, getLanguage } from '@nextcloud/l10n'\n\ntype IdentifierFn<T> = (v: T) => unknown\nexport type SortingOrder = 'asc' | 'desc'\n\n/**\n * Helper to create string representation\n *\n * @param value Value to stringify\n */\nfunction stringify(value: unknown) {\n\t// The default representation of Date is not sortable because of the weekday names in front of it\n\tif (value instanceof Date) {\n\t\treturn value.toISOString()\n\t}\n\treturn String(value)\n}\n\n/**\n * Natural order a collection\n * You can define identifiers as callback functions, that get the element and return the value to sort.\n *\n * @param collection The collection to order\n * @param identifiers An array of identifiers to use, by default the identity of the element is used\n * @param orders Array of orders, by default all identifiers are sorted ascening\n */\nexport function orderBy<T>(collection: readonly T[], identifiers?: IdentifierFn<T>[], orders?: SortingOrder[]): T[] {\n\t// If not identifiers are set we use the identity of the value\n\tidentifiers = identifiers ?? [(value) => value]\n\t// By default sort the collection ascending\n\torders = orders ?? []\n\tconst sorting = identifiers.map((_, index) => (orders[index] ?? 'asc') === 'asc' ? 1 : -1)\n\n\tconst collator = Intl.Collator(\n\t\t[getLanguage(), getCanonicalLocale()],\n\t\t{\n\t\t\t// handle 10 as ten and not as one-zero\n\t\t\tnumeric: true,\n\t\t\tusage: 'sort',\n\t\t},\n\t)\n\n\treturn [...collection].sort((a, b) => {\n\t\tfor (const [index, identifier] of identifiers.entries()) {\n\t\t\t// Get the local compare of stringified value a and b\n\t\t\tconst value = collator.compare(stringify(identifier(a)), stringify(identifier(b)))\n\t\t\t// If they do not match return the order\n\t\t\tif (value !== 0) {\n\t\t\t\treturn value * sorting[index]\n\t\t\t}\n\t\t\t// If they match we need to continue with the next identifier\n\t\t}\n\t\t// If all are equal we need to return equality\n\t\treturn 0\n\t})\n}\n"],"names":[],"mappings":";AAeA,SAAS,UAAU,OAAgB;AAElC,MAAI,iBAAiB,MAAM;AAC1B,WAAO,MAAM,YAAA;AAAA,EACd;AACA,SAAO,OAAO,KAAK;AACpB;AAUO,SAAS,QAAW,YAA0B,aAAiC,QAA8B;AAEnH,gBAAc,eAAe,CAAC,CAAC,UAAU,KAAK;AAE9C,WAAS,UAAU,CAAA;AACnB,QAAM,UAAU,YAAY,IAAI,CAAC,GAAG,WAAW,OAAO,KAAK,KAAK,WAAW,QAAQ,IAAI,EAAE;AAEzF,QAAM,WAAW,KAAK;AAAA,IACrB,CAAC,YAAA,GAAe,oBAAoB;AAAA,IACpC;AAAA;AAAA,MAEC,SAAS;AAAA,MACT,OAAO;AAAA,IAAA;AAAA,EACR;AAGD,SAAO,CAAC,GAAG,UAAU,EAAE,KAAK,CAAC,GAAG,MAAM;AACrC,eAAW,CAAC,OAAO,UAAU,KAAK,YAAY,WAAW;AAExD,YAAM,QAAQ,SAAS,QAAQ,UAAU,WAAW,CAAC,CAAC,GAAG,UAAU,WAAW,CAAC,CAAC,CAAC;AAEjF,UAAI,UAAU,GAAG;AAChB,eAAO,QAAQ,QAAQ,KAAK;AAAA,MAC7B;AAAA,IAED;AAEA,WAAO;AAAA,EACR,CAAC;AACF;"}