Created
October 3, 2023 20:42
-
-
Save run-dlang/b443baa72a773a75adf36653fb35245b to your computer and use it in GitHub Desktop.
Code shared from run.dlang.io.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import std.traits; | |
import std.meta; | |
import std.typecons; | |
import std.stdio; | |
import std.conv; | |
import std.array; | |
import std.algorithm.iteration : map, joiner; | |
import std.ascii; | |
import std.string; | |
void main() | |
{ | |
Style style = new Style(); | |
style.width(0.5); | |
style.minHeight(200); | |
writeln(style); | |
} | |
struct PropertyInfo | |
{ | |
string name; | |
string type; | |
} | |
const PropertyInfo[] PROPERTY_NAMES = | |
[ | |
PropertyInfo("width", float.stringof), | |
PropertyInfo("min-height", float.stringof) | |
]; | |
class Style { | |
mixin GenerateProperties!PROPERTY_NAMES; | |
override string toString() { | |
string result; | |
static foreach (elem; PROPERTY_NAMES) | |
{ | |
mixin("result ~= \"" ~ elem.name ~ ": \" ~ to!string(_" ~ toMemberName(elem.name) ~ ") ~ \"\\n\";"); | |
} | |
return result; | |
} | |
} | |
mixin template AddMemberAndSetter(string name, string typeName) | |
{ | |
mixin("private " ~ typeName ~ " _" ~ toMemberName(name) ~ ";"); | |
mixin("void " ~ toMemberName(name) ~ "(" ~ typeName ~ " value) { _" ~ toMemberName(name) ~ " = value; }"); | |
} | |
mixin template GenerateProperties(alias propMap) | |
{ | |
static if (isSomeString!(typeof(propMap))) | |
{ | |
static assert(0, "propMap must be an associative array"); | |
} | |
static foreach (elem; propMap) | |
{ | |
mixin AddMemberAndSetter!(elem.name, elem.type); | |
} | |
} | |
string toMemberName(string name) | |
{ | |
// Преобразует имя в формат camelCase | |
string result; | |
auto parts = name.split("-"); | |
foreach (idx, part; parts) | |
{ | |
if (idx == 0) | |
result ~= toLower(part); | |
else | |
result ~= std.ascii.toUpper(part[0]) ~ part[1 .. $].toLower; | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment