Writing more content on lodash this month for now, and have noticed that I did not get around to _.uniqueId yet. The method addresses something that comes up a lot now and then when developing projects, so it deserves a post. Also in these lodash posts I often take a moment to brush up on how hard it is to go about making a vanilla js solution, or if there are native methods that can be used, and as such this post will be no exception. So lets take a look at _.uniqueId, and some other solutions for generating unique ids.
This is a post on the _.uniqueId method in lodash. This method can be used to create a unique id for something each time it is called. This method will work for the purpose of assigning a unique id for most use cases, but not with complex projects that require a unique id always even if the project restarts. In any case this will be a brief post on this topic.
Using the _.uniqueId method is fairly straight forward to use, I just need to call it, passing an optional prefix as the first argument, and a unique id will be returned.
The value might be unique in a relative way, but it is not at all the best solution for many other use case examples. The method is just a lazy way to get a value that is unique each time it is called, and one way to do that is to have it so it just returns a count each time.
Making my own solution for this is not to hard, all is needed is the power of closure. I just write a self executing function expression and then inside the body of that function expression I have a local num variable, I then return a function that when called will step the num variable, and use that as part of the string that is returned that will be unique each time.
So it goes without saying that the value that is returned by the lodash uniqueid method is not all that unique. Depending on how unique you need the value to be though it is good enough, however it comes projects you might need to have a method that returns a value that has a lower probability of being duplicated.
A method such as this results in a value where there is still a non zero change of the value being duplicated, but it is still unique enough that the probability of that happening is pretty negligible.