/ src / term.js
term.js
 1  import * as API from './api.js'
 2  import * as Variable from './variable.js'
 3  import * as Constant from './constant.js'
 4  
 5  /**
 6   * @param {unknown} term
 7   * @returns {term is API.Term}
 8   */
 9  export const is = (term) => Variable.is(term) || Constant.is(term)
10  
11  /**
12   * @param {API.Term} term
13   */
14  export const toJSON = (term) =>
15    Variable.is(term) ? Variable.toJSON(term) : Constant.toJSON(term)
16  
17  /**
18   * @param {API.Term} term
19   * @returns {string}
20   */
21  export const toString = (term) =>
22    Variable.is(term) ? Variable.toString(term) : Constant.toString(term)
23  
24  /**
25   * @param {API.Term} term
26   */
27  export const isBlank = (term) => Variable.is(term) && Variable.isBlank(term)
28  
29  /**
30  
31  /**
32   * @param {API.Term} term
33   * @param {API.Term} to
34   * @returns {0|1|-1}
35   */
36  export const compare = (term, to) => {
37    // If both are variables we compare them by variable comparison otherwise
38    // non variable is greater.
39    if (Variable.is(term)) {
40      return Variable.is(to) ? Variable.compare(term, to) : -1
41    }
42    // If term is a constant and `to` is a variable return 1 as we consider
43    // constant greater than variable, otherwise we compare by constants.
44    else {
45      return Variable.is(to) ? 1 : Constant.compare(term, to)
46    }
47  }
48  
49  /**
50   * @param {API.Term} term
51   */
52  export const toDebugString = (term) =>
53    Variable.is(term) ?
54      Variable.toDebugString(term)
55    : Constant.toDebugString(term)