all files / algebra/src/ createScalar.js

97.83% Statements 45/46
50% Branches 1/2
100% Functions 7/7
97.83% Lines 45/46
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               15×                         164×       164× 164×   164×       15×   15× 120× 914× 914×       15×   15×   15× 150× 28×     150× 17×   17×       15× 60×   60× 53× 53×   53×   53×       15× 30×     15× 30×   30×           15× 165× 195× 195×       15×      
var coerced = require('./coerced')
var operators = require('./operators.json')
var staticProps = require('static-props')
var toData = require('./toData')
 
/**
 * @param {Object} ring
 *
 * @returns {Function} Scalar
 */
 
function createScalar (ring) {
  var attributes = {
    zero: ring.zero,
    one: ring.one,
    order: 0
  }
 
  /**
   * Scalar element.
   */
 
  class Scalar {
    constructor (data) {
      // validate data
      Iif (ring.notContains(data)) {
        throw new TypeError('Invalid data = ' + data)
      }
 
      var enumerable = true
      staticProps(this)({ data }, enumerable)
 
      staticProps(this)(attributes)
    }
  }
 
  staticProps(Scalar)(attributes)
 
  var staticNary = (operator) => {
    Scalar[operator] = function () {
      var operands = [].slice.call(arguments).map(toData)
      return coerced(ring[operator]).apply(null, operands)
    }
  }
 
  var unaryOperators = operators.inversion
 
  unaryOperators.push('conjugation')
 
  unaryOperators.forEach((operator) => {
    Scalar[operator] = function (operand) {
      return ring[operator](toData(operand))
    }
 
    Scalar.prototype[operator] = function () {
      var data = Scalar[operator](this.data)
 
      return new Scalar(data)
    }
  })
 
  operators.group.concat(operators.ring).forEach((operator) => {
    staticNary(operator)
 
    Scalar.prototype[operator] = function () {
      var args = [].slice.call(arguments)
      var operands = [this.data].concat(args)
 
      var data = Scalar[operator].apply(null, operands)
 
      return new Scalar(data)
    }
  })
 
  operators.set.forEach((operator) => {
    staticNary(operator)
  })
 
  operators.comparison.forEach((operator) => {
    staticNary(operator)
 
    Scalar.prototype[operator] = function () {
      var args = [].slice.call(arguments)
      var operands = [this.data].concat(args)
 
      var bool = Scalar[operator].apply(null, operands)
 
      return bool
    }
  })
 
  Object.keys(operators.aliasesOf).forEach((operator) => {
    operators.aliasesOf[operator].forEach((alias) => {
      Scalar[alias] = Scalar[operator]
      Scalar.prototype[alias] = Scalar.prototype[operator]
    })
  })
 
  return Scalar
}
 
module.exports = createScalar