runtime-bridge.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. const CHAT_KEY_PREFIX = 'hl88msg:message_'
  2. function decimalPlaces(n) {
  3. const parts = String(n).split('.')
  4. return parts.length > 1 ? parts[1].length : 0
  5. }
  6. function scaleFactor(a, b) {
  7. return Math.pow(10, Math.max(decimalPlaces(a), decimalPlaces(b)))
  8. }
  9. function stripDot(n) {
  10. return Number(String(n).replace('.', ''))
  11. }
  12. export function persistChatMessage(payload, direction) {
  13. const peerId = direction === 'send' ? payload.to_id : payload.form.id
  14. const storageKey = CHAT_KEY_PREFIX + peerId
  15. uni.getStorage({
  16. key: storageKey,
  17. success(res) {
  18. const history = res.data.slice(-96)
  19. history.push(payload)
  20. uni.setStorageSync(storageKey, history)
  21. },
  22. fail() {
  23. uni.setStorageSync(storageKey, [payload])
  24. }
  25. })
  26. return payload
  27. }
  28. export const decimalAdd = (a, b) => {
  29. const factor = scaleFactor(a, b)
  30. return (decimalMul(a, factor) + decimalMul(b, factor)) / factor
  31. }
  32. export const decimalSub = (a, b) => {
  33. const factor = scaleFactor(a, b)
  34. return (decimalMul(a, factor) - decimalMul(b, factor)) / factor
  35. }
  36. export const decimalMul = (a, b) => {
  37. let precision = 0
  38. const sa = String(a)
  39. const sb = String(b)
  40. try { precision += sa.split('.')[1].length } catch (_) {}
  41. try { precision += sb.split('.')[1].length } catch (_) {}
  42. return stripDot(sa) * stripDot(sb) / Math.pow(10, precision)
  43. }
  44. export const decimalDiv = (a, b) => {
  45. let pa = 0
  46. let pb = 0
  47. try { pa = String(a).split('.')[1].length } catch (_) {}
  48. try { pb = String(b).split('.')[1].length } catch (_) {}
  49. const na = stripDot(a)
  50. const nb = stripDot(b)
  51. return decimalMul(na / nb, Math.pow(10, pb - pa))
  52. }