This post is on the lodash repeat method which is a string method that is just a quick way of creating a new string that is a product of repeating another given string a number of given times. This is something that comes up now and then when working with projects, and it is kind of nice to have a quick convenience method in place to save me the trouble of having to do this myself each time.
So say I want to create a string that is a single string repeated a few times. For example I want to have a string that is a one with a whole bunch of zeros after it. I could do something like just having two strings one of which is a string of the number one and the other is a bunch of zeros, and just add them together. However what if the number of number one might change to something else, or the number of zeros will change? In that case I will want some kind of method where I can pass a string, and a number of times I want that string repeated, and then add my first value to the result of that method.
With that said if the full lodash utility library is available there is the lodash repeat method to work with then it comes to this sort of thing. I can then use the lodash repeat method as a way to do just that and just get a string that is a fixed number of zeros. Just call the lodash repeat method and pass the string 0 as the first argument followed by the number of zeros I want after the string.
A similar method that comes to mind is the lodash times method. This method is a method that just simply called a given function a number of given times. It is a quick convenient way of doing something that would otherwise require writing a loop.
So there is the lodash repeat method when it comes to string methods, but then there are other methods such as the lodash fill array method. The lodash fill method is another method to be aware of when using lodash as it does more or less the same thing as lodash repeat only with arrays rather than strings.
There is using the main lodash function as a way to wrap a new array that has a given element length, then using the fill method off of that to fill the array with zeros. After that I can then call the join method that will unwrap the whole thing and return a string. When using the join method I can pass an empty string that will result in nothing between the zeros.
No to hard to just making my own repeat method with a while loop after all. Sometimes I like to do this when it comes to lodash methods, most of the time it is supper easy to just put something together. However I have to admit doing this does have a tenancy to eat up a little time.
Making my own times method is not a big deal as well. The thing about it is that making a lot of these methods from the ground up is not so hard. It is not always the case with some lodash methods, such as merge, but it is not a big deal to make a high order function that accepts a function as an argument and then calls that function inside a few times.