summaryrefslogtreecommitdiff
path: root/app/utils/kb-util.js
blob: aac88f9029673e39724b5ec204cc216bd75a80ed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
 * fast string manipulation utilities
 * for bi-lingual (EL/EN) words/phrases
 * based on the keyboard layout
 */

// suplamentary arrays (mostly for cache)
// --- -- -- - - -

var ORiGiNal = 'ςερτυθιοπασδφγηξκλζχψωβνμΕΡΤΥΘΙΟΠΑΣΔΦΓΗΞΚΛΖΧΨΩΒΝΜάέήίόύώϊΐϋΆΈΉΊΌΎΏΪΫQWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm0123456789- '.split('');

var kbKeyZed = 'sertyuiopasdfghjklzxcvbnmertyuiopasdfghjklzxcvbnmaehioyviiyaehioyviyqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnm0123456789- '.split('');

var map = new Map();
for (var i=0; i<ORiGiNal.length; i++) map.set(ORiGiNal[i], kbKeyZed[i]);


// cache (=create a global array)
// of accended to non-accended vowels mapping
// --- -- -- - - -
accented_vowels = [];   
[
    'ά α', 'έ ε', 'ή η', 'ί ι', 'ϊ ι', 'ΐ ι', 'ό ο', 'ύ υ', 'ϋ υ', 'ώ ω',
    'Ά Α', 'Έ Ε', 'Ή Η', 'Ί Ι', 'Ϊ Ι', 'Ό Ο', 'Ύ Υ', 'Ϋ Υ', 'Ώ Ω'
].forEach( pair => {
    ap = pair.split(' ');
    accented_vowels.push({
        a: ap[0],   // accented
        p: ap[1]    // pure = non accended
    });
});


// translates string to keyboard-latin keys
// (the ones that used whan typing each letter of the word)
const keyboardize = (str) => {
    str = str.replace('\'','');
    var out = '';
    // [map]'s implementation is 40x faster than [for]'s
    for (var i=0 ; i< str.length; i++)  out += map.get(str[i]);
    return out;
}

// keyboardize an array of strings
const keyb_array = (arr) => {
    kb_arr = [];
    arr.forEach( w => {
        kb_arr.push(keyboardize(w));
    });
    return kb_arr;
}


// transforms to lowercase; handles sigma-teliko
const sanitizeGR = (str) => {
    str = str.toLowerCase();

    // replace accended vowels with pure ones
    accented_vowels.forEach( v => {
        str = str.replaceAll(v.a, v.p);
    });

    // replace sigma on the end of words
    str = str + ' ';
    str = str.replaceAll('σ-', 'ς-');
    str = str.replaceAll('σ ', 'ς ');
    
    return str;
}

// removes non keyword characters [+ . , !] and internal multiple-spaces
// @param txt (string): product description
const clean = (txt) => {
    return txt.replace('+',' ').replace('.',' ').replace(',',' ')   // change to space
        .replace('!','').replace('\"', '')                  // remove character
        .replace('   ',' ').replace('  ',' ');          // remove multiple spaces
}


// exports
// --- -- -- - - -

module.exports = {
    keyboardize,
    keyb_array,
    sanitizeGR,
    clean
};