Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@skava/money / src / MoneyValueObject.ts
Size: Mime:
import {
  transformPricing,
  PriceType,
  fromRangeToString,
  fromRangeToStringPure,
} from './deps'
import { MoneyValueFormattingOptions, MoneyValueDiff } from './typings'

/**
 * @TODO extendCoerce
 * this is a common DDD entity, with our work cut out for us
 * @see  https://github.com/moneyphp/money/blob/master/src/Money.php
 */
class MoneyValueObject {
  /** (for view, with currency etc) */
  formatted?: string

  /* (type from api - usually used in Moneys to compare diff */
  type: string = 'type'
  isValid: boolean = false
  amount: string | number
  raw: any
  /**
   * @todo inherit globally
   * @alias currencycode
   * @desc symbol for currency, our api has invalid naming for this
   */
  currencySymbol = '$'
  /**
   * @api https://en.wikipedia.org/wiki/ISO_4217
   */
  standardCurrencyCode = 'USD'
  formattingOptions: MoneyValueFormattingOptions = { digits: 2 }

  // could be # or Obj...
  constructor(price) {
    this.amount = price.value
    this.raw = price
  }

  get longtype() {
    return this.type === 'reg'
      ? 'Regular'
      : this.type === 'sale'
        ? 'Sale'
        : this.type === 'orig'
          ? 'Original'
          : 'N/A'
  }
  get isRange() {
    return this.raw.ismin && this.raw.ismax
  }

  toPrimitive(hint: 'number' | 'string' | 'default') {
    if (hint === 'number') {
      return this.toNumber()
    } else {
      return this.toString()
    }
  }
  // [Symbol.toPrimitive](hint) {
  //   if (hint === 'number') {
  //     return this.toNumber()
  //   } else {
  //     return this.toString()
  //   }
  // }
  toNumber() {
    return this.amount
  }
  toString() {
    if (this.isRange) {
      return fromRangeToString(this.min, this.max)
    } else {
      return this.toFixed()
    }
  }

  toFixed() {
    return this.amount.toFixed(this.formattingOptions.digits)
  }
  get digits() {
    return this.toString()
      .split('.')
      .pop()
  }

  /**
   * @todo some of our apis provide .Math
   * @tutorial https://www.mathsisfun.com/percentage-calculator.html
   * @alias salePercentDiff,saleNumberDiff
   */
  diff = ($: MoneyValueObject): MoneyValueDiff => {
    return {
      percent: +$,
      price: +$,
    }
  }
}

Object.defineProperty(MoneyValueObject.prototype, Symbol.toPrimitive, {
  value: MoneyValueObject.prototype.toPrimitive,
})

export { MoneyValueObject }