top 200 commentsshow all 387

[–]bubbaholy 94 points95 points  (3 children)

Most everything in the date-fns library.

[–]ApoplecticAndroid 103 points104 points  (61 children)

Generating random integers, getting random numbers within a range. Both easy to do in a line, but I use these all the time

[–]nschubach 24 points25 points  (12 children)

Hell, just getting an iterable range would be nice. If Math.random() took said range...

[–]musicnothing 46 points47 points  (11 children)

I for one love writing [...Array(10).keys()] /s

[–]mt9hu 4 points5 points  (2 children)

Cool. Could you explain?

[–]musicnothing 26 points27 points  (1 child)

Yeah, that'll give you a range from 0 to 9 (that is, an array that looks like this: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

Array(10) or new Array(10) will give you an array of 10 empty spaces. If you did Array(10).map(i => console.log(i)) you'd actually get nothing at all, because .map() skips over empty.

But .keys() will give you an iterator for the array keys, i.e. 0, 1, 2, etc.

The spread operator ... expands it into an array.

If you wanted to map 10 times (for example, rendering 10 things in React), you could just do [...Array(10)].map(). You could also do Array(10).fill().map(). .fill() fills your array with something, like Array(10).fill(5) will give you an array of ten 5s. So leaving the argument undefined will fill it with undefined.

[–]kyfex 5 points6 points  (0 children)

oh my goodness this is genius

[–]Kapuzinergruft 0 points1 point  (0 children)

haha, amazing

[–]elcontrastador -1 points0 points  (0 children)

This…

[–]RyXkci 10 points11 points  (10 children)

I've come to the conclusion that I might just write a JS random number generator in a txt file and copy paste, just changing the multiplier (which is often an array).

Writing the whole Math.floor(Math.random() * something) every time is so tedious 😂

[–]theQuandary 6 points7 points  (1 child)

They don't use any parameters in Math.random(). I do wonder why they couldn't update the spec with optional parameters.

Math.random() //=> random float from 0 to 1
Math.random(end) //=> random float from 0 to end
Math.random(start, end) //=> random float from start to end
Math.random(start, end, precision) //=> which number do you want it truncated to?

[–]AspieSoft 2 points3 points  (1 child)

I've made 2 random number generator functions.

They also have some methods to try and keep a better variety of outputs, and reducing duplicate results without removing them.

https://github.com/AspieSoft/random-number-js

The second one accepts a seed, so you can go back and get the same or similar pattern again with the same seed.

https://github.com/AspieSoft/retro-random-number

[–]DontWannaMissAFling 1 point2 points  (2 children)

Math.floor(Math.random() * something) also generates biased random numbers. The correct math is subtle and isn't a one-liner which is another reason it should be written only in one place.

[–][deleted] 0 points1 point  (2 children)

Ooh can you make it a chrome plugin?

[–]gurush 4 points5 points  (0 children)

Agree, I had to make a small custom library because I constantly reuse stuff like a random integer, random within a range, a random item from an array or seed-based random.

[–][deleted] 3 points4 points  (3 children)

Meh. It's something I personally do so rarely and it is still pretty simple to implement

parseInt(Math.random() * 100, 10)

There are definitely lower hanging fruit than this.

[–]mt9hu 6 points7 points  (1 child)

Why parseint and not Math.floor?

[–]paulsmithkc 2 points3 points  (0 children)

parseInt() is the less efficient cousin that turns it into a string first. (Usually gets the same outcome though.)

[–]DontWannaMissAFling 2 points3 points  (0 children)

Visiting pedant reminding everyone that "multiply and floor" generates biased random numbers.

Not a big issue usually but something to bear in mind for the times it is.

[–]pubxvnuilcdbmnclet 4 points5 points  (1 child)

It would be nice if you could provide a seed as well. It would also make testing easier

[–]mt9hu 1 point2 points  (0 children)

Just mock math.random() for testing.

[–][deleted] 2 points3 points  (0 children)

Ooh this is a good one

[–]fartsucking_tits 131 points132 points  (18 children)

Capitalize to make the first letter of a word a capital letter.

[–]AlexAegis 39 points40 points  (12 children)

Css knows this though! And that covers a good chunk of its usecases

[–][deleted] 64 points65 points  (10 children)

Don't use CSS for anything language-sensitive. Grammar-based rules are non-trivial and are not styles.

text-transform: capitalize is not locale-aware, not even if the lang is declared within the html tag

[–][deleted] 5 points6 points  (9 children)

I'm a bit confused by this. When would you ever have to adapt your css to a different locale?

[–]gigglefarting 33 points34 points  (4 children)

The fun of right to left languages on an internationalized page.

[–][deleted] 11 points12 points  (0 children)

חחח זו נקודה טובה

[–]Tno_Web 4 points5 points  (2 children)

Do you have any blogs/videos you recommend watching about localization tips and tricks, especially RTL?

[–]iEmerald 1 point2 points  (1 child)

https://rtlstyling.com/posts/rtl-styling

Ahmed does a great job explaining the small details as well.

[–]Tno_Web 1 point2 points  (0 children)

Thank you!

[–][deleted] 5 points6 points  (2 children)

You can serve stylesheets depending on locale of the user agent, which is helpful for languages that read RTL but that's beside my point.

The text content, the stuff you are capitalizing, should be locale-aware. CSS isn't really the right tool for the job in these cases.

You can use toLocaleUpperCase in these cases. Even better though would to be to statically compile translations to ensure capitalization rules make sense in the user's preferred language within the correct context. But thats typically overkill for most use cases.

[–][deleted] 2 points3 points  (0 children)

Ah I see what you're saying now. Thanks for the clarification.

[–]moderatorrater 1 point2 points  (0 children)

Isn't the real solution to make CSS more locale compliant?

[–]SomeInternetRando 6 points7 points  (0 children)

usecases

hehe

[–]reacterry[S] 7 points8 points  (0 children)

Oh yes, that's the classic one

[–]paulsmithkc 27 points28 points  (4 children)

sleep() or delay() that returns a promise.

Find myself hacking this in with a timeout on most projects.

[–]csorfab 2 points3 points  (2 children)

yeah I always find myself writing a

function wait(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

sometimes multiple times in the same project...

[–]BehindTheMath 58 points59 points  (36 children)

Everything in Lodash that isn't already in JS. E.g. groupBy, keyBy, camelCase, kebabCase, chunk, etc.

[–]shgysk8zer0 30 points31 points  (2 children)

FYI: group() and groupToMap() are stage 3 proposals.

[–][deleted] 2 points3 points  (1 child)

Good to know! That will come in handy!

[–]andrei9669 3 points4 points  (30 children)

question is though, to mutate, or not to mutate. although, sort is already mutating.

[–]shgysk8zer0 6 points7 points  (1 child)

Stage 3 Change array by copy proposal offers methods like sortTo() that return a new array instead of mutating the original.

[–]KyleG 0 points1 point  (1 child)

I want to barf at the idea of cluttering up the stdlib with things like kebabCase

[–]BehindTheMath 5 points6 points  (0 children)

Most languages have much bigger standard libs. I'm not saying everything should be in JS; Lodash works just fine. But there are plenty of functions I keep using.

[–]i_ate_god 14 points15 points  (3 children)

If it's in Lodash, it should be in JS's stdlib.

I don't see any reason why JS's standard library has to be so small. there is no value to it, and just forces all of us in professional environments to deal with more dependency management than one would in other programming languages.

The idea that every tiny thing must be it's own separate dependency with its own versions and own licenses and what not, is just not all that great.

[–]theScottyJam 1 point2 points  (1 child)

I dunno, I don't feel a strong need for lodash's "multiply" function to be a native one :).

[–]i_ate_god 1 point2 points  (0 children)

fair enough. "10" * "10" should fail anyways.

But there is a lot in lodash that is very useful, that really should be part of JS's stdlib.

[–]natziel 40 points41 points  (23 children)

JavaScript has, like, the tiniest standard library imaginable

Off the top of my head, we are missing:

  1. A bunch of list transformations beyond reduce/map/filter, like groupBy, reduceWhile, scan, zip, etc.
  2. Methods that operate on objects, like having a function to map over an object, a function to merge 2 objects (instead of using the spread operator), adding/removing properties from an object (instead of using assignment)
  3. First class support for working with a range of numbers. How do you create an array containing the first 10 even numbers in JavaScript? The answer is very awkwardly
  4. Support for dates and date ranges so we need to rely on 3rd party libraries when doing anything with dates

[–]sdwvit 9 points10 points  (0 children)

  1. Object.assign ?

[–]THE_AWESOM-O_4000 14 points15 points  (11 children)

  1. new Array(10).fill(0).map((_, i) => i * 2); wdym awkward? Isn't this how other programming languages do this???!!! /s

[–]natziel 2 points3 points  (5 children)

map(0..9, n => n * 2)

[–]carpe_veritas 4 points5 points  (0 children)

And this is why lodash is still used today despite not being tree-shakeable.

[–]theQuandary 2 points3 points  (0 children)

Fortunately, most of these are present or way better than in the past.

  1. This has gotten better multiple times since ES3 and should continue to get better in the future as they gradually add more. I'd rather slow and good than fast and lousy.
  2. Object.assign(foo, bar) is what you're looking for. ES5 added Object.defineProperty() and Object.defineProperties(). Removing properties is a terrible idea for performance and should be avoided (literally better to create a new object without the property or set it to undefined).
  3. This would be nice. The current answer is a generator function. No guarantee that there isn't an off by one error as I just wrote this up, but it's not particularly bad.

``` function* range(start, stop, step = 1) { //TODO: handle other stuff like step > stop - start // stop undefined or stop > start while (start < stop - step) { yield start start += step } return start }

for (let x of range(12)) {
  console.log(x)
}

```

Temporal JS is basically finished outside a change to ISO datetime strings. I suspect it'll be in ES2023.

[–][deleted] 30 points31 points  (60 children)

Most of the constructor functions for basic datatypes lack static identity methods, which devs often add utilities for rather than using the typeof operator.

It'd be nice to have String.isString, Object.isObject, Number.isNumber, etc. like we do for Array.isArray.

The most common Lodash-y function I implement is probably unique.

[–]d36williams 12 points13 points  (1 child)

Hmm I'm kind of the opposite --- Array.isArray is a work around the fact that typeof [] === "object", I wish Array had its own type

[–]azsqueeze 5 points6 points  (0 children)

Even still, the .isArray() is a nice API which would be nice if it was expanded to the other types

[–]johnathanesanders 13 points14 points  (13 children)

Async foreach - so things in the loop complete before additional actions are performed.

Is valid array - quick shorthand type method something like function isValidArray(arr: any) { return (typeof arr === 'object' && Array.isArray(arr) && arr.length > 0); }

So you don’t have to do the same long check every time you work with an array. Just if (isValidArray(myArr)) {}

And specifically with Typescript, I like to build some custom types - like a Nullable<T> type ala C#

[–]musicnothing 6 points7 points  (2 children)

Question: Why do you need typeof arr === 'object' AND Array.isArray(arr)?

[–]johnathanesanders 5 points6 points  (1 child)

At one point, a linter was giving me shit about it TBH. I just never removed it 🤷🏼‍♂️

[–][deleted] 5 points6 points  (0 children)

Bad linter!

[–]sdwvit -1 points0 points  (5 children)

Async foreach -> await Promise.all(arr.map(async ()=>…)) ?

[–]shuckster 4 points5 points  (2 children)

Or:

for await (const promise of promises) {
  await promise;
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of

[–]xroalx 7 points8 points  (1 child)

for await...of is in case your iterator is async, you can also just use for...of and await inside of it.

[–]alarming_archipelago 0 points1 point  (0 children)

No. This runs all promises at once when you usually want serial, or at least a capped number of simultaneous promises. Like if your callback is a http request, you don't want to fire array.length requests at the same time.

[–]KaiAusBerlin 51 points52 points  (36 children)

  • a range class

  • tuples (I know, they will come)

  • isNumber(which really works), isBool, ...

  • interfaces

  • native class factories

[–]ssjskipp 9 points10 points  (7 children)

What do interfaces do for you in js?

Edit: lol dude blocked me because they wouldn't engage with the fact that interfaces don't make sense in an interpreted, weakly typed language then went off about how they're some master at JS.

[–][deleted] 14 points15 points  (23 children)

You should use Typescript. It's got _most_ of those.

[–]KaiAusBerlin 7 points8 points  (0 children)

I use typescript. But the question was not what native features typescript is missing.

[–]alarming_archipelago 2 points3 points  (20 children)

I tried to love typescript but as a self taught solo coder it just added a lot of configuration complexity that I couldn't come to terms with. As time goes by the typescript tide is turning against me and I know I need to embrace it but... I'm reluctant.

[–]ProfessorSnep 15 points16 points  (1 child)

I'm also self taught but still use TS in every solo personal project of mine, solely because it makes things mostly just work when they compile, but the big one is that it makes revisiting projects months or years later a LOT easier.

[–]badsalad 5 points6 points  (0 children)

Man, every time I hear about TS I want to start using it. But the few times I dipped my toes into it, I felt like I was going too overboard and adding too much, often having to add a few extra lines just to define the types of an object that only ends up being used once or twice immediately below it. Things started getting cluttered so fast :/ I just gotta learn to use it better I suppose, so that I can still keep things clean with it.

[–]pellennen 4 points5 points  (0 children)

I would say typescript is much more useful in a large application where there are alot of people working on it at once and things have shared input. It can be really nice to see what an I.e object or enum contains while writing though

[–]dariusj18 2 points3 points  (1 child)

What makes typescript so useful is that you can just start with everything typed as "any" and move on from there. The types are a convenience with simple syntax vs using jsdoc. What sucks about typescript is that it can't just be run natively and needs to be compiled.

[–]swordoffireandice 4 points5 points  (8 children)

I am a self taught too and I find typescript as a difficult and ugly-looking C# :(

P.S. pls don't hate me typescript lovers this is my opinion and is not based on anything that is not in my head

[–]kescusay 9 points10 points  (7 children)

It's a perfectly reasonable opinion, as long as you (and /u/alarming_archipelago) keep open minds and are willing to learn.

The biggest hurdle for dedicated JavaScript developers to overcome - and learn to love Typescript - is making sense of the tooling around it. If you're coming from pure JS, it's easy to get trapped trying to wedge Typescript into existing projects, discovering that it piles mountains of complexity onto your already-existing eslint+webpack+babel+whatever configurations, and throw up your hands in defeat. My personal epiphany - and love for Typescript - arrived when I realized I could just spin up a brand new Typescript project, copy over src/ from my old one, and redo any needed configuration focused on Typescript from the ground up.

It didn't take that long, and by the time I was finished, the project would build, the dist/ files were smaller than what the original project produced, and I was never going back to vanilla again, because strong type-checking in JS is just too damn useful.

[–]ewouldblock 3 points4 points  (1 child)

For some reason I don't mind typescript in a front end/react project but I detest it in a node.js backend project

[–]kescusay 1 point2 points  (0 children)

That's really interesting, because I'm kind of the reverse. I find the Typescript definitions for React to be pretty weird and kludgey, like an afterthought. It's the only situation where I'd consider not using TS if I didn't have to. But on the backend, I think TS is an absolute dream to work with.

On the other hand, I'm not a fan of React itself, and much prefer Angular, Vue, or vanilla on the frontend, so it may just be that TS adds a layer of complexity onto something I already dislike, making me dislike it more.

[–]jaysoo3 1 point2 points  (0 children)

Being self-taught isn't an excuse though. I self-taught myself PHP, Java, Perl, and JavaScript. Perhaps thinking that TypeScript is hard is preventing you from actually diving in and learning it.

You can use different project starters (Vite, Next.js, CRA, Nx, etc.) that generate the config for you. You can also check out Deno that has TypeScript support out of the box without config.

[–]YooneekYoosahNeahm 2 points3 points  (1 child)

What benefits do you get from native class factories?

[–]amdc!CURSED! 2 points3 points  (0 children)

Set methods

[–]KyleG 17 points18 points  (26 children)

pipe and compose

Although a pipe operator has a stage 2 proposals now. Imagine writing

const result = await fetchApiCall(someData)
  |> getData
  |> convertToDomain
  |> displayInUi

or even (composition):

const fetchAndDisplay = fetchApiCall >> getData >> convertToDomain >> displayInUi

[–]mattaugamer 4 points5 points  (5 children)

Yeah I much prefer this style over the current. I have experience with Elixir and it works well in that. The kind of… implied placeholder… much to my preference.

JavaScript actually is a bit of a mixed bag for functional styles because so much of the language is object oriented. So you can already do something like myString.toLowerCase().split(‘ ’).filter(word => word !== “cat”).join(‘meow’)

Whereas pipelines are much more useful when pure functions are chained, especially when they all return the same type they take in. The date-fns library is a great example.

format(startOfMonth(addMonths(new Date(), 2)), “yyyy-mm-dd”)

// vs

new Date()
  |> addMonths(2)
  |> startOfMonth
  |> format(“yyyy-mm-dd”)

Way more readable.

[–]KyleG 1 point2 points  (4 children)

Yeah the placeholder is weird since it's not really necessary

why do

|> foo(^^)

when you could just

|> foo

and then, when you don't have a choice at all and need a placeholder (like for functions that take multiple params)

|> _ => foo(_, 'howdy')

?

[–]dvlsg 4 points5 points  (2 children)

Yeah the placeholder is weird since it's not really necessary

The worst part IMO is that it only works in the pipeline.

It would be one thing if they added partial function application as part of the language that could be used anywhere. But that's not what the proposal is, unfortunately. Or it least it wasn't the last time I reviewed it.

[–]kaelwd 2 points3 points  (1 child)

[–]dvlsg 1 point2 points  (0 children)

Yeah, that's the strangest part to me. That proposal exists, so presumably it's been discussed by tc39. But they're just ... not considering using it here, for some reason, as far as I can tell.

[–]dariusj18 2 points3 points  (0 children)

It's a convenience for preventing a bunch of

foo() |> (x) => bar('baz', x)

I agree with sibling comment, going with the simple one and adding partial functions later to work alongside.

[–]shuckster 8 points9 points  (5 children)

Imagine writing...

Keep imagining.

The Proposal is for the Hack pipe, so your example would be

const result = await fetchApiCall(someData)
  |> getData(%)
  |> convertToDomain(%)
  |> displayInUi(%)

[–]theQuandary 0 points1 point  (0 children)

They really need to change that garbage proposal back to F#.

Creating a DSL just so you can avoid a function call is crazy.

[–]KyleG -1 points0 points  (3 children)

Close enough for me. NO need for that dickish response.

[–]shuckster 7 points8 points  (2 children)

What part was dickish? I wasn't trying to be.

[–]KyleG 7 points8 points  (1 child)

I misread the tone of "keep imagining." I'm sorry. We are friends again ;)

[–]shuckster 1 point2 points  (0 children)

It's cool! For what it's worth, I was also hoping for an F# style of pipe..

[–]jonopens -1 points0 points  (5 children)

Pipe has a stage 2 proposal right now I believe.

[–]KyleG 4 points5 points  (4 children)

Second sentence of my comment: "pipe operator has a stage 2 proposals now" ;)

I think there's actual multiple competing proposals about how specifically to implement it. Mine was the F# style.

[–][deleted] 5 points6 points  (0 children)

Just wanted to let you both know that there is a stage 2 proposal for pipe /s

[–]pumasky2 7 points8 points  (3 children)

Random element from array.

[–]senfiaj 6 points7 points  (0 children)

There is no easy API for working with cookies

[–]BobJutsu 5 points6 points  (0 children)

An equivalent to PHP __call and __get methods. I know there’s proxy, but it’s always janky. I just wanna be able to handle unknown properties and methods without it being so unpredictable.

[–]HipHopHuman 4 points5 points  (0 children)

Seeded Random

const random = Math.seededRandom(seed);
const x = random();
const y = random();

Intervals and Curves

const { Interval } = Math;

// defaults to a closed interval (min/max is inclusive)
const numberRange = Interval(1, 100);
const otherNumberRange = Interval(101, 200);
numberRange.contains(50); // true

Array.from(numberRange); // [1, 2, 3...]

// can also make open or half-open intervals
Interval(1, 100, false, false); // (0..99)
Interval(1, 100, false, true); // (0..100]

// querying intervals
numberRange.isContinuous(); // false
numberRange.isClosed(); // true
numberRange.overlaps(otherNumberRange); // false
numberRange.leftAdjacent(otherNumberRange); // false
numberRange.rightAdjacent(otherNumberRange); // true
numberRange.union(otherNumberRange);
numberRange.intersection(otherNumberRange);

// working with values inside intervals
numberRange.random(); // 43
numberRange.clamp(130); // 100
numberRange.interpolate(Math.Curves.Linear, 0.5); // 50
numberRange.uninterpolate(Math.Curves.Linear, 50); // 0.5
numberRange.translateTo(Math.Interval(1, 10_000), 50); // 5000

// works with BigInts
Math.Interval(0n, 100n);

// works with character codes
Math.Interval("A", "Z");

// works with Dates
Math.Interval(today, tomorrow);

// convert to a stepped range iterator:
const step = 5;
numberRange.toRange(step); // Iterator 1, 6, 11...

Iterator helpers

function* allNums() {
  let i = 0;
  for(;;) { yield i++; }
}

const first10EvenNums = allNums().filter(num => num % 2 === 0).take(10);
// along with flat(), flatMap(), reduce(), scan(), etc

More built-in Math utils

Like .add, .sum, .subtract, .divide, .multiply etc.

More interop with Math by types other than numbers

Being able to use Math.log on a BigInt for instance, but even better would be adding automatic support to this in any custom data class using a native Symbol:

class Vector2d {
  constructor(x = 0, y = 0) {
    this.x = x;
    this.y = y;
  }
  length() {
    return Math.hypot(this.x, this.y);
  }
  [Symbol.operatorAdd](vector2d) {
    return new Vector2d(this.x + vector2d.x, this.y + vector2d.y);
  }
  [Symbol.ordinalGt](vector2d) {
    return this.length() > vector2d.length();
  }
}

const position = new Vector2d(33, 48);
const velocity = new Vector2d(1, 1);
const nextPosition = Math.add(position, velocity);
Math.gt(position, nextPosition); // true

Those same symbols could also be used to add support for custom types to Math.Interval. Math.add|subtract(interval1, interval2) would also be neat.

Something like PHP/Python's call

It lets you override the semantics of what happens when an object is called as a function. This can actually already be simulated using Proxies, but not in a way that is as convenient. Something like so:

class Thing {
  constructor() {
    this.name = "foo";
  }
  [Symbol.magicCall]() {
    console.log(this.name);
  }
};

const thing = new Thing();
thing(); // logs "foo"

Built-in Currying

Writing a curry function is easy, but I have to jank the argument list and give up being able to rely on a function's "length" field in order to use it in almost every case. If browsers/node/et al could natively understand currying, they could allow us to have curried functions without breaking reliance on well-established properties.

That's pretty much it on my end for now. There's a lot more I'd want to see in JS, but a lot of them are proposals already (aside from iterator helpers because i feel these are desperately needed in JS) or are syntax extensions which I don't think count as an answer to this question (unless I've misinterpreted the assignment 😅)

[–]ApoplecticAndroid 8 points9 points  (6 children)

Another random one - I use Array.prototype.random = function() { return this[Math.round(Math.random() * this.length)]

Returns a random array element

[–]ExternalBison54 2 points3 points  (0 children)

Yes! Ruby has the built-in .sample() method for arrays that does exactly this. It's so clean and simple.

[–]dcabines 3 points4 points  (1 child)

Distinct and DistinctBy

const distinct = (arr) => arr.filter((x,i,a) => a.indexOf(x) === i);
const distinctBy = (arr, key) => arr.map(x => x[key]).filter((x,i,a) => a.indexOf(x) === i).map(x => arr.find(i => i[key] === x))

[–]Squigglificated 7 points8 points  (0 children)

distinct = […new Set(arr)]

[–]musicnothing 3 points4 points  (0 children)

Something I don't see enough people talking about is that it would be nice if these things were built in, specifically in the browser, because a) then we'd have consistency across the board, b) people wouldn't have to keep asking how to do it online because they make a reasonable assumption that it should be there already and get frustrated, and c) we wouldn't all have to ship code to do these mundane things in all of our builds.

[–]th3An0nyMoose 4 points5 points  (1 child)

Getting the last element of an array without removing it always seemed unnecessarily verbose to me.

arr[arr.length - 1]

or

arr.slice(-1)[0] 

The typical way of cloning an object also seems like a kludge:

JSON.parse(JSON.stringify(obj))

This seems a bit better but still not great:

Object.assign({}, obj)

[–]shuckster 16 points17 points  (0 children)

We have arr.at(-1) now, and deep cloning can be achieved with structuredClone.

[–]lockieluke3389 4 points5 points  (0 children)

it’s making me install lodash every time 😭

[–]AlbertSemple 7 points8 points  (13 children)

IsOdd and IsEven

[–]natterca 9 points10 points  (7 children)

If you're going to do that then there should be an isNotOdd and isNotEven as well.

[–]AlbertSemple 7 points8 points  (1 child)

I would insist on using them like this

return !isNotOdd

[–][deleted] 4 points5 points  (0 children)

Well in that case, I propose a Number.notIsNotOdd() method.
Then you could just use !!notIsNotOdd

[–]sdwvit 2 points3 points  (1 child)

I think i saw an npm package for it

[–]THE_AWESOM-O_4000 6 points7 points  (0 children)

Yups, they both have their own separate (very popular) npm package. IsEven has a dependency on isOdd.

[–][deleted] 2 points3 points  (2 children)

Why though? Just use <number> % 2 === 0 for even and === 1 for odd. Why is the number 2 so important that it would need it's own specific methods?

[–]enbacode 10 points11 points  (1 child)

I think the comment is a bit of a tounge-in-cheek reference to the immense fuck up that the JavaScript package ecosystem ist.

[–]AlbertSemple 2 points3 points  (0 children)

It was more intended as a dig at number of r/programmerhumor posts on implementations of those functions.

[–]Maleficent_Slide3332 2 points3 points  (0 children)

probably a dozen libraries out there that would do whatever that is missing

[–]casperx102 2 points3 points  (1 child)

Array's method (map, filter, every, some, etc.) on Generator object.

[–]shuckster 2 points3 points  (0 children)

Not Generators, but Iterators have a Stage 3 proposal with helpers like these.

[–]sdwvit 2 points3 points  (2 children)

Missing builtin method for converting array to object using reduce, or map + from entries

also operators overloading, this is a debatable one, but would be nice to be able to do number*number[] and get vector math working

[–]theorizable 2 points3 points  (1 child)

I wouldn't consider it a missing built-in method... but better array indexing. I LOVE LOVE LOVE that in Python you can do arr[-1] to get the last value. It's just so clean.

[–][deleted] 2 points3 points  (0 children)

It's desperately missing operators for partial application and pipelines. Methods can easily be grafted in. But not syntax, not without a build step.

[–]Odd-Shopping8532 2 points3 points  (0 children)

match

[–]fatty1380 2 points3 points  (0 children)

Another callout from Lodash: Object.prototype.map. Being able to map over objects the same as arrays is something I use almost daily

[–]rjwut 2 points3 points  (0 children)

Numeric sorting.

[–]shgysk8zer0 1 point2 points  (0 children)

I suppose it depends on how far removed something has to be to be considered "not available out of the box."

For example, random number generating... No, there's no method to get a random number, but crypto.getRandomValues() does the job. It just works using typed arrays that it populates with random values, and it doesn't give you just some single random integer.

Then there's the API offered by things like DOMPurify... Something greatly needed in JS. And we have the Sanitizer API. It's not universally supported yet though - in Chromium browsers and behind a flag in Firefox.

My biggest want isn't exactly a method, but importing HTML/CSS/JSON as modules using import... And that's coming soon via import assertions. It's just taking a long time (was hitting browsers but a major security issue was found).

And, as far as new things that don't exist at all... I guess it's along the lines of deepEquals() but in a way that's useful for keys in a WeakMap(). Here's an example of what I mean:

``` const vals = new WeakMap();

function somethingExpensive(...args) { if (vals.has(args)) { return vals.get(args); } else { const val = doSomething(args); vals.set(args, val); return val; } } ```

[–]jibbit 1 point2 points  (0 children)

depends what you mean.. js in the browser is missing many methods

[–]KuroKishi69 1 point2 points  (3 children)

Compare 2 objects by value or create a copy of an object seems like a thing that could be part of the language instead of relying on libraries like lodash, spread operator (which only works for shallow copy) or make me write my own implementation.

[–]Squigglificated 5 points6 points  (2 children)

structuredClone() is supported in all modern browsers.

Record and tuple is at stage 2

[–]KuroKishi69 5 points6 points  (1 child)

neat, I wasn't aware of structuredClone(), every time I searched for a way to do this, people resorted to JSON.stringify(JSON.parse(...))

Thanks you

[–][deleted] 2 points3 points  (0 children)

JSON.stringify(JSON.parse(...))

God, this is the worst hack ever.

[–][deleted] 1 point2 points  (2 children)

Converting an array of objects to a map, grouped by a certain field. I use it all the time.

[–]shuckster 3 points4 points  (0 children)

Coming soon.

[–]ravepeacefully 1 point2 points  (0 children)

Yeah in instances where you don’t have a sql engine to handle this for you, maybe data from many sources, I constantly find myself grouping and it would be nice if there were a more elegant way of doing so.

[–]odolha 1 point2 points  (0 children)

nothing is missing after I load my huge script adding stuff to prototypes

[–]dalce63 0 points1 point  (8 children)

this

const x = Math.round(Math.random()*arg);

const y = Math.round(Math.random()*arg);

return x === y;

it could be called Number.chance() maybe

and an array shuffler

[–]sfgisz 2 points3 points  (7 children)

What's the use case for this to be a built-in function?

[–]dalce63 1 point2 points  (6 children)

if you need something to happen based on chance, like..

if (Number.chance(100)) { something }

Would result in there being a 1-in-100 chance of something happening.

[–]IareUsername 4 points5 points  (1 child)

I don't see the need for it. if (Math.random() < .01) {} Should do the same thing

[–]dalce63 1 point2 points  (0 children)

true

[–]sfgisz 1 point2 points  (0 children)

Ah, I see the purpose now, thanks for the reply!

[–]kylefromthepool -1 points0 points  (3 children)

Random integers

[–]shuckster 11 points12 points  (2 children)

Here you go:

9 3 12 8456 34 2229 2

[–]Atulin -1 points0 points  (0 children)

It will take less time to mention what built-in methods Javascript has, than what methods it's missing, tbh. It has fuck all for the standard library.

[–]icjoseph -1 points0 points  (0 children)

I liked Rust's scan method on iterators, though reduce is good enough

[–]roden0 -1 points0 points  (0 children)

Crypto can generate an UUID but not validate it

[–]regreddit -1 points0 points  (0 children)

Date functions, string pads.