Skip to content

Commit

Permalink
Add translation support to custom alphabet
Browse files Browse the repository at this point in the history
  • Loading branch information
lauriro committed Oct 2, 2014
1 parent 3583384 commit e0799c5
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
8 changes: 8 additions & 0 deletions README.md
Expand Up @@ -94,6 +94,9 @@ a.sort(function(a, b){
It is possible to configure a custom alphabet
to achieve a desired order.

At the end of alphabet after "\b" can be a translation table
when some letters needs to be equal.

```javascript
// Estonian alphabet
String.alphabet = "ABDEFGHIJKLMNOPRSŠZŽTUVÕÄÖÜXYabdefghijklmnoprsšzžtuvõäöüxy"
Expand All @@ -104,6 +107,11 @@ String.alphabet = "ABDEFGHIJKLMNOPRSŠZŽTUVÕÄÖÜXYabdefghijklmnoprsšzžtuv
String.alphabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя"
["Ё", "А", "Б"].sort(String.naturalCompare)
// ["А", "Б", "Ё"]

// Spanish alphabet
String.alphabet = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZabcdefghijklmnñopqrstuvwxyz\bÁAÉEÍIÓOÚUÜUáaéeíióoúuüu"
["á3", "a2", "á1", "piñata", "pinza"].sort(String.naturalCompare)
// ["á1", "a2", "á3", "pinza", "piñata"]
```


Expand Down
10 changes: 8 additions & 2 deletions index.js
Expand Up @@ -16,14 +16,20 @@ String.naturalCompare = function(a, b) {
, posA = 0
, posB = 0
, alphabet = String.alphabet
, tr = alphabet && alphabet.split("\b")[1]

function getCode(str, pos, code) {
if (code) {
for (i = pos; code = getCode(str, i), code < 76 && code > 65;) ++i;
return +str.slice(pos - 1, i)
}
code = alphabet && alphabet.indexOf(str.charAt(pos))
return code > -1 ? code + 76 : ((code = str.charCodeAt(pos) || 0), code < 45 || code > 127) ? code

str = tr && str && (code = tr.indexOf(str) + 1) % 2 ?
tr.charAt(code) :
str.charAt(pos)

code = alphabet && alphabet.indexOf(str)
return code > -1 ? code + 76 : ((code = str.charCodeAt() || 0), code < 45 || code > 127) ? code
: code < 46 ? 65 // -
: code < 48 ? code - 1
: code < 58 ? code + 18 // 0-9
Expand Down

0 comments on commit e0799c5

Please sign in to comment.