Allow to sort reverse

cf #698
This commit is contained in:
Yohan Boniface 2023-06-26 09:44:21 +02:00
parent 4c5fb43720
commit 1a8c6c846b
2 changed files with 58 additions and 2 deletions

View file

@ -202,7 +202,12 @@ L.Util.sortFeatures = (features, sortKey) => {
const sortKeys = (sortKey || 'name').split(',') const sortKeys = (sortKey || 'name').split(',')
const sort = (a, b, i) => { const sort = (a, b, i) => {
const sortKey = sortKeys[i] let sortKey = sortKeys[i],
reverse = 1
if (sortKey[0] === '-') {
reverse = -1
sortKey = sortKey.substring(1)
}
let score let score
const valA = a.properties[sortKey] || '' const valA = a.properties[sortKey] || ''
const valB = b.properties[sortKey] || '' const valB = b.properties[sortKey] || ''
@ -221,7 +226,7 @@ L.Util.sortFeatures = (features, sortKey) => {
}) })
} }
if (score === 0 && sortKeys[i + 1]) return sort(a, b, i + 1) if (score === 0 && sortKeys[i + 1]) return sort(a, b, i + 1)
return score return score * reverse
} }
features.sort((a, b) => { features.sort((a, b) => {

View file

@ -446,4 +446,55 @@ describe('L.Util', function () {
assert.ok(L.Util.usableOption({ key: null }, 'key')) assert.ok(L.Util.usableOption({ key: null }, 'key'))
}) })
}) })
describe("#sortFeatures()", function () {
let feat1, feat2, feat3
before(function () {
feat1 = {properties: {}}
feat2 = {properties: {}}
feat3 = {properties: {}}
})
it('should sort feature from custom key', function () {
feat1.properties.mykey = "13. foo"
feat2.properties.mykey = "7. foo"
feat3.properties.mykey = "111. foo"
let features = L.Util.sortFeatures([feat1, feat2, feat3], "mykey")
assert.equal(features[0], feat2)
assert.equal(features[1], feat1)
assert.equal(features[2], feat3)
})
it('should sort feature from multiple keys', function () {
feat1.properties.mykey = "13. foo"
feat2.properties.mykey = "111. foo"
feat3.properties.mykey = "111. foo"
feat1.properties.otherkey = "C"
feat2.properties.otherkey = "B"
feat3.properties.otherkey = "A"
let features = L.Util.sortFeatures([feat1, feat2, feat3], "mykey,otherkey")
assert.equal(features[0], feat1)
assert.equal(features[1], feat3)
assert.equal(features[2], feat2)
})
it('should sort feature from custom key reverse', function () {
feat1.properties.mykey = "13. foo"
feat2.properties.mykey = "7. foo"
feat3.properties.mykey = "111. foo"
let features = L.Util.sortFeatures([feat1, feat2, feat3], "-mykey")
assert.equal(features[0], feat3)
assert.equal(features[1], feat1)
assert.equal(features[2], feat2)
})
it('should sort feature from multiple keys with reverse', function () {
feat1.properties.mykey = "13. foo"
feat2.properties.mykey = "111. foo"
feat3.properties.mykey = "111. foo"
feat1.properties.otherkey = "C"
feat2.properties.otherkey = "B"
feat3.properties.otherkey = "A"
let features = L.Util.sortFeatures([feat1, feat2, feat3], "mykey,-otherkey")
assert.equal(features[0], feat1)
assert.equal(features[1], feat2)
assert.equal(features[2], feat3)
})
})
}) })