source: imaps-frontend/node_modules/es-abstract/2017/RawBytesToNumber.js

main
Last change on this file was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago

Update repo after prototype presentation

  • Property mode set to 100644
File size: 2.1 KB
RevLine 
[d565449]1'use strict';
2
3var callBound = require('call-bind/callBound');
4
5var $RangeError = require('es-errors/range');
6var $TypeError = require('es-errors/type');
7
8var $charAt = callBound('String.prototype.charAt');
9var $reverse = callBound('Array.prototype.reverse');
10var $slice = callBound('Array.prototype.slice');
11
12var hasOwnProperty = require('./HasOwnProperty');
13var IsArray = require('./IsArray');
14
15var bytesAsFloat32 = require('../helpers/bytesAsFloat32');
16var bytesAsFloat64 = require('../helpers/bytesAsFloat64');
17var bytesAsInteger = require('../helpers/bytesAsInteger');
18var every = require('../helpers/every');
19var isByteValue = require('../helpers/isByteValue');
20
21var keys = require('object-keys');
22
23// https://262.ecma-international.org/8.0/#table-50
24var TypeToSizes = {
25 __proto__: null,
26 Int8: 1,
27 Uint8: 1,
28 Uint8C: 1,
29 Int16: 2,
30 Uint16: 2,
31 Int32: 4,
32 Uint32: 4,
33 Float32: 4,
34 Float64: 8
35};
36
37// https://262.ecma-international.org/8.0/#sec-rawbytestonumber
38
39module.exports = function RawBytesToNumber(type, rawBytes, isLittleEndian) {
40 if (typeof type !== 'string' || !hasOwnProperty(TypeToSizes, type)) {
41 throw new $TypeError('Assertion failed: `type` must be a TypedArray element type: ' + keys(TypeToSizes));
42 }
43 if (!IsArray(rawBytes) || !every(rawBytes, isByteValue)) {
44 throw new $TypeError('Assertion failed: `rawBytes` must be an Array of bytes');
45 }
46 if (typeof isLittleEndian !== 'boolean') {
47 throw new $TypeError('Assertion failed: `isLittleEndian` must be a Boolean');
48 }
49
50 var elementSize = TypeToSizes[type]; // step 1
51
52 if (rawBytes.length !== elementSize) {
53 // this assertion is not in the spec, but it'd be an editorial error if it were ever violated
54 throw new $RangeError('Assertion failed: `rawBytes` must have a length of ' + elementSize + ' for type ' + type);
55 }
56
57 // eslint-disable-next-line no-param-reassign
58 rawBytes = $slice(rawBytes, 0, elementSize);
59 if (!isLittleEndian) {
60 $reverse(rawBytes); // step 2
61 }
62
63 if (type === 'Float32') { // step 3
64 return bytesAsFloat32(rawBytes);
65 }
66
67 if (type === 'Float64') { // step 4
68 return bytesAsFloat64(rawBytes);
69 }
70
71 return bytesAsInteger(rawBytes, elementSize, $charAt(type, 0) === 'U', false);
72};
Note: See TracBrowser for help on using the repository browser.