Skip to content

Instantly share code, notes, and snippets.

@martianboy
Last active October 5, 2016 14:01
Show Gist options
  • Save martianboy/fe21a220451da7d266ad807f6810c00f to your computer and use it in GitHub Desktop.
Save martianboy/fe21a220451da7d266ad807f6810c00f to your computer and use it in GitHub Desktop.
تابع مقایسه رشته فارسی با رعایت ترتیب الفبایی حروف.
function persian_alphabetic_compare(s1, s2) {
const persian_alphabet_fix_map = {
'ؤ': 1608.5,
'ئ': 1609.5,
'پ': 1577,
'ة': 1607.5,
'ژ': 1586.5,
'ک': 1603,
'چ': 1580.5,
'گ': 1603.5,
'ی': 1610
}
function compare_char_at_index(i) {
if (i >= s1.length && i >= s2.length) return 0;
if (i >= s1.length) return -1;
if (i >= s2.length) return 1;
const cmp_value =
(persian_alphabet_fix_map[s1[i]] || s1.charCodeAt(i)) -
(persian_alphabet_fix_map[s2[i]] || s2.charCodeAt(i));
if (!cmp_value) return compare_char_at_index(i + 1);
return cmp_value;
}
return compare_char_at_index(0);
}
['پاوه', 'تهران', 'بهشهر', 'گرگان', 'کرمانشاه', 'کردکوی', 'یاسوج', 'اهواز'].sort(persian_alphabetic_compare);
// => ["اهواز", "بهشهر", "پاوه", "تهران", "کردکوی", "کرمانشاه", "گرگان", "یاسوج"]
  • Ignore special characters like Arabic diacritics, ZWNJ, RTL & LTR marks, etc.
  • Ignore difference between Arabic and Persian number sets.
  • Add a test suite.
  • What to do with 0x06C0 (Arabic letter Heh with Yeh above)?
@martianboy
Copy link
Author

There's a NPM package for this function now with improved functionality.

https://www.npmjs.com/package/persian-alphabetic-compare

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment