Hacker News new | ask | show | jobs
30 seconds of code: Curated list of useful JavaScript snippets (github.com)
75 points by azorba1987 3109 days ago
7 comments

Besides the "Hey I can write stuff you can't read" factor, what's the point of the array and scientific notation here for the UUID generator[1]?

    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'm with you 100% that this is silly, show-off-y code golf at its worst. The fact that its purporting to generate something a bit sensitive (why else would you use the awkward `crypto.getRandomValues` interface?) is especially troublesome - sensitive code should be clear at all costs.

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!

Is brevity (in terms of kb) important for this snippets? If not, I think having more explicit variable names (`string` or even `str` instead of `s`) would be better for the purpose of understanding them in less than 30 seconds.

Otherwise, I enjoy reading some of them.

It shouldn't be. The programmer should be able to decide, if they care they'll already be using UglifyJS or some other minimizer.
I am not the owner of the project, but from my point of view, brevity should be quite important. Some names could be more descriptive, though.
I agree with you, brevity, as far as quantity of code required to accomplish the goal is concerned, but too many times brevity is confused for compactness, which to me, is the opposite of what you would want with these.
It's been while since I've had to code heavily in JS (when ES6 required transpiling from Babel), so I'm fuzzy on the syntax. But what does the underscore and the use of the fat arrow mean in this context?

https://github.com/Chalarangelo/30-seconds-of-code#current-u...

> Use window.location.href to get current URL.

      var currentUrl = _ => window.location.href;
The underscore is used for placeholders, that is variables you need to declare but you're not going to use. In this case, I guess, the author thinks that this looks better than

    () => window.location.href
Fat arrow is used to define a lambda function. The left-hand side of the arrow is argument list (_ is used to indicate lack of used arguments) and the right-hand side is the function body. It is equivalent to:

   var currentUrl = function () { return window.location.href; }
> _ is used to indicate lack of used arguments

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)`

It is not the same as that. the fat arrow doesn't change the value of "this" while the function definition does.
Given that "this" isn't referenced in the function, though, it's practically equivalent.
I think one is more efficient memory wise but I'm not sure which one.
The non-fat-arrow one, as it does not need to carry around the context of `this` with it.
the `=>` de-sugars to:

    var currentUrl = function(_) {
        return window.location.href;
    }
the underscore is used so they don't have to type `() =>` instead
Ahhh. I think I was confused why referring to `window.location.href` would be needed to be put into a function, and then called as `currentUrl()`, rather than having currentUrl be a string value. Is this best practice? I mean, is there some `window.location.href` isn't a global object?
Because the value may change. If 'currentUrl' was a constant (eg. `const currentUrl = window.location.href`) it would capture the href at the start of the application, even though it might change later on (history API, pushstate etc).
Why wouldn't you just reference `window.location.href` when needed, instead of wrapping it up in `currentUrl`?
Yeah that was my question. I was racking my head thinking of when this window.location.href wouldn't refer to what a program would want given how it almost acts like a global function in some ways (e.g. `window.location.href="http://example.com"` can be used to change the page). Maybe currentUrl is supposed to be a wrapper just incase window.location.href changes (which seems highly unlikely but again, I'm out of the loop with modern JS).
Some snippets, like this, read a lot like codegolf functions.
Code Golf is about using the most terse syntax (and frankly, showing off while doing it).

This 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.

Note that not all of this code is performant.

The 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...

Given recent discussions mentioning tools like Black Duck Software that looks for per-line signatures from open source projects, is there any information on any needed licensing for any of these? I know they're snippets, but I also know there are companies like SCO out there.
In the current JS world of ever-increasing complexity, it's a breath of fresh air to see a useful and simple display of JS code. Thanks for sharing.
All that's left is to copy-paste all of these into a module and publish it to NPM.

/s

The "Randomize order of array" snippet isn't actually random. It would just confuse the sorting algorithm.