Guest User

Untitled

a guest
Dec 15th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. function resize(arr, newSize, defaultValue) {
  2. if (newSize > arr.length)
  3. while(newSize > arr.length)
  4. arr.push(defaultValue);
  5. else
  6. arr.length = newSize;
  7. }
  8.  
  9. function resize(arr, newSize, defaultValue) {
  10. while(newSize > arr.length)
  11. arr.push(defaultValue);
  12. arr.length = newSize;
  13. }
  14.  
  15. Array.prototype.resize = function(newSize, defaultValue) {
  16. while(newSize > this.length)
  17. this.push(defaultValue);
  18. this.length = newSize;
  19. }
  20.  
  21. function resize(arr, size, defval) {
  22. while (arr.length > size) { arr.pop(); }
  23. while (arr.length < size) { arr.push(defval); }
  24. }
  25.  
  26. function resize(arr, size, defval) {
  27. var delta = arr.length - size;
  28.  
  29. while (delta-- > 0) { arr.pop(); }
  30. while (delta++ < 0) { arr.push(defval); }
  31. }
  32.  
  33. function resize(arr, size, defval) {
  34. var delta = arr.length - size;
  35.  
  36. if (delta > 0) {
  37. arr.length = size;
  38. }
  39. else {
  40. while (delta++ < 0) { arr.push(defval); }
  41. }
  42. }
  43.  
  44. Array.prototype.resize = function(newSize, defaultValue) {
  45. while(newSize > this.length)
  46. this.push(defaultValue);
  47. this.length = newSize;
  48. }
  49.  
  50. if (Array.prototype.fill) {
  51. Array.prototype.resize = function (size, defaultValue) {
  52. var len = this.length;
  53.  
  54. this.length = size;
  55.  
  56. if (this.length - len > 0)
  57. this.fill(defaultValue, len);
  58. };
  59. } else {
  60. Array.prototype.resize = function (size, defaultValue) {
  61. while (size > this.length)
  62. this.push(defaultValue);
  63.  
  64. this.length = size;
  65. };
  66. }
  67.  
  68. function resize(arr, newSize, defaultValue) {
  69. var originLength = arr.length; // cache original length
  70.  
  71. arr.length = newSize; // resize array to newSize
  72.  
  73. (newSize > originLength) && arr.fill(defaultValue, originLength); // Use Array.prototype.fill to insert defaultValue from originLength to the new length
  74. }
  75.  
  76. const resize_array_left = (array, length, fill_with) => (new Array(length)).fill(fill_with).concat(array).slice(-length);
  77. // Pads left when expanding an array.
  78. // Put left elements first to be removed when shrinking an array.
  79.  
  80. const resize_array_right = (array, length, fill_with) => array.concat((new Array(length)).fill(fill_with)).slice(0, length);
  81. // Pads right when expanding an array.
  82. // Put right elements first to be removed when shrinking an array.
Add Comment
Please, Sign In to add comment