testTypedArray.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright (C) 2015 André Bargull. All rights reserved.
  2. // This code is governed by the BSD license found in the LICENSE file.
  3. /*---
  4. description: |
  5. Collection of functions used to assert the correctness of TypedArray objects.
  6. ---*/
  7. /**
  8. * Array containing every typed array constructor.
  9. */
  10. var typedArrayConstructors = [
  11. Float64Array,
  12. Float32Array,
  13. Int32Array,
  14. Int16Array,
  15. Int8Array,
  16. Uint32Array,
  17. Uint16Array,
  18. Uint8Array,
  19. Uint8ClampedArray
  20. ];
  21. var floatArrayConstructors = typedArrayConstructors.slice(0, 2);
  22. var intArrayConstructors = typedArrayConstructors.slice(2, 7);
  23. /**
  24. * The %TypedArray% intrinsic constructor function.
  25. */
  26. var TypedArray = Object.getPrototypeOf(Int8Array);
  27. /**
  28. * Callback for testing a typed array constructor.
  29. *
  30. * @callback typedArrayConstructorCallback
  31. * @param {Function} Constructor the constructor object to test with.
  32. */
  33. /**
  34. * Calls the provided function for every typed array constructor.
  35. *
  36. * @param {typedArrayConstructorCallback} f - the function to call for each typed array constructor.
  37. * @param {Array} selected - An optional Array with filtered typed arrays
  38. */
  39. function testWithTypedArrayConstructors(f, selected) {
  40. var constructors = selected || typedArrayConstructors;
  41. for (var i = 0; i < constructors.length; ++i) {
  42. var constructor = constructors[i];
  43. try {
  44. f(constructor);
  45. } catch (e) {
  46. e.message += " (Testing with " + constructor.name + ".)";
  47. throw e;
  48. }
  49. }
  50. }
  51. /**
  52. * Helper for conversion operations on TypedArrays, the expected values
  53. * properties are indexed in order to match the respective value for each
  54. * TypedArray constructor
  55. * @param {Function} fn - the function to call for each constructor and value.
  56. * will be called with the constructor, value, expected
  57. * value, and a initial value that can be used to avoid
  58. * a false positive with an equivalent expected value.
  59. */
  60. function testTypedArrayConversions(byteConversionValues, fn) {
  61. var values = byteConversionValues.values;
  62. var expected = byteConversionValues.expected;
  63. testWithTypedArrayConstructors(function(TA) {
  64. var name = TA.name.slice(0, -5);
  65. return values.forEach(function(value, index) {
  66. var exp = expected[name][index];
  67. var initial = 0;
  68. if (exp === 0) {
  69. initial = 1;
  70. }
  71. fn(TA, value, exp, initial);
  72. });
  73. });
  74. }