|
1 | | -const hasOwnProperty = require('has-own-prop') |
2 | 1 | const {isArray} = require('core-util-is') |
| 2 | +const {sort} = require('array-timsort') |
3 | 3 |
|
4 | 4 | const { |
5 | 5 | SYMBOL_PREFIXES, |
6 | 6 |
|
7 | 7 | UNDEFINED, |
8 | 8 |
|
9 | 9 | symbol, |
10 | | - define, |
11 | | - copy_comments, |
12 | | - copy_all_comments |
| 10 | + copy_all_comments, |
| 11 | + swap_comments |
13 | 12 | } = require('./common') |
14 | 13 |
|
15 | 14 |
|
16 | | -const swap_comments = (array, from, to) => { |
17 | | - if (from === to) { |
18 | | - return |
19 | | - } |
20 | | - |
21 | | - SYMBOL_PREFIXES.forEach(prefix => { |
22 | | - const target_prop = symbol(prefix, to) |
23 | | - if (!hasOwnProperty(array, target_prop)) { |
24 | | - copy_comments(array, array, to, from, prefix) |
25 | | - return |
26 | | - } |
27 | | - |
28 | | - const comments = array[target_prop] |
29 | | - copy_comments(array, array, to, from, prefix) |
30 | | - define(array, symbol(prefix, from), comments) |
31 | | - }) |
32 | | -} |
33 | | - |
34 | 15 | const reverse_comments = array => { |
35 | 16 | const {length} = array |
36 | 17 | let i = 0 |
@@ -235,6 +216,43 @@ class CommentArray extends Array { |
235 | 216 |
|
236 | 217 | return ret |
237 | 218 | } |
| 219 | + |
| 220 | + sort (...args) { |
| 221 | + const result = sort( |
| 222 | + this, |
| 223 | + // Make sure there is no more than one argument |
| 224 | + ...args.slice(0, 1) |
| 225 | + ) |
| 226 | + |
| 227 | + // For example, |
| 228 | + // if we sort ['c', 'a', 'b', 'd'], |
| 229 | + // then `result` will be [1, 2, 0, 3], and the array is ['a', 'b', 'c', 'd'] |
| 230 | + |
| 231 | + // First, we swap index 0 and index 1, then the array comments are |
| 232 | + // ['a.comments', 'c.comments', 'b.comments', 'd.comments'] |
| 233 | + |
| 234 | + // Then swap index 1 and index 2 |
| 235 | + // ['a.comments', 'b.comments', 'c.comments', 'd.comments'] |
| 236 | + |
| 237 | + // And we should not swap index 2 and index 0 |
| 238 | + |
| 239 | + const sorted = new Set() |
| 240 | + |
| 241 | + result.forEach((new_index, original_index) => { |
| 242 | + if (new_index === original_index) { |
| 243 | + return |
| 244 | + } |
| 245 | + |
| 246 | + if (sorted.has(new_index) && sorted.has(original_index)) { |
| 247 | + return |
| 248 | + } |
| 249 | + |
| 250 | + sorted.add(new_index) |
| 251 | + sorted.add(original_index) |
| 252 | + |
| 253 | + swap_comments(this, new_index, original_index) |
| 254 | + }) |
| 255 | + } |
238 | 256 | } |
239 | 257 |
|
240 | 258 | module.exports = { |
|
0 commit comments