(array: any[], slice: string)
| 9 | import {toJS, isObservableArray} from 'mobx'; |
| 10 | |
| 11 | export function arraySlice(array: any[], slice: string) { |
| 12 | if (typeof slice !== 'string') { |
| 13 | return array; |
| 14 | } |
| 15 | if (isObservableArray(array)) { |
| 16 | array = toJS(array); |
| 17 | } |
| 18 | |
| 19 | slice = slice.trim(); |
| 20 | if (!slice || !Array.isArray(array)) { |
| 21 | return array; |
| 22 | } |
| 23 | const parts = slice.split(','); |
| 24 | const ret: any[] = []; |
| 25 | const arrayLength = array.length; |
| 26 | if (!arrayLength) { |
| 27 | return array; |
| 28 | } |
| 29 | for (const part of parts) { |
| 30 | // 普通的场景 |
| 31 | if (part.indexOf(':') === -1) { |
| 32 | const index = parseInt(part, 10); |
| 33 | if (!isNaN(index) && index < arrayLength) { |
| 34 | ret.push(array[index]); |
| 35 | } |
| 36 | } else { |
| 37 | const [start, end] = part.split(':'); |
| 38 | let startIndex = parseInt(start || '0', 10); |
| 39 | if (isNaN(startIndex) || startIndex < 0) { |
| 40 | startIndex = 0; |
| 41 | } |
| 42 | // 大于就没意义了 |
| 43 | if (startIndex >= arrayLength) { |
| 44 | continue; |
| 45 | } |
| 46 | let endIndex = parseInt(end, 10); |
| 47 | if (isNaN(endIndex)) { |
| 48 | endIndex = arrayLength; |
| 49 | } |
| 50 | // 负数就从后面开始取 |
| 51 | if (endIndex < 0) { |
| 52 | endIndex = arrayLength + endIndex; |
| 53 | } |
| 54 | // 小于没有意义 |
| 55 | if (endIndex < startIndex) { |
| 56 | continue; |
| 57 | } |
| 58 | if (endIndex > arrayLength) { |
| 59 | endIndex = arrayLength; |
| 60 | } |
| 61 | |
| 62 | ret.push(...array.slice(startIndex, endIndex)); |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | return ret; |
| 67 | } |
no test coverage detected