all files / model/ Coordinate.js

60.87% Statements 14/23
76.92% Branches 10/13
45.45% Functions 5/11
63.64% Lines 14/22
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                          6811× 6811× 4214× 4214× 4214×   2597× 2597×   6811×     6811×           169×                 1135×                                                   1673×                    
import { isArray, isArrayEqual, isNumber } from '../util'
 
/**
  @internal
*/
class Coordinate {
 
  /**
   @param {Array} path the address of a property, such as ['text_1', 'content']
   @param {int} offset the position in the property
  */
  constructor(path, offset) {
    // HACK: to allow this class be inherited but without calling this ctor
    Iif (arguments[0] === 'SKIP') return
    if (arguments.length === 1) {
      let data = arguments[0]
      this.path = data.path
      this.offset = data.offset
    } else {
      this.path = path
      this.offset = offset
    }
    Iif (!isArray(this.path)) {
      throw new Error('Invalid arguments: path should be an array.')
    }
    Iif (!isNumber(this.offset) || this.offset < 0) {
      throw new Error('Invalid arguments: offset must be a positive number.')
    }
  }
 
  equals(other) {
    return (other === this ||
      (isArrayEqual(other.path, this.path) && other.offset === this.offset) )
  }
 
  withCharPos(offset) {
    return new Coordinate(this.path, offset)
  }
 
  getNodeId() {
    return this.path[0]
  }
 
  getPath() {
    return this.path
  }
 
  getOffset() {
    return this.offset
  }
 
  toJSON() {
    return {
      path: this.path.slice(),
      offset: this.offset
    }
  }
 
  toString() {
    return "(" + this.path.join('.') + ", " + this.offset + ")"
  }
 
  isPropertyCoordinate() {
    return this.path.length > 1
  }
 
  isNodeCoordinate() {
    return this.path.length === 1
  }
 
  hasSamePath(other) {
    return isArrayEqual(this.path, other.path)
  }
}
 
Coordinate.prototype._isCoordinate = true
 
export default Coordinate