30 seconds of code: Curated list of useful JavaScript snippets
github.com
github.com
var uuid = _ =>
( [1e7]+-1e3+-4e3+-8e3+-1e11 ).replace( /[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
)
The first piece evaluates to the static string '10000000-1000-4000-8000-100000000000'. Writing it using the array toString and scientific notation saves 8 bytes (or 10 if you remove the other whitespace) but is otherwise pointless.It'd be even better to use '00000000-0000-4000-0000-000000000000' as the "1" and "8" values aren't special. That would let you replace the /[018]/ with just /0/ too.
[1]: https://github.com/Chalarangelo/30-seconds-of-code/blob/mast...
I spent a bit longer than 30 seconds looking at it though, and I think the 8 is actually significant - according to the RFC,
> "Set the two most significant bits (bits 6 and 7) of the clock_seq_hi_and_reserved to zero and one, respectively."
The right shift by `c / 4` seems to be taking care of this, at least if JavaScript's shift operator works the way I think it does.
The `1`s are to facilitate the goofy string creation trick.
The fact that there's some discussion around the meaning of the code on HN is a bad thing, of course!
Otherwise, I enjoy reading some of them.
https://github.com/Chalarangelo/30-seconds-of-code#current-u...
> Use window.location.href to get current URL.
var currentUrl = _ => window.location.href; var currentUrl = function(_) {
return window.location.href;
}
the underscore is used so they don't have to type `() =>` insteadThis was a new syntax added to the language spec to reduce the amount of boilerplate required for common tasks.
Also, the "fat arrow function" handles "this" different inside of the function, so it can serve a slightly different function and in many event-handling cases it can be even more terse than traditional JS functions.
var currentUrl = function () { return window.location.href; }Note that this is a convention, not a requirement for the syntax (like in some other languages).
I've spent at least a few mins troubleshooting why `_.map` (from `lodash` npm module) didn't work inside of a fat function while fixing another developer's defect.
If you use `_` as a valid const/variable identifier anywhere in your codebase, I would recommend you ditch `_ => alert(1)` for something more obscure like `ø => alert(1)`
() => window.location.hrefThe Difference Between Arrays[1] snippet is O(n^2), but you could make it much more performant for many data types.
[1] https://github.com/Chalarangelo/30-seconds-of-code#differenc...
/s