arrayFill.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. const length = array.length >>> 0;
  30. const relativeStart = defaultValue(start, 0);
  31. // If negative, find wrap around position
  32. let k =
  33. relativeStart < 0
  34. ? Math.max(length + relativeStart, 0)
  35. : Math.min(relativeStart, length);
  36. const relativeEnd = defaultValue(end, length);
  37. // If negative, find wrap around position
  38. const last =
  39. relativeEnd < 0
  40. ? Math.max(length + relativeEnd, 0)
  41. : Math.min(relativeEnd, length);
  42. // Fill array accordingly
  43. while (k < last) {
  44. array[k] = value;
  45. k++;
  46. }
  47. return array;
  48. }
  49. export default arrayFill;