cross.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { arraySize, squeeze } from '../../utils/array.js';
  2. import { factory } from '../../utils/factory.js';
  3. var name = 'cross';
  4. var dependencies = ['typed', 'matrix', 'subtract', 'multiply'];
  5. export var createCross = /* #__PURE__ */factory(name, dependencies, _ref => {
  6. var {
  7. typed,
  8. matrix,
  9. subtract,
  10. multiply
  11. } = _ref;
  12. /**
  13. * Calculate the cross product for two vectors in three dimensional space.
  14. * The cross product of `A = [a1, a2, a3]` and `B = [b1, b2, b3]` is defined
  15. * as:
  16. *
  17. * cross(A, B) = [
  18. * a2 * b3 - a3 * b2,
  19. * a3 * b1 - a1 * b3,
  20. * a1 * b2 - a2 * b1
  21. * ]
  22. *
  23. * If one of the input vectors has a dimension greater than 1, the output
  24. * vector will be a 1x3 (2-dimensional) matrix.
  25. *
  26. * Syntax:
  27. *
  28. * math.cross(x, y)
  29. *
  30. * Examples:
  31. *
  32. * math.cross([1, 1, 0], [0, 1, 1]) // Returns [1, -1, 1]
  33. * math.cross([3, -3, 1], [4, 9, 2]) // Returns [-15, -2, 39]
  34. * math.cross([2, 3, 4], [5, 6, 7]) // Returns [-3, 6, -3]
  35. * math.cross([[1, 2, 3]], [[4], [5], [6]]) // Returns [[-3, 6, -3]]
  36. *
  37. * See also:
  38. *
  39. * dot, multiply
  40. *
  41. * @param {Array | Matrix} x First vector
  42. * @param {Array | Matrix} y Second vector
  43. * @return {Array | Matrix} Returns the cross product of `x` and `y`
  44. */
  45. return typed(name, {
  46. 'Matrix, Matrix': function MatrixMatrix(x, y) {
  47. return matrix(_cross(x.toArray(), y.toArray()));
  48. },
  49. 'Matrix, Array': function MatrixArray(x, y) {
  50. return matrix(_cross(x.toArray(), y));
  51. },
  52. 'Array, Matrix': function ArrayMatrix(x, y) {
  53. return matrix(_cross(x, y.toArray()));
  54. },
  55. 'Array, Array': _cross
  56. });
  57. /**
  58. * Calculate the cross product for two arrays
  59. * @param {Array} x First vector
  60. * @param {Array} y Second vector
  61. * @returns {Array} Returns the cross product of x and y
  62. * @private
  63. */
  64. function _cross(x, y) {
  65. var highestDimension = Math.max(arraySize(x).length, arraySize(y).length);
  66. x = squeeze(x);
  67. y = squeeze(y);
  68. var xSize = arraySize(x);
  69. var ySize = arraySize(y);
  70. if (xSize.length !== 1 || ySize.length !== 1 || xSize[0] !== 3 || ySize[0] !== 3) {
  71. throw new RangeError('Vectors with length 3 expected ' + '(Size A = [' + xSize.join(', ') + '], B = [' + ySize.join(', ') + '])');
  72. }
  73. var product = [subtract(multiply(x[1], y[2]), multiply(x[2], y[1])), subtract(multiply(x[2], y[0]), multiply(x[0], y[2])), subtract(multiply(x[0], y[1]), multiply(x[1], y[0]))];
  74. if (highestDimension > 1) {
  75. return [product];
  76. } else {
  77. return product;
  78. }
  79. }
  80. });