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
https://lemmy.sdf.org/pictrs/image/d227ffb4-6e8c-4033-9776-a505b3b3caca.png
βWhy are you trying to use βnewβ? Classes are so 2015! [β¦]β
[β¦]
Iβve seen something similar to this at work. Horrible.
Very DRY.
Thatβll be fun in a multi threaded setting!
What theme are you using, i like it!
validators is a shitty name for something that actually does type conversion.
This should be programmer horror
JS disgusts me
I think thatβs called a functor.
Dont look at C++ with std:: function
ββββ
ββββ