mirror of
https://github.com/harttle/liquidjs.git
synced 2026-09-16 04:40:39 -07:00
fix: stable sort for undefined keys, fixes #191
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
const toLowerCase = String.prototype.toLowerCase
|
||||
import { caseInsensitiveCompare } from '../../util/underscore'
|
||||
|
||||
export default {
|
||||
'abs': (v: number) => Math.abs(v),
|
||||
@@ -18,22 +18,12 @@ export default {
|
||||
'times': (v: number, arg: number) => v * arg
|
||||
}
|
||||
|
||||
function caseInsensitiveCmp (a: any, b: any) {
|
||||
if (!b) return -1
|
||||
if (!a) return 1
|
||||
a = toLowerCase.call(a)
|
||||
b = toLowerCase.call(b)
|
||||
if (a < b) return -1
|
||||
if (a > b) return 1
|
||||
return 0
|
||||
}
|
||||
|
||||
function sortNatural (input: any[], property?: string) {
|
||||
if (!input || !input.sort) return []
|
||||
if (property !== undefined) {
|
||||
return [...input].sort(
|
||||
(lhs, rhs) => caseInsensitiveCmp(lhs[property], rhs[property])
|
||||
(lhs, rhs) => caseInsensitiveCompare(lhs[property], rhs[property])
|
||||
)
|
||||
}
|
||||
return [...input].sort(caseInsensitiveCmp)
|
||||
return [...input].sort(caseInsensitiveCompare)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Drop } from '../drop/drop'
|
||||
|
||||
const toStr = Object.prototype.toString
|
||||
const toLowerCase = String.prototype.toLowerCase
|
||||
|
||||
/*
|
||||
* Checks if value is classified as a String primitive or object.
|
||||
@@ -127,3 +128,15 @@ export function changeCase (str: string): string {
|
||||
export function ellipsis (str: string, N: number): string {
|
||||
return str.length > N ? str.substr(0, N - 3) + '...' : str
|
||||
}
|
||||
|
||||
// compare string in case-insensitive way, undefined values to the tail
|
||||
export function caseInsensitiveCompare (a: any, b: any) {
|
||||
if (a == null && b == null) return 0
|
||||
if (a == null) return 1
|
||||
if (b == null) return -1
|
||||
a = toLowerCase.call(a)
|
||||
b = toLowerCase.call(b)
|
||||
if (a < b) return -1
|
||||
if (a > b) return 1
|
||||
return 0
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user