Last active
July 12, 2019 14:43
-
-
Save smitroshin/0ed3ad9870cd6651c4cc4070bd098761 to your computer and use it in GitHub Desktop.
Fill array with one value 'n' times
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Fill array with value, len times | |
// Using concat | |
fillArray = (value, len) => { | |
if (len === 0) return []; | |
let a = [value]; | |
while (a.length * 2 <= len) a = a.concat(a); | |
if (a.length < len) a = a.concat(a.slice(0, len - a.length)); | |
return a; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Fill array with value, len times | |
// Using push | |
fillArray = (value, len) => { | |
const arr = []; | |
for (let i = 0; i < len; i += 1) { | |
arr.push(value); | |
} | |
return arr; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Fill array with value, len times | |
// Using spread operator | |
const fillArray = (value, len) => { | |
let arr = []; | |
for (let i = 0; i < len; i += 1) { | |
arr = [...arr, value]; | |
} | |
return arr; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment