Skip to content

Instantly share code, notes, and snippets.

@C-Ezra-M
Last active February 27, 2025 20:41
Show Gist options
  • Save C-Ezra-M/dc7c0ae5acaf6b4ee0be4f01b7826510 to your computer and use it in GitHub Desktop.
Save C-Ezra-M/dc7c0ae5acaf6b4ee0be4f01b7826510 to your computer and use it in GitHub Desktop.
Algodoo dict library
// Copyright (c) 2025 C.Ezra.M <cezram AT proton DOT me>
// This code is licensed under the MIT License
/** Dict v1.0
*
* To use this library, do either:
*
* - Import it with Reflection.ExecuteFile("path/to/dict.txt")
* - Copy-paste it into the Algodoo console
*/
Scene.my._arrayWithoutFirst = (array) => {
end = string.length(array) - 1;
array(1..end)
};
Scene.my._dictIndexOf = (d, key, i) => {
string.length(d) == 0 ? -1 : {
d(0)(0) == key ? i : {
Scene.my._dictIndexOf(Scene.my._arrayWithoutFirst(d), key, i + 1)
}
}
};
Scene.my._dictHas = (d, key) => {
Scene.my._dictIndexOf(d, key, 0) != -1
};
Scene.my._dictSet = (d, key, value) => {
splitIndex = Scene.my._dictIndexOf(d, key, 0);
splitIndex == -1 ? {
d ++ [[key, value]]
} : {
d(0..(splitIndex - 1)) ++ [[key, value]] ++ Scene.my._arrayWithoutFirst(d(splitIndex .. (string.length(d) - 1)))
}
};
/** The purpose of this function is to make up for the fact Algodoo lists are immutable.
- d: the dictionary to modify
- key: the key to update
- func: function with 1 argument that the previous value will be passed into (undefined if it doesn't exist)
*/
Scene.my._dictUpdate = (d, key, func) => {
Scene.my._dictSet(d, key, func(Scene.my._dictGet(d, key)))
};
Scene.my._dictGet = (d, key) => {
Scene.my._dictGetDefault(d, key, undefined)
};
Scene.my._dictGetDefault = (d, key, default) => {
i = Scene.my._dictIndexOf(d, key, 0);
i == -1 ? default : { d(i)(1) }
};
Scene.my._dictWithout = (d, key) => {
splitIndex = Scene.my._dictIndexOf(d, key, 0);
splitIndex == -1 ? {
d
} : {
d(0..(splitIndex - 1)) ++ Scene.my._arrayWithoutFirst(d(splitIndex .. (string.length(d) - 1)))
}
};
Scene.my._dictFromKeys = (keys, value) => {
string.length(keys) == 0 ? [] : {
[[keys(0), value]] ++ Scene.my._dictFromKeys(Scene.my._arrayWithoutFirst(keys), value)
}
};
Scene.my._dictMerge = (d1, d2) => {
string.length(d2) == 0 ? d1 : {
Scene.my._dictMerge(Scene.my._dictSet(d1, d2(0)(0), d2(0)(1)), Scene.my._arrayWithoutFirst(d2))
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment