πŸ“£ Post by sebastiancarlos

2024-11-17 πŸ”„ programmerhumor

Real Programmers Implement Functions On Top Of Classes
class BaseFunction {
static #allowInstantiation = false;
constructor(...args) {
if (!BaseFunction.#allowInstantiation) {
throw new Error(
"Why are you trying to use 'new'? Classes are so 2015! Use our fancy 'run' method instead!"
);
}
for (const [name, validator] of this.parameters()) {
this[name] = validator(args.shift());
}
}
parameters() {
return [];
}
body() {
return undefined;
}
static run(...args) {
BaseFunction.#allowInstantiation = true;
const instance = new this(...args);
BaseFunction.#allowInstantiation = false;
return instance.body();
}
}
class Add extends BaseFunction {
parameters() {
return [
["a", (x) => Number(x)],
["b", (x) => Number(x)],
];
}
body() {
return this.a + this.b;
}
}
console.log(Add.run(5, 3)); // 8

sebastiancarlos

https://lemmy.sdf.org/pictrs/image/d227ffb4-6e8c-4033-9776-a505b3b3caca.png

πŸ”„ programmerhumor

πŸ’¬ Replies

2024-11-23 30p87

β€œWhy are you trying to use β€˜new’? Classes are so 2015! […]”
[…]

2024-11-19 CrossbarSwitch

I’ve seen something similar to this at work. Horrible.

2024-11-18 NigelFrobisher

Very DRY.

2024-11-18 FiskFisk33

That’ll be fun in a multi threaded setting!

2024-11-18 TunaSlap ┃ 1πŸ’¬

What theme are you using, i like it!

2024-11-17 bleistift2

validators is a shitty name for something that actually does type conversion.

2024-11-17 PanArab

This should be programmer horror

2024-11-17 Burghler

JS disgusts me

2024-11-17 Chais

I think that’s called a functor.

2024-11-17 navi

Dont look at C++ with std:: function

────

View thread

Next page (10-20)

────

πŸ“‘ Local feed

πŸ•οΈ Communities

πŸ”₯ Hashtags

πŸ”Ž Search posts

πŸ”‘ Sign in

πŸ“Š Status

πŸ›Ÿ Help