tuple.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /**
  2. * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import { hash2 } from '../util';
  7. /**
  8. * Represents a pair of two integers as a double,
  9. * Caution: === does not work, because of NaN, use IntTuple.areEqual for equality
  10. */
  11. interface IntTuple { '@type': 'int-tuple' }
  12. namespace IntTuple {
  13. export const Zero: IntTuple = 0 as any;
  14. const { _int32, _float64, _int32_1, _float64_1 } = (function () {
  15. const data = new ArrayBuffer(8);
  16. const data_1 = new ArrayBuffer(8);
  17. return {
  18. _int32: new Int32Array(data),
  19. _float64: new Float64Array(data),
  20. _int32_1: new Int32Array(data_1),
  21. _float64_1: new Float64Array(data_1)
  22. };
  23. }());
  24. export function is(x: any): x is IntTuple {
  25. return typeof x === 'number';
  26. }
  27. export function create(fst: number, snd: number): IntTuple {
  28. _int32[0] = fst;
  29. _int32[1] = snd;
  30. return _float64[0] as any;
  31. }
  32. /** snd - fst */
  33. export function diff(t: IntTuple) {
  34. _float64[0] = t as any;
  35. return _int32[1] - _int32[0];
  36. }
  37. export function fst(t: IntTuple): number {
  38. _float64[0] = t as any;
  39. return _int32[0];
  40. }
  41. export function snd(t: IntTuple): number {
  42. _float64[0] = t as any;
  43. return _int32[1];
  44. }
  45. /** Normal equality does not work, because NaN === NaN ~> false */
  46. export function areEqual(a: IntTuple, b: IntTuple) {
  47. _float64[0] = a as any;
  48. _float64_1[0] = b as any;
  49. return _int32[0] === _int32_1[0] && _int32[1] === _int32_1[1];
  50. }
  51. export function compare(a: IntTuple, b: IntTuple) {
  52. _float64[0] = a as any;
  53. _float64_1[0] = b as any;
  54. const x = _int32[0] - _int32_1[0];
  55. if (x !== 0) return x;
  56. return _int32[1] - _int32_1[1];
  57. }
  58. export function compareInArray(xs: ArrayLike<IntTuple>, i: number, j: number) {
  59. _float64[0] = xs[i] as any;
  60. _float64_1[0] = xs[j] as any;
  61. const x = _int32[0] - _int32_1[0];
  62. if (x !== 0) return x;
  63. return _int32[1] - _int32_1[1];
  64. }
  65. export function hashCode(t: IntTuple) {
  66. _float64[0] = t as any;
  67. return hash2(_int32[0], _int32[1]);
  68. }
  69. export function toString(t: IntTuple) {
  70. _float64[0] = t as any;
  71. return `(${_int32[0]}, ${_int32[1]})`;
  72. }
  73. }
  74. export { IntTuple };