'use strict';
var $ = require('../internals/export');
var uncurryThis = require('../internals/function-uncurry-this');
var aDataView = require('../internals/a-data-view');
var toIndex = require('../internals/to-index');
// TODO: Replace with module dependency in `core-js@4`
var log2 = require('../internals/math-log2');
var roundTiesToEven = require('../internals/math-round-ties-to-even');

var pow = Math.pow;

var MIN_INFINITY16 = 65520; // (2 - 2 ** -11) * 2 ** 15
var MIN_NORMAL16 = 0.000061005353927612305; // (1 - 2 ** -11) * 2 ** -14
var REC_MIN_SUBNORMAL16 = 16777216; // 2 ** 10 * 2 ** 14
var REC_SIGNIFICAND_DENOM16 = 1024; // 2 ** 10;

var packFloat16 = function (value) {
  // eslint-disable-next-line no-self-compare -- NaN check
  if (value !== value) return 0x7E00; // NaN
  if (value === 0) return (1 / value === -Infinity) << 15; // +0 or -0

  var neg = value < 0;
  if (neg) value = -value;
  if (value >= MIN_INFINITY16) return neg << 15 | 0x7C00; // Infinity
  if (value < MIN_NORMAL16) return neg << 15 | roundTiesToEven(value * REC_MIN_SUBNORMAL16); // subnormal

  // normal
  var exponent = log2(value) | 0;
  if (exponent === -15) {
    // we round from a value between 2 ** -15 * (1 + 1022/1024) (the largest subnormal) and 2 ** -14 * (1 + 0/1024) (the smallest normal)
    // to the latter (former impossible because of the subnormal check above)
    return neg << 15 | REC_SIGNIFICAND_DENOM16;
  }
  var significand = roundTiesToEven((value * pow(2, -exponent) - 1) * REC_SIGNIFICAND_DENOM16);
  if (significand === REC_SIGNIFICAND_DENOM16) {
    // we round from a value between 2 ** n * (1 + 1023/1024) and 2 ** (n + 1) * (1 + 0/1024) to the latter
    return neg << 15 | exponent + 16 << 10;
  }
  return neg << 15 | exponent + 15 << 10 | significand;
};

// eslint-disable-next-line es/no-typed-arrays -- safe
var setUint16 = uncurryThis(DataView.prototype.setUint16);

// `DataView.prototype.setFloat16` method
// https://github.com/tc39/proposal-float16array
$({ target: 'DataView', proto: true }, {
  setFloat16: function setFloat16(byteOffset, value /* , littleEndian */) {
    aDataView(this);
    var offset = toIndex(byteOffset);
    var bytes = packFloat16(+value);
    return setUint16(this, offset, bytes, arguments.length > 2 ? arguments[2] : false);
  }
});
