|
| 1 | +const Library = require("../definitions/Library"); |
| 2 | + |
| 3 | +class ArrayUtil extends Library { |
| 4 | + /** |
| 5 | + * |
| 6 | + * @param {*} marked_map |
| 7 | + * @param {*} subject |
| 8 | + */ |
| 9 | + remove_marked_items (marked_map, subject) { |
| 10 | + for ( let i=0 ; i < marked_map.length ; i++ ) { |
| 11 | + let ii = marked_map[i]; |
| 12 | + // track: type check |
| 13 | + if ( ! Number.isInteger(ii) ) { |
| 14 | + throw new Error( |
| 15 | + 'marked_map can only contain integers' |
| 16 | + ); |
| 17 | + } |
| 18 | + // track: bounds check |
| 19 | + if ( ii < 0 && ii >= subject.length ) { |
| 20 | + throw new Error( |
| 21 | + 'each item in `marked_map` must be within that bounds ' + |
| 22 | + 'of `subject`' |
| 23 | + ); |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + marked_map.sort((a, b) => b - a); |
| 28 | + |
| 29 | + for ( let i=0 ; i < marked_map.length ; i++ ) { |
| 30 | + let ii = marked_map[i]; |
| 31 | + subject.splice(ii, 1); |
| 32 | + } |
| 33 | + |
| 34 | + return subject; |
| 35 | + } |
| 36 | + |
| 37 | + _test ({ assert }) { |
| 38 | + // inner indices |
| 39 | + { |
| 40 | + const subject = [ |
| 41 | + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']; |
| 42 | + // 0 1 2 3 4 5 6 7 |
| 43 | + const marked_map = [2, 5]; |
| 44 | + this.remove_marked_items(marked_map, subject); |
| 45 | + assert(() => subject.join('') === 'abdegh'); |
| 46 | + } |
| 47 | + // left edge |
| 48 | + { |
| 49 | + const subject = [ |
| 50 | + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']; |
| 51 | + // 0 1 2 3 4 5 6 7 |
| 52 | + const marked_map = [0] |
| 53 | + this.remove_marked_items(marked_map, subject); |
| 54 | + assert(() => subject.join('') === 'bcdefgh'); |
| 55 | + } |
| 56 | + // right edge |
| 57 | + { |
| 58 | + const subject = [ |
| 59 | + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']; |
| 60 | + // 0 1 2 3 4 5 6 7 |
| 61 | + const marked_map = [7] |
| 62 | + this.remove_marked_items(marked_map, subject); |
| 63 | + assert(() => subject.join('') === 'abcdefg'); |
| 64 | + } |
| 65 | + // both edges |
| 66 | + { |
| 67 | + const subject = [ |
| 68 | + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']; |
| 69 | + // 0 1 2 3 4 5 6 7 |
| 70 | + const marked_map = [0, 7] |
| 71 | + this.remove_marked_items(marked_map, subject); |
| 72 | + assert(() => subject.join('') === 'bcdefg'); |
| 73 | + } |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +module.exports = ArrayUtil; |
0 commit comments