[79a0317] | 1 | 'use strict';
|
---|
| 2 |
|
---|
| 3 | function Sorter() {
|
---|
| 4 | }
|
---|
| 5 |
|
---|
| 6 | Sorter.prototype.sort = function(tokens, fromIndex) {
|
---|
| 7 | fromIndex = fromIndex || 0;
|
---|
| 8 | for (var i = 0, len = this.keys.length; i < len; i++) {
|
---|
| 9 | var key = this.keys[i];
|
---|
| 10 | var token = key.slice(1);
|
---|
| 11 | var index = tokens.indexOf(token, fromIndex);
|
---|
| 12 | if (index !== -1) {
|
---|
| 13 | do {
|
---|
| 14 | if (index !== fromIndex) {
|
---|
| 15 | tokens.splice(index, 1);
|
---|
| 16 | tokens.splice(fromIndex, 0, token);
|
---|
| 17 | }
|
---|
| 18 | fromIndex++;
|
---|
| 19 | } while ((index = tokens.indexOf(token, fromIndex)) !== -1);
|
---|
| 20 | return this[key].sort(tokens, fromIndex);
|
---|
| 21 | }
|
---|
| 22 | }
|
---|
| 23 | return tokens;
|
---|
| 24 | };
|
---|
| 25 |
|
---|
| 26 | function TokenChain() {
|
---|
| 27 | }
|
---|
| 28 |
|
---|
| 29 | TokenChain.prototype = {
|
---|
| 30 | add: function(tokens) {
|
---|
| 31 | var self = this;
|
---|
| 32 | tokens.forEach(function(token) {
|
---|
| 33 | var key = '$' + token;
|
---|
| 34 | if (!self[key]) {
|
---|
| 35 | self[key] = [];
|
---|
| 36 | self[key].processed = 0;
|
---|
| 37 | }
|
---|
| 38 | self[key].push(tokens);
|
---|
| 39 | });
|
---|
| 40 | },
|
---|
| 41 | createSorter: function() {
|
---|
| 42 | var self = this;
|
---|
| 43 | var sorter = new Sorter();
|
---|
| 44 | sorter.keys = Object.keys(self).sort(function(j, k) {
|
---|
| 45 | var m = self[j].length;
|
---|
| 46 | var n = self[k].length;
|
---|
| 47 | return m < n ? 1 : m > n ? -1 : j < k ? -1 : j > k ? 1 : 0;
|
---|
| 48 | }).filter(function(key) {
|
---|
| 49 | if (self[key].processed < self[key].length) {
|
---|
| 50 | var token = key.slice(1);
|
---|
| 51 | var chain = new TokenChain();
|
---|
| 52 | self[key].forEach(function(tokens) {
|
---|
| 53 | var index;
|
---|
| 54 | while ((index = tokens.indexOf(token)) !== -1) {
|
---|
| 55 | tokens.splice(index, 1);
|
---|
| 56 | }
|
---|
| 57 | tokens.forEach(function(token) {
|
---|
| 58 | self['$' + token].processed++;
|
---|
| 59 | });
|
---|
| 60 | chain.add(tokens.slice(0));
|
---|
| 61 | });
|
---|
| 62 | sorter[key] = chain.createSorter();
|
---|
| 63 | return true;
|
---|
| 64 | }
|
---|
| 65 | return false;
|
---|
| 66 | });
|
---|
| 67 | return sorter;
|
---|
| 68 | }
|
---|
| 69 | };
|
---|
| 70 |
|
---|
| 71 | module.exports = TokenChain;
|
---|