Guest User

Untitled

a guest
Feb 25th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. /**
  2. * fillBlanks takes an array with falsy/null values, and fills them with the previous value in the array.
  3. * If null values appear without a previous value, you can use nullReplace to autofill it.
  4. * @example
  5. * const arr = ["", "", 0, "", "", 1, "", 2, "", "", "", "Test", ""]
  6. * fillBlanks(arr)
  7. * // => [ null, null, 0, 0, 0, 1, 1, 2, 2, 2, 2, 'Test', 'Test' ]
  8. * @example
  9. * const arr = ["", "", 0, "", "", 1, "", 2, "", "", "", "Test", ""]
  10. * fillBlanks(arr, "replaced")
  11. * // => [ 'replaced', 'replaced', 0, 0, 0, 1, 1, 2, 2, 2, 2, 'Test', 'Test' ]
  12. * @function fillBlanks
  13. * @param {array} arr - the input array
  14. * @param {string} [nullReplace=null] - the replacement value when a null value is encountered
  15. * @returns {string[]}
  16. */
  17.  
  18. function fillBlanks(arr, nullReplace = null) {
  19. const hasValue = val => (val || val === 0 ? true : false)
  20.  
  21. return arr.reduce((acc, val, idx) => {
  22. if (hasValue(val)) {
  23. acc.push(val)
  24. } else {
  25. const hasPrevValue = hasValue(acc[idx - 1])
  26. const prevVal = hasPrevValue ? acc[idx - 1] : nullReplace
  27. acc.push(prevVal)
  28. }
  29. return acc
  30. }, [])
  31. }
  32.  
  33. // Example:
  34. const arr = ["", "", 0, "", "", 1, "", 2, "", "", "", "Test", ""]
  35. fillBlanks(arr)
  36. // => [ null, null, 0, 0, 0, 1, 1, 2, 2, 2, 2, 'Test', 'Test' ]
  37. fillBlanks(arr, "replaced")
  38. // => [ 'replaced', 'replaced', 0, 0, 0, 1, 1, 2, 2, 2, 2, 'Test', 'Test' ]
Add Comment
Please, Sign In to add comment