Skip to content

Instantly share code, notes, and snippets.

@tabularelf
Last active September 11, 2023 12:10
Show Gist options
  • Save tabularelf/a23d06083da23ab62a7bc24326b5ce98 to your computer and use it in GitHub Desktop.
Save tabularelf/a23d06083da23ab62a7bc24326b5ce98 to your computer and use it in GitHub Desktop.
Listionary (For converting an array of structs or struct of arrays into a list/dictionary combo, with method accessors!)
function Listionary(_object) {
static __Value = function(_pos) {
if (argument_count > 1) {
struct_set_from_hash(list[_pos], hash, argument[1]);
return;
}
return struct_get_from_hash(list[_pos], hash);
}
static __ListGet = function(_pos) {
return list[_pos];
}
var _len = is_struct(_object) ? variable_struct_names_count(_object) : array_length(_object);
var _dict = {};
var _list = [];
var _i = 0;
// Array of Structs
if (is_array(_object)) {
var _names = [];
var _ii = 0;
repeat(_len) {
if (is_struct(_object[_ii])) {
var _structNames = variable_struct_get_names(_object[_ii]);
array_copy(_names, array_length(_names), _structNames, 0, array_length(_structNames));
} else {
array_push(_names, string(_object[_ii]));
}
++_ii;
}
_names = array_unique(_names);
var _entriesCount = array_length(_names);
repeat(_entriesCount) {
var _j = 0;
if (_i >= _len) break;
repeat(_entriesCount) {
var _name = _names[_j];
_value = (_i < _len) ? (_object[_i][$ _name]) : undefined;
if (array_length(_list) <= _j) array_push(_list, {});
_list[_i][$ _name] = _value;
_dict[$ _name] = method({list: _list, hash: variable_get_hash(_name)}, __Value);
++_j;
}
++_i;
}
}
// Struct of Arrays
if (is_struct(_object)) {
var _names = struct_get_names(_object);
var _entriesCount = struct_names_count(_object);
repeat(_entriesCount) {
var _j = 0;
if (_i >= _len) break;
repeat(_entriesCount) {
var _name = _names[_j];
var _entry = _object[$ _name];
var _value = (_entry != undefined) && (_i < array_length(_entry)) ? (_entry[_i]) : undefined;
if (array_length(_list) <= _j) array_push(_list, {});
_list[_i][$ _name] = _value;
_dict[$ _name] = method({list: _list, hash: variable_get_hash(_name)}, __Value);
++_j;
}
++_i;
}
}
return {
dict: _dict,
list: method({list: _list}, _Get)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment