utils/array-utils/src/padToLength.js

  1. /**
  2. * Build an array of the given target length from an existing array and a padding value.
  3. * If the array is already larger than the target length, it will not be shortened.
  4. * @param {Array} anArray - the source array to copy into the result.
  5. * @param {*} padding - the value to add to the new array to reach the desired length.
  6. * @param {Number} targetLength - The desired length of the returned array.
  7. * @returns {Array} an array with at least 'target length" elements
  8. * @alias module:array-utils.padToLength
  9. * @example
  10. * const srcArray = [2, 3, 4]
  11. * const paddedArray = padToLength(srcArray, 0, 5)
  12. */
  13. const padToLength = (anArray, padding, targetLength) => {
  14. anArray = anArray.slice()
  15. while (anArray.length < targetLength) {
  16. anArray.push(padding)
  17. }
  18. return anArray
  19. }
  20. module.exports = padToLength