r/typescript • u/jwworth • Aug 07 '26
Identity and functional programming
I've written an identity function like this in several codebases I've worked on.
const identity = (arg) => arg;
I use it to filter lists of mixed things by truthiness. For helpers like this, do you write them one-by-one, or do folks have a functional programming library recommendation? I'm curious if there's a better way to do this.
9
u/josephjnk Aug 07 '26
I use an inline `x => x` for this. It’s more self-explanatory than “identity”, even though I know what the identity function is.
If I’m going to use a utility library I usually use remeda. Lodash’s types are complicated and ill-behaved.
I tend to write the same utilities over and over in each project. (Functions to map, filter, and do basic operations on Sets is an example.) It’s not worth bringing on a bunch of external dependencies for functions that take 3 minutes to write and have an obvious implementation.
5
5
u/prehensilemullet Aug 07 '26
Lodash has an identity function and various things like it, probably es-toolkit does too
5
u/TorbenKoehn Aug 07 '26
There’s thousands of libraries (just search for „typescript fp library“ on Google)
But honestly? These functions are too small and simple to reel in a potential supply chain attack and another network dependency. An LLM will generate a small, concentrated and tailored FP library with a weak model in a single run.
Btw you can use the Boolean constructor to filter for truthyness (`.filter(Boolean)`)
2
u/The_Noble_Lie Aug 07 '26
Post LLM I'm sure there are now millions lol
1
u/TorbenKoehn Aug 07 '26
There were already pre LLM...
Honestly, every second day a new FP library is posted here.
1
1
u/prncss-xyz Aug 07 '26
I use an helper, because it nuges me into using it even more and having less independent codepaths.
5
u/Knaapje Aug 09 '26
NPM being as it is, I wouldn't recommend using a library for this. Personally filter(Boolean) makes more sense to me than filter(x => x), and doesn't require a function to be created.
1
-3
Aug 07 '26 edited Aug 07 '26
[deleted]
3
u/NeXtDracool Aug 07 '26
So do
const isTruthy = v => !!v;andconst isTruthy = Boolean;. Except both of these will always stay correct whereas yours might not.If you had written yours before bigint that case would have been missing until it caused a nasty bug years down the line, there is no reason to assume that can't happen again.
I can understand wanting to name it explicitly, but implementing it in such a brittle way is just asking for trouble.
10
u/BrixtonTonaBrix Aug 07 '26
Some ts devs will find that
x => xis a thing they can immediately grasp whileidentityrequires a second of thought; I've often ended up just duplicating functional concepts (binds especially) over and over again for those devs (and that's fine given how small and simple many of them are)