> ...no one I know is excited about working with GoF-style OO code these days
FYI, this is C#:
var namedFunctions = new Dictionary<string, Func<int, int, int>>() {
["multiply"] = (int x, int y) => x * y,
["add"] = (int x, int y) => x + y,
["subtract"] = (int x, int y) => x - y,
["divide"] = (int x, int y) => x / y,
};
log(namedFunctions["add"](x, y));
This is also C#:
var multiplyN = (int[] numbers) => numbers.Aggregate(1, (a, b) => a * b);
var addN = (int[] numbers) => numbers.Aggregate(0, (a, b) => a + b);
var subtractN = (int[] numbers) => numbers.Aggregate(0, (a, b) => a - b);
var divideN = (int[] numbers) => numbers.Aggregate(1, (a, b) => a / b);
log(multiplyN(new[]{1, 2, 3, 4}));
log(addN(new[]{1, 2, 3, 4}));
log(subtractN(new[]{1, 2, 3, 4}));
log(divideN(new[]{1, 2, 3, 4}));
As is this:
// Return a tuple
var runCalcsAsTuple = (int[] values) => {
return (
multiplyN(values),
addN(values),
subtractN(values),
divideN(values)
);
};
// Destructure the tuple
var (
multiplyResult,
addResult,
subtractResult,
dividResult
) = runCalcsAsTuple(new [] {2, 3, 4, 5});
Named tuple types are also kinda interesting:
using Profile = (
string Username,
(string Hn, string Mastodon) Socials
);
var profile = GetProfile();
var (hnHandle, mastodonHandle) = profile.Socials;
Profile GetProfile() => ("chrlschn", ("CharlieDigital", "@chrlschn"));
If you haven't looked at C# in a while, I'd recommend taking a look with a fresh set of eyes.
Small repo with examples comparing C# to JS and TS: https://github.com/CharlieDigital/js-ts-csharp