arrayFill.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import Check from './Check.js';
  2. import defaultValue from './defaultValue.js';
  3. import defined from './defined.js';
  4. /**
  5. * Fill an array or a portion of an array with a given value.
  6. *
  7. * @param {Array} array The array to fill.
  8. * @param {*} value The value to fill the array with.
  9. * @param {Number} [start=0] The index to start filling at.
  10. * @param {Number} [end=array.length] The index to end stop at.
  11. *
  12. * @returns {Array} The resulting array.
  13. * @private
  14. */
  15. function arrayFill(array, value, start, end) {
  16. //>>includeStart('debug', pragmas.debug);
  17. Check.defined('array', array);
  18. Check.defined('value', value);
  19. if (defined(start)) {
  20. Check.typeOf.number('start', start);
  21. }
  22. if (defined(end)) {
  23. Check.typeOf.number('end', end);
  24. }
  25. //>>includeEnd('debug');
  26. if (typeof array.fill === 'function') {
  27. return array.fill(value, start, end);
  28. }
  29. var length = array.length >>> 0;
  30. var relativeStart = defaultValue(start, 0);
  31. // If negative, find wrap around position
  32. var k = (relativeStart < 0) ? Math.max(length + relativeStart, 0) : Math.min(relativeStart, length);
  33. var relativeEnd = defaultValue(end, length);
  34. // If negative, find wrap around position
  35. var last = (relativeEnd < 0) ? Math.max(length + relativeEnd, 0) : Math.min(relativeEnd, length);
  36. // Fill array accordingly
  37. while (k < last) {
  38. array[k] = value;
  39. k++;
  40. }
  41. return array;
  42. }
  43. export default arrayFill;