-
Notifications
You must be signed in to change notification settings - Fork 0
/
bwt.js
58 lines (56 loc) · 1.23 KB
/
bwt.js
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
//Burrows-Wheeler transform
class BWT {
_sort(a,b){
for(let i=0;i<len;i++){
const diff = a[i].charCodeAt() - b[i].charCodeAt();
if(diff !== 0) return diff;
}
return 0;
}
//@TODO: limit str
static Transform(str){
const len = str.length;
const buff = str + str;
let sorted_arr_idx = [];
for(let i=0;i<len;i++){
sorted_arr_idx.push(i);
}
sorted_arr_idx.sort((x,y) =>{
for(let i=0;i<len;i++){
const diff = buff[x+i].charCodeAt() - buff[y+i].charCodeAt();
if(diff !== 0){return diff;}
}
return 0;
})
let pos;
let retStr = [];
for(let i=0;i<len;i++){
const ch_id = sorted_arr_idx[i];
if(ch_id === 0){
pos = i;
}
retStr.push(buff[ch_id + len -1]);
}
return [pos, retStr.join('')];
}
static InverseTransform([pos,str]){
const len = str.length;
let bwt_arr = Array.from(str);
let sorted_arr_idx = [];
for(let i=0;i<len;i++){
sorted_arr_idx.push(i);
}
sorted_arr_idx.sort((x,y) =>{
const diff = bwt_arr[x].charCodeAt() - bwt_arr[y].charCodeAt();
return diff === 0 ? x-y : diff ;
});
let p = sorted_arr_idx[pos];
let retStr = [];
for(let i=0;i<len;i++){
retStr.push(bwt_arr[p]);
p = sorted_arr_idx[p];
}
return retStr.join('');
}
}
module.exports = BWT;