all files / model/ CoordinateOperation.js

52.27% Statements 23/44
30% Branches 6/20
50% Functions 7/14
52.27% Lines 23/44
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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119            28×       28×   28×   28×     28×           21×       28×                                                                 14×                                                                         14×              
import { isNumber } from '../util'
 
const SHIFT = 'shift'
 
class CoordinateOperation {
 
  constructor(data) {
    Iif (!data || data.type === undefined) {
      throw new Error("Illegal argument: insufficient data.")
    }
    // 'shift'
    this.type = data.type
    // the position where to apply the operation
    this.val = data.val
    // sanity checks
    Iif(!this.isShift()) {
      throw new Error("Illegal type.")
    }
    Iif (!isNumber(this.val)) {
      throw new Error("Illegal argument: expecting number as shift value.")
    }
  }
 
  apply(coor) {
    coor.offset = coor.offset + this.val
  }
 
  isShift() {
    return this.type === SHIFT
  }
 
  isNOP() {
    switch (this.type) {
      case SHIFT: {
        return this.val === 0
      }
      default:
        return false
    }
  }
 
  clone() {
    return new CoordinateOperation(this)
  }
 
  invert() {
    let data
    switch (this.type) {
      case SHIFT:
        data = {
          type: SHIFT,
          val: -this.val
        }
        break
      default:
        throw new Error('Invalid type.')
    }
    return new CoordinateOperation(data)
  }
 
  hasConflict() {
    // TODO: support conflict detection?
    return false
  }
 
  toJSON() {
    return {
      type: this.type,
      val: this.val
    }
  }
 
  toString() {
    return ["(", (this.type), ",", this.val, "')"].join('')
  }
 
}
 
CoordinateOperation.prototype._isOperation = true
CoordinateOperation.prototype._isCoordinateOperation = true
 
function transform_shift_shift(a, b) {
  a.val += b.val
  b.val += a.val
}
 
function transform(a, b, options) {
  options = options || {}
  // TODO: support conflict detection?
  if (!options.inplace) {
    a = a.clone()
    b = b.clone()
  }
  if (a.type === SHIFT && b.type === SHIFT) {
    transform_shift_shift(a, b)
  }
  else {
    throw new Error('Illegal type')
  }
  return [a, b]
}
 
CoordinateOperation.transform = function(...args) {
  return transform(...args)
}
 
CoordinateOperation.fromJSON = function(json) {
  return new CoordinateOperation(json)
}
 
CoordinateOperation.Shift = function(val) {
  return new CoordinateOperation({
    type: SHIFT,
    val: val
  })
}
 
export default CoordinateOperation