tuple.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. export function fst(t: IntTuple): number {
  33. _float64[0] = t as any;
  34. return _int32[0];
  35. }
  36. export function snd(t: IntTuple): number {
  37. _float64[0] = t as any;
  38. return _int32[1];
  39. }
  40. /** Normal equality does not work, because NaN === NaN ~> false */
  41. export function areEqual(a: IntTuple, b: IntTuple) {
  42. _float64[0] = a as any;
  43. _float64_1[0] = b as any;
  44. return _int32[0] === _int32_1[0] && _int32[1] === _int32_1[1];
  45. }
  46. export function compare(a: IntTuple, b: IntTuple) {
  47. _float64[0] = a as any;
  48. _float64_1[0] = b as any;
  49. const x = _int32[0] - _int32_1[0];
  50. if (x !== 0) return x;
  51. return _int32[1] - _int32_1[1];
  52. }
  53. export function compareInArray(xs: ArrayLike<IntTuple>, i: number, j: number) {
  54. _float64[0] = xs[i] as any;
  55. _float64_1[0] = xs[j] as any;
  56. const x = _int32[0] - _int32_1[0];
  57. if (x !== 0) return x;
  58. return _int32[1] - _int32_1[1];
  59. }
  60. export function hashCode(t: IntTuple) {
  61. _float64[0] = t as any;
  62. return hash2(_int32[0], _int32[1]);
  63. }
  64. export function toString(t: IntTuple) {
  65. _float64[0] = t as any;
  66. return `(${_int32[0]}, ${_int32[1]})`;
  67. }
  68. }
  69. export default IntTuple;