Localized Sort Scripting Service

Last modified by Vincent Massol on 2024/07/05 14:20

cogSorting service which takes into account accented letters and language specific sort rules
TypeJAR
Category
Developed by

Victor Rachieru

Rating
0 Votes
LicenseGNU Lesser General Public License 2.1

Success

Installable with the Extension Manager

Description

About

Description

Sorting service which takes into account accented letters and language specific sort rules

Usage

$services.localizationSort.sort($param1, $param2)
NameMandatoryDescription
$param1yesObject containing elements to be sorted. Can either be a list or a map.
$param2yesCode of the language of which rules to apply. Ex: 'en', 'fr', 'ro', 'ru', etc.

Examples

List

Say we have the following array of strings: 

#set ($arr = ['pêche', 'éléphant', 'âgé', 'compagnon', 'Frère', 'péché', 'âge', 'fruit', 'frere', 'Château'])

Using the default sort from $sorttool you will get the following result.
Which is not what you would expect, because the accented letters are always considered to be after the non-accented ones.
So you get the words that start with an accented letter at the end of the array.

#set ($arr = $sorttool.sort($arr)) ## => ['Château', 'Frère', 'compagnon', 'frere', 'fruit', 'péché', 'pêche', 'âge', 'âgé', 'éléphant']

Using the localization sort service and setting the desired language to 'en' you kinda' get what you want but not quite.
According to the rules of the French language, the following list is in the wrong order.
In French 'péché' should follow 'pêche' in a sorted list.
This is why you want to make sure that you set the right language for your scenario when using the service.

#set ($arr = $services.localizationSort.sort($arr, 'en')) ## => ['âge', 'âgé', 'Château', 'compagnon', 'éléphant', 'frere', 'Frère', 'fruit', 'péché', 'pêche']

When using the service set to 'fr' the array is sorted in the correct order.

#set ($arr = $services.localizationSort.sort($arr, 'fr')) ## => ['âge', 'âgé', 'Château', 'compagnon', 'éléphant', 'frere', 'Frère', 'fruit', 'pêche', 'péché']

Map

You can use the service to sort maps as well.

#set ($map = {'pêche':1, 'éléphant':2, 'âgé':3, 'compagnon':4, 'Frère':5, 'péché':6, 'âge':7, 'fruit':8, 'frere':9, 'Château':10})
#set ($map = $services.localizationSort.sort($map, 'fr')) ## => {âge=7, âgé=3, Château=10, compagnon=4, éléphant=2, frere=9, Frère=5, fruit=8, pêche=1, péché=6}

Prerequisites & Installation Instructions

We recommend using the Extension Manager to install this extension (Make sure that the text "Installable with the Extension Manager" is displayed at the top right location on this page to know if this extension can be installed with the Extension Manager).

You can also use the manual method which involves dropping the JAR file and all its dependencies into the WEB-INF/lib folder and restarting XWiki.

Get Connected