\n\ntemplate \nstd::string filter(const std::string& str, P&& predicate) {\n return str\n | std::ranges::views::filter(std::forward(predicate))\n | std::ranges::to();\n}\n\n\n\n// Usage:\nstd::string str = \"Hello, World!\";\nstd::string filtered = filter(str, [](char c){ return std::isalpha(c); });\nstd::cout << filtered << std::endl; // HelloWorld\n",
- "extension": "cpp"
- },
- {
- "title": "Palindrome",
- "description": "Check if a string is a palindrome or not.",
- "author": "majvax",
- "tags": ["string", "c++23"],
- "contributors": [],
- "code": "#include \n#include \n#include \n\nbool is_palindrome(const std::string& str) {\n std::string sanitized_string = str\n | std::ranges::views::filter([](char c){ return std::isalnum(c); })\n | std::ranges::views::transform([](char c){ return std::tolower(c); })\n | std::ranges::to();\n \n return std::ranges::equal(sanitized_string, sanitized_string | std::views::reverse);\n}\n\n\n\n// Usage:\nbool pal = is_palindrome(\"A man, a plan, a canal, Panama\"); // true\n",
- "extension": "cpp"
- },
- {
- "title": "Reverse String",
- "description": "Reverses the characters in a string.",
- "author": "Vaibhav-kesarwani",
- "tags": ["array", "reverse", "c++23"],
- "contributors": [],
- "code": "#include \n#include \n\nstd::string reverseString(const std::string& input) {\n std::string reversed = input;\n std::reverse(reversed.begin(), reversed.end());\n return reversed;\n}\n\nreverseString(\"quicksnip\"); // Returns: \"pinskciuq\"\n",
- "extension": "cpp"
- },
- {
- "title": "Split String",
- "description": "Splits a string by a delimiter",
- "author": "saminjay",
- "tags": ["string", "split"],
- "contributors": [],
- "code": "#include \n#include \n\nstd::vector split_string(std::string str, std::string delim) {\n std::vector splits;\n int i = 0, j;\n int inc = delim.length();\n while (j != std::string::npos) {\n j = str.find(delim, i);\n splits.push_back(str.substr(i, j - i));\n i = j + inc;\n }\n return splits;\n}\n\n// Usage:\nsplit_string(\"quick_-snip\", \"_-\"); // Returns: std::vector { \"quick\", \"snip\" }\n",
- "extension": "cpp"
- },
- {
- "title": "Transform",
- "description": "Transform a string with a function",
- "author": "majvax",
- "tags": ["string", "transform", "c++23"],
- "contributors": [],
- "code": "#include \n#include \n\ntemplate \nstd::string transform(const std::string& str, F&& transformer) {\n return str\n | std::ranges::views::transform(std::forward(transformer))\n | std::ranges::to();\n}\n\n\n\n// Usage:\nstd::string str = \"Hello, World!\";\nstd::string transformed = transform(str, [](char c){ return std::toupper(c); });\nstd::cout << transformed << std::endl; // HELLO, WORLD!\n",
- "extension": "cpp"
- }
- ]
- },
- {
- "name": "Vector Manipulation.md",
- "snippets": [
- {
- "title": "Filter",
- "description": "Filters a vector using a predicate function.",
- "author": "majvax",
- "tags": ["array", "filter", "c++23"],
- "contributors": [],
- "code": "#include \n#include \n\ntemplate \nauto filter(const std::vector& vec, P&& predicate) {\n return vec\n | std::views::filter(std::forward(predicate))\n | std::ranges::to>();\n}\n\n\n\n// Usage:\nstd::vector vec = {1, 2, 3, 4, 5};\nstd::vector filtered = filter(vec, [](int i){ return i % 2 == 0; });\n// filtered contains 2 and 4\n",
- "extension": "cpp"
- },
- {
- "title": "Remove duplicates",
- "description": "Removes duplicates from an vector of ints",
- "author": "AnkushRoy-code",
- "tags": ["vector", "remove", "duplicate"],
- "contributors": [],
- "code": "#include \n#include \n\nbool removeDuplicates(std::vector &input) noexcept {\n if (input.empty()) return false;\n const auto size = input.size();\n std::sort(input.begin(), input.end());\n\n auto last = std::unique(input.begin(), input.end()); // remove duplicates\n input.erase(last, input.end()); // resize vector and delete the undefined elements\n\n return size != input.size();\n}\n\n\n\n// Usage:\nstd::vector vec = {4, 2, 2, 8, 5, 6, 9, 9, 9, 8, 8, 4};\nremoveDuplicates(vec); // returns {2, 4, 5, 6, 8, 9}\n",
- "extension": "cpp"
- },
- {
- "title": "Remove n Occurences",
- "description": "Removes duplicates from an vector of ints",
- "author": "AnkushRoy-code",
- "tags": ["vector", "remove"],
- "contributors": [],
- "code": "#include \n#include \n#include \n\nbool removeOccurrences(std::vector& vec, const unsigned int n) noexcept {\n if (vec.empty() || n == 0) return false;\n\n const auto size = vec.size();\n std::unordered_map frequency; // count frequencies\n for (int num : vec) {\n frequency[num]++;\n }\n\n vec.erase( // remove elements with n number of occurrences\n std::remove_if(vec.begin(), vec.end(), [&frequency, n](const int x) {\n return frequency[x] == n;\n }),\n vec.end()\n );\n return size != vec.size();\n}\n\n\n\n// Usage:\nstd::vector vec = {4, 2, 4, 8, 5, 6, 8, 8, 4, 3 };\n\nint n = 3; // Remove elements that occur exactly 3 times\nremoveOccurrences(vec, n); // returns {2, 5, 6, 3}\n",
- "extension": "cpp"
- },
- {
- "title": "Transform",
- "description": "Transforms a vector using a function.",
- "author": "majvax",
- "tags": ["array", "transform", "c++23"],
- "contributors": [],
- "code": "#include \n#include \n\ntemplate \nauto transform(const std::vector& vec, F&& transformer) {\n using U = std::invoke_result_t;\n return vec\n | std::views::transform(std::forward(transformer))\n | std::ranges::to>();\n}\n\n\n\n// Usage:\nstd::vector vec = {1, 2, 3, 4, 5};\nstd::vector transformed = transform(vec, [](int i){ return i * 2; });\n// transformed contains 2, 4, 6, 8, 10\n",
- "extension": "cpp"
- }
- ]
- }
-]
+ {
+ "name": "Basics",
+ "snippets": [
+ {
+ "title": "Hello, World!",
+ "description": "Prints Hello, World! to the terminal.",
+ "author": "James-Beans",
+ "tags": [
+ "printing",
+ "hello-world"
+ ],
+ "contributors": [],
+ "code": "#include // Includes the input/output stream library\n\nint main() { // Defines the main function\n std::cout << \"Hello, World!\" << std::endl; // Outputs Hello, World! and a newline\n return 0; // indicate the program executed successfully\n}\n",
+ "extension": "cpp"
+ }
+ ]
+ },
+ {
+ "name": "Bit Manipulation",
+ "snippets": [
+ {
+ "title": "Find Non-Repeating Number",
+ "description": "Finds the number that appears only once in an array where every other number appears twice.",
+ "author": "ashukr07",
+ "tags": [
+ "bit-manipulation",
+ "xor"
+ ],
+ "contributors": [],
+ "code": "#include \n\nint find_non_repeating(const std::vector nums) {\n int result = 0;\n for (const int num : nums) {\n result ^= num;\n }\n return result;\n}\n\n// Usage:\nstd::vector nums = {4, 1, 2, 1, 2};\nfind_non_repeating(nums); // Returns: 4\n",
+ "extension": "cpp"
+ }
+ ]
+ },
+ {
+ "name": "Data Structure Conversion",
+ "snippets": [
+ {
+ "title": "Vector to Queue",
+ "description": "Convert vector into queue quickly",
+ "author": "mrityunjay2003",
+ "tags": [
+ "data structures",
+ "queue",
+ "vector"
+ ],
+ "contributors": [
+ "majvax"
+ ],
+ "code": "#include\n#include\n#include\n\ntemplate \nstd::queue vectorToQueue(const std::vector& v) {\n return std::queue(std::deque(v.begin(), v.end()));\n}\n\n\n\n// Usage:\nstd::vector vec = { 1, 2, 3, 4, 5 };\nvectorToQueue(vec); // Returns: std::queue { 1, 2, 3, 4, 5 }\n",
+ "extension": "cpp"
+ }
+ ]
+ },
+ {
+ "name": "Debugging",
+ "snippets": [
+ {
+ "title": "Vector Print",
+ "description": "Overloads the << operator to print the contents of a vector just like in python.",
+ "author": "Mohamed-faaris",
+ "tags": [
+ "printing",
+ "debuging",
+ "vector"
+ ],
+ "contributors": [],
+ "code": "#include \n#include \n\ntemplate \nstd::ostream& operator<<(std::ostream& os, const std::vector& vec) {\n os << \"[\"; \n for (size_t i = 0; i < vec.size(); ++i) {\n os << vec[i]; // Print each vector element\n if (i != vec.size() - 1) {\n os << \", \"; // Add separator\n }\n }\n os << \"]\"; \n return os; // Return the stream\n}\n\n// Usage:\nstd::vector numbers = {1, 2, 3, 4, 5};\nstd::cout << numbers << std::endl; // Outputs: [1, 2, 3, 4, 5]\n\n",
+ "extension": "cpp"
+ }
+ ]
+ },
+ {
+ "name": "File Handling",
+ "snippets": [
+ {
+ "title": "Find files recursively",
+ "description": "Find all the files in a directory and subdirectories using a predicate function.",
+ "author": "majvax",
+ "tags": [
+ "filesystem",
+ "file_search",
+ "c++17"
+ ],
+ "contributors": [],
+ "code": "#include \n#include \n#include \n\ntemplate \nstd::vector find_files_recursive(const std::string& path, P&& predicate) {\n std::vector files;\n std::error_code ec;\n\n if (!std::filesystem::exists(path, ec) || ec)\n return files;\n if (!std::filesystem::is_directory(path, ec) || ec)\n return files;\n\n auto it = std::filesystem::recursive_directory_iterator(path, ec);\n if (ec)\n return files;\n\n for (const auto& entry : it)\n if (!std::filesystem::is_directory(entry) && predicate(entry.path()))\n files.push_back(entry.path());\n\n return files;\n}\n\n\n\n// Usage:\n\n// Find all files with size greater than 10MB\nauto files = find_files_recursive(\"Path\", [](const auto& p) {\n return std::filesystem::file_size(p) > 10 * 1024 * 1024;\n});\n\n// Find all files with \".pdf\" as extension\nauto files = find_files_recursive(\"Path\", [](const auto& p) {\n return p.extension() == \".pdf\";\n});\n\n// Find all files writed after The New Year\n#include \n// need std=c++20\nauto jan_1_2025 = std::filesystem::file_time_type::clock::from_sys(\n std::chrono::sys_days{std::chrono::year{2025}/std::chrono::month{1}/std::chrono::day{1}}\n);\nauto files = find_files_recursive(\"Path\", [jan_1_2025](const auto& p) {\n return std::filesystem::last_write_time(p) > jan_1_2025;\n}),\n",
+ "extension": "cpp"
+ },
+ {
+ "title": "Find files",
+ "description": "Find all the files in a directory using a predicate function.",
+ "author": "majvax",
+ "tags": [
+ "filesystem",
+ "file_search",
+ "c++17"
+ ],
+ "contributors": [],
+ "code": "#include \n#include \n#include \n\ntemplate \nstd::vector find_files(const std::string& path, P&& predicate) {\n std::vector files;\n std::error_code ec;\n\n if (!std::filesystem::exists(path, ec) || ec)\n return files;\n if (!std::filesystem::is_directory(path, ec) || ec)\n return files;\n\n auto it = std::filesystem::directory_iterator(path, ec);\n if (ec)\n return files;\n\n for (const auto& entry : it)\n if (!std::filesystem::is_directory(entry) && predicate(entry.path()))\n files.push_back(entry.path());\n\n return files;\n}\n\n\n\n// Usage:\n\n// Find all files with size greater than 10MB\nauto files = find_files(\"Path\", [](const auto& p) {\n return std::filesystem::file_size(p) > 10 * 1024 * 1024;\n});\n\n// Find all files with \".pdf\" as extension\nauto files = find_files(\"Path\", [](const auto& p) {\n return p.extension() == \".pdf\";\n});\n\n// Find all files writed after The New Year\n#include \n// need std=c++20\nauto jan_1_2025 = std::filesystem::file_time_type::clock::from_sys(\n std::chrono::sys_days{std::chrono::year{2025}/std::chrono::month{1}/std::chrono::day{1}}\n);\nauto files = find_files(\"Path\", [jan_1_2025](const auto& p) {\n return std::filesystem::last_write_time(p) > jan_1_2025;\n}),\n",
+ "extension": "cpp"
+ },
+ {
+ "title": "List Directories",
+ "description": "Lists all the directories in a path.",
+ "author": "majvax",
+ "tags": [
+ "filesystem",
+ "directories",
+ "c++17"
+ ],
+ "contributors": [],
+ "code": "#include \n#include \n#include \n\nstd::vector list_directories(const std::string& path) {\n std::vector files;\n std::error_code ec;\n\n if (!std::filesystem::exists(path, ec) || ec)\n return files;\n if (!std::filesystem::is_directory(path, ec) || ec)\n return files;\n\n auto it = std::filesystem::directory_iterator(path, ec);\n if (ec)\n return files;\n\n for (const auto& entry : it)\n if (std::filesystem::is_directory(entry))\n files.push_back(entry.path());\n\n return files;\n}\n\n\n\n// Usage:\nauto directories = list_directories(\"Path\");\n",
+ "extension": "cpp"
+ }
+ ]
+ },
+ {
+ "name": "Math And Numbers",
+ "snippets": [
+ {
+ "title": "Binary to Unsigned Integer Conversion",
+ "description": "Converts a binary number represented as a string to its decimal equivalent.",
+ "author": "ashukr07",
+ "tags": [
+ "binary",
+ "conversion",
+ "c++20"
+ ],
+ "contributors": [],
+ "code": "#include \n#include \n#include \n\ntemplate \nT binary_to_uintegral(const std::string& binary) {\n if (binary.size() > sizeof(T) * 8)\n throw std::invalid_argument(\"binary string is too long\");\n return static_cast(std::bitset(binary).to_ullong());\n}\n\n// Usage:\nstd::string binary(64, '1'); // Binary 8 bytes long with all bits set to 1\nbinary_to_uintegral(binary); // Returns: 18446744073709551615\nbinary_to_uintegral(binary); // Compiles error: signed/unsigned mismatch\nbinary_to_uintegral(std::string(65, '1')); // Throws: std::invalid_argument\n",
+ "extension": "cpp"
+ },
+ {
+ "title": "Check Prime Number",
+ "description": "Check if an integer is a prime number",
+ "author": "MihneaMoso",
+ "tags": [
+ "number",
+ "prime"
+ ],
+ "contributors": [],
+ "code": "bool is_prime(int n) {\n if (n < 2) return false;\n if (n == 2 || n == 3) return true;\n if (n % 2 == 0) return false;\n for (int i = 3; i * i <= n; i += 2) {\n if (n % i == 0) return false;\n }\n return true;\n}\n\n// Usage:\nis_prime(29); // Returns: true\n",
+ "extension": "cpp"
+ }
+ ]
+ },
+ {
+ "name": "String Manipulation",
+ "snippets": [
+ {
+ "title": "Filter",
+ "description": "Filter a string with a predicate function",
+ "author": "majvax",
+ "tags": [
+ "string",
+ "filtering",
+ "c++23"
+ ],
+ "contributors": [],
+ "code": "#include \n#include \n\ntemplate \nstd::string filter(const std::string& str, P&& predicate) {\n return str\n | std::ranges::views::filter(std::forward(predicate))\n | std::ranges::to();\n}\n\n\n\n// Usage:\nstd::string str = \"Hello, World!\";\nstd::string filtered = filter(str, [](char c){ return std::isalpha(c); });\nstd::cout << filtered << std::endl; // HelloWorld\n",
+ "extension": "cpp"
+ },
+ {
+ "title": "Palindrome",
+ "description": "Check if a string is a palindrome or not.",
+ "author": "majvax",
+ "tags": [
+ "string",
+ "c++23"
+ ],
+ "contributors": [],
+ "code": "#include \n#include \n#include \n\nbool is_palindrome(const std::string& str) {\n std::string sanitized_string = str\n | std::ranges::views::filter([](char c){ return std::isalnum(c); })\n | std::ranges::views::transform([](char c){ return std::tolower(c); })\n | std::ranges::to();\n \n return std::ranges::equal(sanitized_string, sanitized_string | std::views::reverse);\n}\n\n\n\n// Usage:\nbool pal = is_palindrome(\"A man, a plan, a canal, Panama\"); // true\n",
+ "extension": "cpp"
+ },
+ {
+ "title": "Reverse String",
+ "description": "Reverses the characters in a string.",
+ "author": "Vaibhav-kesarwani",
+ "tags": [
+ "array",
+ "reverse",
+ "c++23"
+ ],
+ "contributors": [],
+ "code": "#include \n#include \n\nstd::string reverseString(const std::string& input) {\n std::string reversed = input;\n std::reverse(reversed.begin(), reversed.end());\n return reversed;\n}\n\nreverseString(\"quicksnip\"); // Returns: \"pinskciuq\"\n",
+ "extension": "cpp"
+ },
+ {
+ "title": "Split String",
+ "description": "Splits a string by a delimiter",
+ "author": "saminjay",
+ "tags": [
+ "string",
+ "split"
+ ],
+ "contributors": [],
+ "code": "#include \n#include \n\nstd::vector split_string(std::string str, std::string delim) {\n std::vector splits;\n int i = 0, j;\n int inc = delim.length();\n while (j != std::string::npos) {\n j = str.find(delim, i);\n splits.push_back(str.substr(i, j - i));\n i = j + inc;\n }\n return splits;\n}\n\n// Usage:\nsplit_string(\"quick_-snip\", \"_-\"); // Returns: std::vector { \"quick\", \"snip\" }\n",
+ "extension": "cpp"
+ },
+ {
+ "title": "Transform",
+ "description": "Transform a string with a function",
+ "author": "majvax",
+ "tags": [
+ "string",
+ "transform",
+ "c++23"
+ ],
+ "contributors": [],
+ "code": "#include \n#include \n\ntemplate \nstd::string transform(const std::string& str, F&& transformer) {\n return str\n | std::ranges::views::transform(std::forward(transformer))\n | std::ranges::to();\n}\n\n\n\n// Usage:\nstd::string str = \"Hello, World!\";\nstd::string transformed = transform(str, [](char c){ return std::toupper(c); });\nstd::cout << transformed << std::endl; // HELLO, WORLD!\n",
+ "extension": "cpp"
+ }
+ ]
+ },
+ {
+ "name": "Vector Manipulation.md",
+ "snippets": [
+ {
+ "title": "Filter",
+ "description": "Filters a vector using a predicate function.",
+ "author": "majvax",
+ "tags": [
+ "array",
+ "filter",
+ "c++23"
+ ],
+ "contributors": [],
+ "code": "#include \n#include \n\ntemplate \nauto filter(const std::vector& vec, P&& predicate) {\n return vec\n | std::views::filter(std::forward(predicate))\n | std::ranges::to>();\n}\n\n\n\n// Usage:\nstd::vector vec = {1, 2, 3, 4, 5};\nstd::vector filtered = filter(vec, [](int i){ return i % 2 == 0; });\n// filtered contains 2 and 4\n",
+ "extension": "cpp"
+ },
+ {
+ "title": "Remove duplicates",
+ "description": "Removes duplicates from an vector of ints",
+ "author": "AnkushRoy-code",
+ "tags": [
+ "vector",
+ "remove",
+ "duplicate"
+ ],
+ "contributors": [],
+ "code": "#include \n#include \n\nbool removeDuplicates(std::vector &input) noexcept {\n if (input.empty()) return false;\n const auto size = input.size();\n std::sort(input.begin(), input.end());\n\n auto last = std::unique(input.begin(), input.end()); // remove duplicates\n input.erase(last, input.end()); // resize vector and delete the undefined elements\n\n return size != input.size();\n}\n\n\n\n// Usage:\nstd::vector vec = {4, 2, 2, 8, 5, 6, 9, 9, 9, 8, 8, 4};\nremoveDuplicates(vec); // returns {2, 4, 5, 6, 8, 9}\n",
+ "extension": "cpp"
+ },
+ {
+ "title": "Remove n Occurences",
+ "description": "Removes duplicates from an vector of ints",
+ "author": "AnkushRoy-code",
+ "tags": [
+ "vector",
+ "remove"
+ ],
+ "contributors": [],
+ "code": "#include \n#include \n#include \n\nbool removeOccurrences(std::vector& vec, const unsigned int n) noexcept {\n if (vec.empty() || n == 0) return false;\n\n const auto size = vec.size();\n std::unordered_map frequency; // count frequencies\n for (int num : vec) {\n frequency[num]++;\n }\n\n vec.erase( // remove elements with n number of occurrences\n std::remove_if(vec.begin(), vec.end(), [&frequency, n](const int x) {\n return frequency[x] == n;\n }),\n vec.end()\n );\n return size != vec.size();\n}\n\n\n\n// Usage:\nstd::vector vec = {4, 2, 4, 8, 5, 6, 8, 8, 4, 3 };\n\nint n = 3; // Remove elements that occur exactly 3 times\nremoveOccurrences(vec, n); // returns {2, 5, 6, 3}\n",
+ "extension": "cpp"
+ },
+ {
+ "title": "Transform",
+ "description": "Transforms a vector using a function.",
+ "author": "majvax",
+ "tags": [
+ "array",
+ "transform",
+ "c++23"
+ ],
+ "contributors": [],
+ "code": "#include \n#include \n\ntemplate \nauto transform(const std::vector& vec, F&& transformer) {\n using U = std::invoke_result_t;\n return vec\n | std::views::transform(std::forward(transformer))\n | std::ranges::to>();\n}\n\n\n\n// Usage:\nstd::vector vec = {1, 2, 3, 4, 5};\nstd::vector transformed = transform(vec, [](int i){ return i * 2; });\n// transformed contains 2, 4, 6, 8, 10\n",
+ "extension": "cpp"
+ }
+ ]
+ }
+]
\ No newline at end of file
diff --git a/backend/data/consolidated/csharp.json b/backend/data/consolidated/csharp.json
index c6590c60..5afc5f5f 100644
--- a/backend/data/consolidated/csharp.json
+++ b/backend/data/consolidated/csharp.json
@@ -1,99 +1,123 @@
[
- {
- "name": "Basics",
- "snippets": [
- {
- "title": "Hello, World!",
- "description": "Prints Hello, World! to the terminal.",
- "author": "chaitanya-jvnm",
- "tags": ["printing", "hello-world"],
- "contributors": [],
- "code": "public class Program {\n public static void Main(string[] args) {\n System.Console.WriteLine(\"Hello, World!\");\n }\n}\n",
- "extension": "csharp"
- }
- ]
- },
- {
- "name": "Guid Utilities",
- "snippets": [
- {
- "title": "Generate GUID",
- "description": "Generates a new GUID",
- "author": "chaitanya-jvnm",
- "tags": ["guid", "generate"],
- "contributors": [],
- "code": "public static string GenerateGuid() {\n return Guid.NewGuid().ToString();\n}\n\n// Usage:\nGenerateGuid(); // Returns: 1c4c38d8-64e4-431b-884a-c6eec2ab02cd (Uuid is random)\n",
- "extension": "csharp"
- },
- {
- "title": "Validate GUID",
- "description": "Checks if a string is a valid GUID.",
- "author": "chaitanya-jvnm",
- "tags": ["guid", "validate"],
- "contributors": [],
- "code": "public static bool IsGuid(string str) {\n return Guid.TryParse(str, out _);\n}\n\n// Usage:\nIsGuid(\"1c4c38d8-64e4-431b-884a-c6eec2ab02cd\"); // Returns: true\nIsGuid(\"quicksnip\"); // Returns: false\n",
- "extension": "csharp"
- }
- ]
- },
- {
- "name": "Jwt Utilities",
- "snippets": [
- {
- "title": "Decode JWT",
- "description": "Decodes a JWT.",
- "author": "chaitanya-jvnm",
- "tags": ["jwt", "decode"],
- "contributors": [],
- "code": "public static string DecodeJwt(string token) {\n return new JwtSecurityTokenHandler().ReadJwtToken(token).ToString();\n}\n\n// Usage:\nstring token = \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\";\nDecodeJwt(token); // Returns: \"{\\\"alg\\\":\\\"HS256\\\",\\\"typ\\\":\\\"JWT\\\"}.{\\\"sub\\\":\\\"1234567890\\\",\\\"name\\\":\\\"John Doe\\\",\\\"iat\\\":1516239022}\"\n",
- "extension": "csharp"
- },
- {
- "title": "Validate JWT",
- "description": "Validates a JWT.",
- "author": "chaitanya-jvnm",
- "tags": ["jwt", "validate"],
- "contributors": [],
- "code": "public static bool ValidateJwt(string token, string secret) {\n var tokenHandler = new JwtSecurityTokenHandler();\n var validationParameters = new TokenValidationParameters {\n ValidateIssuerSigningKey = true,\n IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret)),\n ValidateIssuer = false,\n ValidateAudience = false\n };\n try {\n tokenHandler.ValidateToken(token, validationParameters, out _);\n return true;\n }\n catch {\n return false\n }\n}\n\n// Usage:\nstring JWT = \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\";\nstring correctSecret = \"your-256-bit-secret\";\nstring wrongSecret = \"this-is-not-the-right-secret\";\n\nValidateJwt(JWT, correctSecret); // Returns: true\nValidateJwt(JWT, wrongSecret); // Returns: false\n",
- "extension": "csharp"
- }
- ]
- },
- {
- "name": "List Utilities",
- "snippets": [
- {
- "title": "Swap items at index",
- "description": "Swaps two items at determined indexes",
- "author": "omegaleo",
- "tags": ["list", "swapping"],
- "contributors": [],
- "code": "public static IList Swap(this IList list, int indexA, int indexB)\n{\n (list[indexA], list[indexB]) = (list[indexB], list[indexA]);\n return list;\n}\n\nvar list = new List() {\"Test\", \"Test2\"};\n\nlist.Swap(0, 1); // Swaps \"Test\" and \"Test2\" in place\n",
- "extension": "csharp"
- }
- ]
- },
- {
- "name": "String Utilities",
- "snippets": [
- {
- "title": "Capitalize first letter",
- "description": "Makes the first letter of a string uppercase.",
- "author": "chaitanya-jvnm",
- "tags": ["string", "capitalize"],
- "contributors": [],
- "code": "public static string Capitalize(this string str) {\n return str.Substring(0, 1).ToUpper() + str.Substring(1);\n}\n\n// Usage:\n\"quicksnip\".Capitalize(); // Returns: \"Quicksnip\"\n",
- "extension": "csharp"
- },
- {
- "title": "Truncate String",
- "description": "Cut off a string once it reaches a determined amount of characters and add '...' to the end of the string",
- "author": "omegaleo",
- "tags": ["string", "truncate"],
- "contributors": [],
- "code": "public static string Truncate(this string value, int maxChars)\n{\n return value.Length <= maxChars ? value : value.Substring(0, maxChars) + \"...\";\n}\n\n// Usage:\n\"Quicksnip\".Truncate(5); // Returns: \"Quick...\"\n",
- "extension": "csharp"
- }
- ]
- }
-]
+ {
+ "name": "Basics",
+ "snippets": [
+ {
+ "title": "Hello, World!",
+ "description": "Prints Hello, World! to the terminal.",
+ "author": "chaitanya-jvnm",
+ "tags": [
+ "printing",
+ "hello-world"
+ ],
+ "contributors": [],
+ "code": "public class Program {\n public static void Main(string[] args) {\n System.Console.WriteLine(\"Hello, World!\");\n }\n}\n",
+ "extension": "csharp"
+ }
+ ]
+ },
+ {
+ "name": "Guid Utilities",
+ "snippets": [
+ {
+ "title": "Generate GUID",
+ "description": "Generates a new GUID",
+ "author": "chaitanya-jvnm",
+ "tags": [
+ "guid",
+ "generate"
+ ],
+ "contributors": [],
+ "code": "public static string GenerateGuid() {\n return Guid.NewGuid().ToString();\n}\n\n// Usage:\nGenerateGuid(); // Returns: 1c4c38d8-64e4-431b-884a-c6eec2ab02cd (Uuid is random)\n",
+ "extension": "csharp"
+ },
+ {
+ "title": "Validate GUID",
+ "description": "Checks if a string is a valid GUID.",
+ "author": "chaitanya-jvnm",
+ "tags": [
+ "guid",
+ "validate"
+ ],
+ "contributors": [],
+ "code": "public static bool IsGuid(string str) {\n return Guid.TryParse(str, out _);\n}\n\n// Usage:\nIsGuid(\"1c4c38d8-64e4-431b-884a-c6eec2ab02cd\"); // Returns: true\nIsGuid(\"quicksnip\"); // Returns: false\n",
+ "extension": "csharp"
+ }
+ ]
+ },
+ {
+ "name": "Jwt Utilities",
+ "snippets": [
+ {
+ "title": "Decode JWT",
+ "description": "Decodes a JWT.",
+ "author": "chaitanya-jvnm",
+ "tags": [
+ "jwt",
+ "decode"
+ ],
+ "contributors": [],
+ "code": "public static string DecodeJwt(string token) {\n return new JwtSecurityTokenHandler().ReadJwtToken(token).ToString();\n}\n\n// Usage:\nstring token = \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\";\nDecodeJwt(token); // Returns: \"{\\\"alg\\\":\\\"HS256\\\",\\\"typ\\\":\\\"JWT\\\"}.{\\\"sub\\\":\\\"1234567890\\\",\\\"name\\\":\\\"John Doe\\\",\\\"iat\\\":1516239022}\"\n",
+ "extension": "csharp"
+ },
+ {
+ "title": "Validate JWT",
+ "description": "Validates a JWT.",
+ "author": "chaitanya-jvnm",
+ "tags": [
+ "jwt",
+ "validate"
+ ],
+ "contributors": [],
+ "code": "public static bool ValidateJwt(string token, string secret) {\n var tokenHandler = new JwtSecurityTokenHandler();\n var validationParameters = new TokenValidationParameters {\n ValidateIssuerSigningKey = true,\n IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret)),\n ValidateIssuer = false,\n ValidateAudience = false\n };\n try {\n tokenHandler.ValidateToken(token, validationParameters, out _);\n return true;\n }\n catch {\n return false\n }\n}\n\n// Usage:\nstring JWT = \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\";\nstring correctSecret = \"your-256-bit-secret\";\nstring wrongSecret = \"this-is-not-the-right-secret\";\n\nValidateJwt(JWT, correctSecret); // Returns: true\nValidateJwt(JWT, wrongSecret); // Returns: false\n",
+ "extension": "csharp"
+ }
+ ]
+ },
+ {
+ "name": "List Utilities",
+ "snippets": [
+ {
+ "title": "Swap items at index",
+ "description": "Swaps two items at determined indexes",
+ "author": "omegaleo",
+ "tags": [
+ "list",
+ "swapping"
+ ],
+ "contributors": [],
+ "code": "public static IList Swap(this IList list, int indexA, int indexB)\n{\n (list[indexA], list[indexB]) = (list[indexB], list[indexA]);\n return list;\n}\n\nvar list = new List() {\"Test\", \"Test2\"};\n\nlist.Swap(0, 1); // Swaps \"Test\" and \"Test2\" in place\n",
+ "extension": "csharp"
+ }
+ ]
+ },
+ {
+ "name": "String Utilities",
+ "snippets": [
+ {
+ "title": "Capitalize first letter",
+ "description": "Makes the first letter of a string uppercase.",
+ "author": "chaitanya-jvnm",
+ "tags": [
+ "string",
+ "capitalize"
+ ],
+ "contributors": [],
+ "code": "public static string Capitalize(this string str) {\n return str.Substring(0, 1).ToUpper() + str.Substring(1);\n}\n\n// Usage:\n\"quicksnip\".Capitalize(); // Returns: \"Quicksnip\"\n",
+ "extension": "csharp"
+ },
+ {
+ "title": "Truncate String",
+ "description": "Cut off a string once it reaches a determined amount of characters and add '...' to the end of the string",
+ "author": "omegaleo",
+ "tags": [
+ "string",
+ "truncate"
+ ],
+ "contributors": [],
+ "code": "public static string Truncate(this string value, int maxChars)\n{\n return value.Length <= maxChars ? value : value.Substring(0, maxChars) + \"...\";\n}\n\n// Usage:\n\"Quicksnip\".Truncate(5); // Returns: \"Quick...\"\n",
+ "extension": "csharp"
+ }
+ ]
+ }
+]
\ No newline at end of file
diff --git a/backend/data/consolidated/css.json b/backend/data/consolidated/css.json
index af235d4a..c1b8835e 100644
--- a/backend/data/consolidated/css.json
+++ b/backend/data/consolidated/css.json
@@ -1,198 +1,274 @@
[
- {
- "name": "Animations",
- "snippets": [
- {
- "title": "Blink Animation",
- "description": "Adds an infinite blinking animation to an element",
- "author": "AlsoKnownAs-Ax",
- "tags": ["animation", "blink", "infinite"],
- "contributors": [],
- "code": ".blink {\n animation: blink 1s linear infinite;\n}\n\n@keyframes blink{\n 0%{\n opacity: 0;\n }\n 50%{\n opacity: 1;\n }\n 100%{\n opacity: 0;\n }\n}\n",
- "extension": "css"
- },
- {
- "title": "Pulse Animation",
- "description": "Adds a smooth pulsing animation with opacity and scale effects",
- "author": "AlsoKnownAs-Ax",
- "tags": ["animation", "pulse", "pulse-scale"],
- "contributors": ["alanb4rt"],
- "code": ".pulse {\n animation: pulse 1s ease-in-out infinite alternate;\n}\n\n@keyframes pulse {\n from {\n opacity: 0.5;\n transform: scale(1);\n }\n to {\n opacity: 1;\n transform: scale(1.05);\n }\n}\n",
- "extension": "css"
- },
- {
- "title": "Shake Animation",
- "description": "Adds a shake animation ( commonly used to mark invalid fields )",
- "author": "AlsoKnownAs-Ax",
- "tags": ["shake", "shake-horizontal"],
- "contributors": [],
- "code": ".shake {\n animation: shake .5s ease-in-out;\n}\n\n@keyframes shake {\n 0%, 100% {\n transform: translateX(0);\n }\n 25% {\n transform: translateX(-10px);\n }\n 50% {\n transform: translateX(10px);\n }\n 75% {\n transform: translateX(-10px);\n }\n}\n",
- "extension": "css"
- },
- {
- "title": "Slide-in Animation",
- "description": "Adds a slide-in from the right side of the screen",
- "author": "AlsoKnownAs-Ax",
- "tags": ["animation", "slide-in", "slide-right"],
- "contributors": [],
- "code": ".slide-in {\n animation: slide-in 1s ease-in-out;\n}\n\n@keyframes slide-in {\n from {\n scale: 300% 1;\n translate: 150vw 0;\n }\n\n to {\n scale: 100% 1;\n translate: 0 0;\n }\n}\n",
- "extension": "css"
- },
- {
- "title": "Typewriter Animation",
- "description": "Adds a typewriter animation + blinking cursor",
- "author": "AlsoKnownAs-Ax",
- "tags": ["blinking", "typewriter"],
- "contributors": [],
- "code": " \n
\n
Typerwriter Animation
\n
\n
\n```\n\n```css\n .typewriter{\n display: flex;\n justify-content: center;\n }\n\n .typewriter p {\n overflow: hidden;\n font-size: 1.5rem;\n font-family: monospace;\n border-right: 1px solid;\n margin-inline: auto;\n white-space: nowrap;\n /* The cursor will inherit the text's color by default */\n /* border-color: red */ \n /* Steps: number of chars (better to set directly in js)*/\n animation: typing 3s steps(21) forwards,\n blink 1s step-end infinite;\n }\n\n @keyframes typing{\n from{\n width: 0%\n }\n to{\n width: 100%\n }\n }\n\n @keyframes blink{\n 50%{\n border-color: transparent;\n }\n }\n",
- "extension": "html"
- }
- ]
- },
- {
- "name": "Buttons",
- "snippets": [
- {
- "title": "3D Button Effect",
- "description": "Adds a 3D effect to a button when clicked.",
- "author": "technoph1le",
- "tags": ["button", "3D", "effect"],
- "contributors": [],
- "code": ".button {\n background-color: #28a745;\n color: white;\n padding: 10px 20px;\n border: none;\n border-radius: 5px;\n box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);\n transition: transform 0.1s;\n}\n\n.button:active {\n transform: translateY(2px);\n box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);\n}\n",
- "extension": "css"
- },
- {
- "title": "Button Hover Effect",
- "description": "Creates a hover effect with a color transition.",
- "author": "technoph1le",
- "tags": ["button", "hover", "transition"],
- "contributors": [],
- "code": ".button {\n background-color: #007bff;\n color: white;\n padding: 10px 20px;\n border: none;\n border-radius: 5px;\n cursor: pointer;\n transition: background-color 0.3s ease;\n}\n\n.button:hover {\n background-color: #0056b3;\n}\n",
- "extension": "css"
- },
- {
- "title": "MacOS Button",
- "description": "A macOS-like button style, with hover and shading effects.",
- "author": "e3nviction",
- "tags": ["button", "macos", "hover", "transition"],
- "contributors": [],
- "code": ".button {\n font: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica,;\n background: #0a85ff;\n color: #fff;\n padding: 8px 12px;\n border: none;\n margin: 4px;\n border-radius: 10px;\n cursor: pointer;\n box-shadow: inset 0 1px 1px #fff2, 0px 2px 3px -2px rgba(0, 0, 0, 0.3) !important; /*This is really performance heavy*/\n font-size: 14px;\n display: flex;\n align-items: center;\n justify-content: center;\n text-decoration: none;\n transition: all 150ms cubic-bezier(0.175, 0.885, 0.32, 1.275);\n}\n.button:hover {\n background: #0974ee;\n color: #fff\n}\n",
- "extension": "css"
- }
- ]
- },
- {
- "name": "Effects",
- "snippets": [
- {
- "title": "Blur Background",
- "description": "Applies a blur effect to the background of an element.",
- "author": "technoph1le",
- "tags": ["blur", "background", "effects"],
- "contributors": [],
- "code": ".blur-background {\n backdrop-filter: blur(10px);\n background: rgba(255, 255, 255, 0.5);\n}\n",
- "extension": "css"
- },
- {
- "title": "Hover Glow Effect",
- "description": "Adds a glowing effect on hover.",
- "author": "technoph1le",
- "tags": ["hover", "glow", "effects"],
- "contributors": [],
- "code": ".glow {\n background-color: #f39c12;\n padding: 10px 20px;\n border-radius: 5px;\n transition: box-shadow 0.3s ease;\n}\n\n.glow:hover {\n box-shadow: 0 0 15px rgba(243, 156, 18, 0.8);\n}\n",
- "extension": "css"
- },
- {
- "title": "Hover to Reveal Color",
- "description": "A card with an image that transitions from grayscale to full color on hover.",
- "author": "Haider-Mukhtar",
- "tags": ["hover", "image", "effects"],
- "contributors": [],
- "code": ".card {\n height: 300px;\n width: 200px;\n border-radius: 5px;\n overflow: hidden;\n}\n\n.card img{\n height: 100%;\n width: 100%;\n object-fit: cover;\n filter: grayscale(100%);\n transition: all 0.3s;\n transition-duration: 200ms;\n cursor: pointer;\n}\n\n.card:hover img {\n filter: grayscale(0%);\n scale: 1.05;\n}\n",
- "extension": "css"
- },
- {
- "title": "RGB Border Color Animation",
- "description": "changes border of an Element to rgb onhover (Can be changed)'",
- "author": "Brianali-codes",
- "tags": ["animation", "effects", "borders"],
- "contributors": [],
- "code": ".yourElement {\n /* Your Elements styles go here*/\n border-style: solid;\n border-radius: 10px;\n color: rgb(0, 0, 0);\n\n}\n.yourElement:hover {\n\n animation: change-color;\n animation-duration: 0.5s; /* you can alter the duration of the animation here. */\n animation-iteration-count: infinite; /* Choose to play animation infinitely or once on hover. */\n}\n\n@keyframes change-color {\n 0% {\n border-color: red;\n }\n\n 50% {\n border-color: green;\n }\n\n 100% {\n border-color: blue;\n }\n}\n\n\n",
- "extension": "css"
- }
- ]
- },
- {
- "name": "Layouts",
- "snippets": [
- {
- "title": "CSS Reset",
- "description": "Resets some default browser styles, ensuring consistency across browsers.",
- "author": "AmeerMoustafa",
- "tags": ["reset", "browser", "layout"],
- "contributors": [],
- "code": "* {\n margin: 0;\n padding: 0;\n box-sizing: border-box\n}\n",
- "extension": "css"
- },
- {
- "title": "Equal-Width Columns",
- "description": "Creates columns with equal widths using flexbox.",
- "author": "technoph1le",
- "tags": ["flexbox", "columns", "layout"],
- "contributors": [],
- "code": ".columns {\n display: flex;\n justify-content: space-between;\n}\n\n.column {\n flex: 1;\n margin: 0 10px;\n}\n",
- "extension": "css"
- },
- {
- "title": "Grid layout",
- "description": "Equal sized items in a responsive grid",
- "author": "xshubhamg",
- "tags": ["layout", "grid"],
- "contributors": ["tryoxiss"],
- "code": ".grid-container {\n display: grid;\n grid-template-columns: repeat(auto-fit, minmax(min(250px, 100%), 1fr));\n/* Explanation:\n- `auto-fit`: Automatically fits as many columns as possible within the container.\n- `minmax(min(250px, 100%), 1fr)`: Defines a minimum column size of 250px and a maximum size of 1fr (fraction of available space). However, that minimum column size is allowed to shrink to fit all avalible space if the space is otherwise less than the minimum.\n - NOTE: the `min(x, 100%)` trick does not do much for very small sizes like 250px, but it will help massively if you increase the min column size yourself.\n*/\n}\n",
- "extension": "css"
- },
- {
- "title": "Responsive Design",
- "description": "The different responsive breakpoints.",
- "author": "kruimol",
- "tags": ["responsive", "media queries"],
- "contributors": [],
- "code": "/* Phone */\n.element {\n margin: 0 10%\n}\n\n/* Tablet */\n@media (min-width: 640px) {\n .element {\n margin: 0 20%\n }\n}\n\n/* Desktop base */\n@media (min-width: 768px) {\n .element {\n margin: 0 30%\n }\n}\n\n/* Desktop large */\n@media (min-width: 1024px) {\n .element {\n margin: 0 40%\n }\n}\n\n/* Desktop extra large */\n@media (min-width: 1280px) {\n .element {\n margin: 0 60%\n }\n}\n\n/* Desktop bige */\n@media (min-width: 1536px) {\n .element {\n margin: 0 80%\n }\n}\n",
- "extension": "css"
- },
- {
- "title": "Sticky Footer",
- "description": "Ensures the footer always stays at the bottom of the page.",
- "author": "technoph1le",
- "tags": ["layout", "footer", "sticky"],
- "contributors": [],
- "code": "body {\n display: flex;\n flex-direction: column;\n min-height: 100vh;\n}\n\nfooter {\n margin-top: auto;\n}\n",
- "extension": "css"
- }
- ]
- },
- {
- "name": "Typography",
- "snippets": [
- {
- "title": "Letter Spacing",
- "description": "Adds space between letters for better readability.",
- "author": "technoph1le",
- "tags": ["typography", "spacing"],
- "contributors": [],
- "code": "p {\n letter-spacing: 0.05em;\n}\n",
- "extension": "css"
- },
- {
- "title": "Responsive Font Sizing",
- "description": "Adjusts font size based on viewport width.",
- "author": "technoph1le",
- "tags": ["font", "responsive", "typography"],
- "contributors": [],
- "code": "h1 {\n font-size: calc(1.5rem + 2vw);\n}\n",
- "extension": "css"
- }
- ]
- }
-]
+ {
+ "name": "Animations",
+ "snippets": [
+ {
+ "title": "Blink Animation",
+ "description": "Adds an infinite blinking animation to an element",
+ "author": "AlsoKnownAs-Ax",
+ "tags": [
+ "animation",
+ "blink",
+ "infinite"
+ ],
+ "contributors": [],
+ "code": ".blink {\n animation: blink 1s linear infinite;\n}\n\n@keyframes blink{\n 0%{\n opacity: 0;\n }\n 50%{\n opacity: 1;\n }\n 100%{\n opacity: 0;\n }\n}\n",
+ "extension": "css"
+ },
+ {
+ "title": "Pulse Animation",
+ "description": "Adds a smooth pulsing animation with opacity and scale effects",
+ "author": "AlsoKnownAs-Ax",
+ "tags": [
+ "animation",
+ "pulse",
+ "pulse-scale"
+ ],
+ "contributors": [
+ "alanb4rt"
+ ],
+ "code": ".pulse {\n animation: pulse 1s ease-in-out infinite alternate;\n}\n\n@keyframes pulse {\n from {\n opacity: 0.5;\n transform: scale(1);\n }\n to {\n opacity: 1;\n transform: scale(1.05);\n }\n}\n",
+ "extension": "css"
+ },
+ {
+ "title": "Shake Animation",
+ "description": "Adds a shake animation ( commonly used to mark invalid fields )",
+ "author": "AlsoKnownAs-Ax",
+ "tags": [
+ "shake",
+ "shake-horizontal"
+ ],
+ "contributors": [],
+ "code": ".shake {\n animation: shake .5s ease-in-out;\n}\n\n@keyframes shake {\n 0%, 100% {\n transform: translateX(0);\n }\n 25% {\n transform: translateX(-10px);\n }\n 50% {\n transform: translateX(10px);\n }\n 75% {\n transform: translateX(-10px);\n }\n}\n",
+ "extension": "css"
+ },
+ {
+ "title": "Slide-in Animation",
+ "description": "Adds a slide-in from the right side of the screen",
+ "author": "AlsoKnownAs-Ax",
+ "tags": [
+ "animation",
+ "slide-in",
+ "slide-right"
+ ],
+ "contributors": [],
+ "code": ".slide-in {\n animation: slide-in 1s ease-in-out;\n}\n\n@keyframes slide-in {\n from {\n scale: 300% 1;\n translate: 150vw 0;\n }\n\n to {\n scale: 100% 1;\n translate: 0 0;\n }\n}\n",
+ "extension": "css"
+ },
+ {
+ "title": "Typewriter Animation",
+ "description": "Adds a typewriter animation + blinking cursor",
+ "author": "AlsoKnownAs-Ax",
+ "tags": [
+ "blinking",
+ "typewriter"
+ ],
+ "contributors": [],
+ "code": " \n
\n
Typerwriter Animation
\n
\n
\n```\n\n```css\n .typewriter{\n display: flex;\n justify-content: center;\n }\n\n .typewriter p {\n overflow: hidden;\n font-size: 1.5rem;\n font-family: monospace;\n border-right: 1px solid;\n margin-inline: auto;\n white-space: nowrap;\n /* The cursor will inherit the text's color by default */\n /* border-color: red */ \n /* Steps: number of chars (better to set directly in js)*/\n animation: typing 3s steps(21) forwards,\n blink 1s step-end infinite;\n }\n\n @keyframes typing{\n from{\n width: 0%\n }\n to{\n width: 100%\n }\n }\n\n @keyframes blink{\n 50%{\n border-color: transparent;\n }\n }\n",
+ "extension": "html"
+ }
+ ]
+ },
+ {
+ "name": "Buttons",
+ "snippets": [
+ {
+ "title": "3D Button Effect",
+ "description": "Adds a 3D effect to a button when clicked.",
+ "author": "technoph1le",
+ "tags": [
+ "button",
+ "3D",
+ "effect"
+ ],
+ "contributors": [],
+ "code": ".button {\n background-color: #28a745;\n color: white;\n padding: 10px 20px;\n border: none;\n border-radius: 5px;\n box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);\n transition: transform 0.1s;\n}\n\n.button:active {\n transform: translateY(2px);\n box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);\n}\n",
+ "extension": "css"
+ },
+ {
+ "title": "Button Hover Effect",
+ "description": "Creates a hover effect with a color transition.",
+ "author": "technoph1le",
+ "tags": [
+ "button",
+ "hover",
+ "transition"
+ ],
+ "contributors": [],
+ "code": ".button {\n background-color: #007bff;\n color: white;\n padding: 10px 20px;\n border: none;\n border-radius: 5px;\n cursor: pointer;\n transition: background-color 0.3s ease;\n}\n\n.button:hover {\n background-color: #0056b3;\n}\n",
+ "extension": "css"
+ },
+ {
+ "title": "MacOS Button",
+ "description": "A macOS-like button style, with hover and shading effects.",
+ "author": "e3nviction",
+ "tags": [
+ "button",
+ "macos",
+ "hover",
+ "transition"
+ ],
+ "contributors": [],
+ "code": ".button {\n font: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica,;\n background: #0a85ff;\n color: #fff;\n padding: 8px 12px;\n border: none;\n margin: 4px;\n border-radius: 10px;\n cursor: pointer;\n box-shadow: inset 0 1px 1px #fff2, 0px 2px 3px -2px rgba(0, 0, 0, 0.3) !important; /*This is really performance heavy*/\n font-size: 14px;\n display: flex;\n align-items: center;\n justify-content: center;\n text-decoration: none;\n transition: all 150ms cubic-bezier(0.175, 0.885, 0.32, 1.275);\n}\n.button:hover {\n background: #0974ee;\n color: #fff\n}\n",
+ "extension": "css"
+ }
+ ]
+ },
+ {
+ "name": "Effects",
+ "snippets": [
+ {
+ "title": "Blur Background",
+ "description": "Applies a blur effect to the background of an element.",
+ "author": "technoph1le",
+ "tags": [
+ "blur",
+ "background",
+ "effects"
+ ],
+ "contributors": [],
+ "code": ".blur-background {\n backdrop-filter: blur(10px);\n background: rgba(255, 255, 255, 0.5);\n}\n",
+ "extension": "css"
+ },
+ {
+ "title": "Hover Glow Effect",
+ "description": "Adds a glowing effect on hover.",
+ "author": "technoph1le",
+ "tags": [
+ "hover",
+ "glow",
+ "effects"
+ ],
+ "contributors": [],
+ "code": ".glow {\n background-color: #f39c12;\n padding: 10px 20px;\n border-radius: 5px;\n transition: box-shadow 0.3s ease;\n}\n\n.glow:hover {\n box-shadow: 0 0 15px rgba(243, 156, 18, 0.8);\n}\n",
+ "extension": "css"
+ },
+ {
+ "title": "Hover to Reveal Color",
+ "description": "A card with an image that transitions from grayscale to full color on hover.",
+ "author": "Haider-Mukhtar",
+ "tags": [
+ "hover",
+ "image",
+ "effects"
+ ],
+ "contributors": [],
+ "code": ".card {\n height: 300px;\n width: 200px;\n border-radius: 5px;\n overflow: hidden;\n}\n\n.card img{\n height: 100%;\n width: 100%;\n object-fit: cover;\n filter: grayscale(100%);\n transition: all 0.3s;\n transition-duration: 200ms;\n cursor: pointer;\n}\n\n.card:hover img {\n filter: grayscale(0%);\n scale: 1.05;\n}\n",
+ "extension": "css"
+ },
+ {
+ "title": "RGB Border Color Animation",
+ "description": "changes border of an Element to rgb onhover (Can be changed)'",
+ "author": "Brianali-codes",
+ "tags": [
+ "animation",
+ "effects",
+ "borders"
+ ],
+ "contributors": [],
+ "code": ".yourElement {\n /* Your Elements styles go here*/\n border-style: solid;\n border-radius: 10px;\n color: rgb(0, 0, 0);\n\n}\n.yourElement:hover {\n\n animation: change-color;\n animation-duration: 0.5s; /* you can alter the duration of the animation here. */\n animation-iteration-count: infinite; /* Choose to play animation infinitely or once on hover. */\n}\n\n@keyframes change-color {\n 0% {\n border-color: red;\n }\n\n 50% {\n border-color: green;\n }\n\n 100% {\n border-color: blue;\n }\n}\n\n\n",
+ "extension": "css"
+ }
+ ]
+ },
+ {
+ "name": "Layouts",
+ "snippets": [
+ {
+ "title": "CSS Reset",
+ "description": "Resets some default browser styles, ensuring consistency across browsers.",
+ "author": "AmeerMoustafa",
+ "tags": [
+ "reset",
+ "browser",
+ "layout"
+ ],
+ "contributors": [],
+ "code": "* {\n margin: 0;\n padding: 0;\n box-sizing: border-box\n}\n",
+ "extension": "css"
+ },
+ {
+ "title": "Equal-Width Columns",
+ "description": "Creates columns with equal widths using flexbox.",
+ "author": "technoph1le",
+ "tags": [
+ "flexbox",
+ "columns",
+ "layout"
+ ],
+ "contributors": [],
+ "code": ".columns {\n display: flex;\n justify-content: space-between;\n}\n\n.column {\n flex: 1;\n margin: 0 10px;\n}\n",
+ "extension": "css"
+ },
+ {
+ "title": "Grid layout",
+ "description": "Equal sized items in a responsive grid",
+ "author": "xshubhamg",
+ "tags": [
+ "layout",
+ "grid"
+ ],
+ "contributors": [
+ "tryoxiss"
+ ],
+ "code": ".grid-container {\n display: grid;\n grid-template-columns: repeat(auto-fit, minmax(min(250px, 100%), 1fr));\n/* Explanation:\n- `auto-fit`: Automatically fits as many columns as possible within the container.\n- `minmax(min(250px, 100%), 1fr)`: Defines a minimum column size of 250px and a maximum size of 1fr (fraction of available space). However, that minimum column size is allowed to shrink to fit all avalible space if the space is otherwise less than the minimum.\n - NOTE: the `min(x, 100%)` trick does not do much for very small sizes like 250px, but it will help massively if you increase the min column size yourself.\n*/\n}\n",
+ "extension": "css"
+ },
+ {
+ "title": "Responsive Design",
+ "description": "The different responsive breakpoints.",
+ "author": "kruimol",
+ "tags": [
+ "responsive",
+ "media queries"
+ ],
+ "contributors": [],
+ "code": "/* Phone */\n.element {\n margin: 0 10%\n}\n\n/* Tablet */\n@media (min-width: 640px) {\n .element {\n margin: 0 20%\n }\n}\n\n/* Desktop base */\n@media (min-width: 768px) {\n .element {\n margin: 0 30%\n }\n}\n\n/* Desktop large */\n@media (min-width: 1024px) {\n .element {\n margin: 0 40%\n }\n}\n\n/* Desktop extra large */\n@media (min-width: 1280px) {\n .element {\n margin: 0 60%\n }\n}\n\n/* Desktop bige */\n@media (min-width: 1536px) {\n .element {\n margin: 0 80%\n }\n}\n",
+ "extension": "css"
+ },
+ {
+ "title": "Sticky Footer",
+ "description": "Ensures the footer always stays at the bottom of the page.",
+ "author": "technoph1le",
+ "tags": [
+ "layout",
+ "footer",
+ "sticky"
+ ],
+ "contributors": [],
+ "code": "body {\n display: flex;\n flex-direction: column;\n min-height: 100vh;\n}\n\nfooter {\n margin-top: auto;\n}\n",
+ "extension": "css"
+ }
+ ]
+ },
+ {
+ "name": "Typography",
+ "snippets": [
+ {
+ "title": "Letter Spacing",
+ "description": "Adds space between letters for better readability.",
+ "author": "technoph1le",
+ "tags": [
+ "typography",
+ "spacing"
+ ],
+ "contributors": [],
+ "code": "p {\n letter-spacing: 0.05em;\n}\n",
+ "extension": "css"
+ },
+ {
+ "title": "Responsive Font Sizing",
+ "description": "Adjusts font size based on viewport width.",
+ "author": "technoph1le",
+ "tags": [
+ "font",
+ "responsive",
+ "typography"
+ ],
+ "contributors": [],
+ "code": "h1 {\n font-size: calc(1.5rem + 2vw);\n}\n",
+ "extension": "css"
+ }
+ ]
+ }
+]
\ No newline at end of file
diff --git a/backend/data/consolidated/haskell.json b/backend/data/consolidated/haskell.json
index 77b1d004..ff27eac2 100644
--- a/backend/data/consolidated/haskell.json
+++ b/backend/data/consolidated/haskell.json
@@ -1,171 +1,240 @@
[
- {
- "name": "Array Manipulation",
- "snippets": [
- {
- "title": "Binary Search",
- "description": "Searches for an element in a sorted array using binary search.",
- "author": "ACR1209",
- "tags": ["array", "binary-search", "search"],
- "contributors": [],
- "code": "binarySearch :: Ord a => a -> [a] -> Maybe Int\nbinarySearch _ [] = Nothing\nbinarySearch target xs = go 0 (length xs - 1)\n where\n go low high\n | low > high = Nothing\n | midElem < target = go (mid + 1) high\n | midElem > target = go low (mid - 1)\n | otherwise = Just mid\n where\n mid = (low + high) `div` 2\n midElem = xs !! mid\n\n-- Usage:\nmain :: IO ()\nmain = do\n let array = [1, 2, 3, 4, 5]\n print $ binarySearch 3 array -- Output: Just 2\n print $ binarySearch 6 array -- Output: Nothing\n",
- "extension": "hs"
- },
- {
- "title": "Chunk Array",
- "description": "Splits an array into chunks of a specified size.",
- "author": "ACR1209",
- "tags": ["array", "chunk", "utility"],
- "contributors": [],
- "code": "chunkArray :: Int -> [a] -> [[a]]\nchunkArray _ [] = []\nchunkArray n xs = take n xs : chunkArray n (drop n xs)\n\n-- Usage:\nmain :: IO ()\nmain = do\n let array = [1, 2, 3, 4, 5, 6]\n print $ chunkArray 2 array -- Output: [[1, 2], [3, 4], [5, 6]]\n",
- "extension": "hs"
- },
- {
- "title": "Matrix Transpose",
- "description": "Transposes a 2D matrix.",
- "author": "ACR1209",
- "tags": ["array", "matrix", "transpose"],
- "contributors": [],
- "code": "transposeMatrix :: [[a]] -> [[a]]\ntransposeMatrix [] = []\ntransposeMatrix ([]:_) = []\ntransposeMatrix xs = map head xs : transposeMatrix (map tail xs)\n\n-- Usage:\nmain :: IO ()\nmain = do\n let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n print $ transposeMatrix matrix -- Output: [[1,4,7],[2,5,8],[3,6,9]]\n",
- "extension": "hs"
- }
- ]
- },
- {
- "name": "Basics",
- "snippets": [
- {
- "title": "Hello, World!",
- "description": "Prints Hello, World! to the terminal.",
- "author": "ACR1209",
- "tags": ["printing", "hello-world", "utility"],
- "contributors": [],
- "code": "putStrLn \"Hello, World!\"\n",
- "extension": "haskell"
- }
- ]
- },
- {
- "name": "File Handling",
- "snippets": [
- {
- "title": "Find Files in Directory by Type",
- "description": "Finds all files in a directory with a specific extension.",
- "author": "ACR1209",
- "tags": ["file", "search", "extension", "filesystem"],
- "contributors": [],
- "code": "import System.Directory (listDirectory)\nimport System.FilePath (takeExtension)\n\nfindFilesByExtension :: FilePath -> String -> IO [FilePath]\nfindFilesByExtension dir ext = do\n files <- listDirectory dir\n return $ filter (\\f -> takeExtension f == ext) files\n\n-- Usage:\nmain :: IO ()\nmain = do\n let directory = \".\"\n let ext = \".txt\"\n files <- findFilesByExtension directory ext\n mapM_ putStrLn files -- Output: list of txt files on the current directory\n",
- "extension": "hs"
- },
- {
- "title": "Read File in Chunks",
- "description": "Reads a file in chunks grouped by lines.",
- "author": "ACR1209",
- "tags": ["file", "read", "chunks", "utility"],
- "contributors": [],
- "code": "import System.IO (openFile, IOMode(ReadMode), hGetContents)\nimport Data.List (unfoldr)\n\nreadFileInChunks :: FilePath -> Int -> IO [[String]]\nreadFileInChunks filePath chunkSize = do\n handle <- openFile filePath ReadMode\n contents <- hGetContents handle\n let linesList = lines contents\n return $ go linesList\n where\n go [] = []\n go xs = take chunkSize xs : go (drop chunkSize xs)\n\n-- Usage:\nmain :: IO ()\nmain = do\n let file = \"example.txt\"\n let chunkSize = 3 -- Number of lines per chunk\n chunks <- readFileInChunks file chunkSize\n mapM_ (putStrLn . unlines) chunks\n\n",
- "extension": "hs"
- }
- ]
- },
- {
- "name": "Monads",
- "snippets": [
- {
- "title": "Either Monad for Error Handling",
- "description": "Using the Either monad to handle errors in a computation.",
- "author": "ACR1209",
- "tags": ["monads", "either", "error handling"],
- "contributors": [],
- "code": "safeDiv :: Int -> Int -> Either String Int\nsafeDiv _ 0 = Left \"Division by zero error\"\nsafeDiv x y = Right (x `div` y)\n\n-- Usage:\nmain :: IO ()\nmain = do\n let result = do\n a <- safeDiv 10 2\n b <- safeDiv a 0 -- This will trigger an error\n return b\n print result -- Output: Left \"Division by zero error\"\n",
- "extension": "hs"
- },
- {
- "title": "Maybe Monad",
- "description": "Using the Maybe monad to handle computations that might fail.",
- "author": "ACR1209",
- "tags": ["monads", "maybe"],
- "contributors": [],
- "code": "safeDiv :: Int -> Int -> Maybe Int\nsafeDiv _ 0 = Nothing\nsafeDiv x y = Just (x `div` y)\n\n-- Usage:\nmain :: IO ()\nmain = do\n let result = do\n a <- safeDiv 10 2\n b <- safeDiv a 2\n return b\n print result -- Output: Just 2\n",
- "extension": "hs"
- },
- {
- "title": "State Monad",
- "description": "Managing mutable state using the State monad.",
- "author": "ACR1209",
- "tags": ["monads", "state", "state-management"],
- "contributors": [],
- "code": "import Control.Monad.State\n\nincrement :: State Int Int\nincrement = do\n count <- get\n put (count + 1)\n return count\n\n-- Usage:\nmain :: IO ()\nmain = do\n let (res1, intermediateState) = runState increment 0\n print res1 -- Output: 0\n let (result, finalState) = runState increment intermediateState\n print result -- Output: 1\n print finalState -- Output: 2\n\n",
- "extension": "hs"
- },
- {
- "title": "Writer Monad",
- "description": "Using the Writer monad to accumulate logs or other outputs alongside a computation.",
- "author": "ACR1209",
- "tags": ["monads", "writer", "logs"],
- "contributors": [],
- "code": "import Control.Monad.Writer\n\naddAndLog :: Int -> Int -> Writer [String] Int\naddAndLog x y = do\n tell [\"Adding \" ++ show x ++ \" and \" ++ show y]\n return (x + y)\n\n-- Usage:\nmain :: IO ()\nmain = do\n let (result, logs) = runWriter $ do\n res1 <- addAndLog 3 5\n addAndLog res1 1\n print result -- Output: 9\n print logs -- Output: [\"Adding 3 and 5\", \"Adding 8 and 1\"]\n",
- "extension": "hs"
- }
- ]
- },
- {
- "name": "String Manipulation",
- "snippets": [
- {
- "title": "CamelCase to snake_case",
- "description": "Converts a Camel Case string to Snake case.",
- "author": "ACR1209",
- "tags": ["string", "convert", "camel-case", "snake-case", "utility"],
- "contributors": [],
- "code": "import Data.Char (isUpper, toLower)\n\ncamelToSnake :: String -> String\ncamelToSnake [] = []\ncamelToSnake (x:xs)\n | isUpper x = '_' : toLower x : camelToSnake xs\n | otherwise = x : camelToSnake xs\n\n-- Usage:\nmain :: IO ()\nmain = do\n let camelCase = \"camelCaseToSnakeCase\"\n print $ camelToSnake camelCase -- Output: \"camel_case_to_snake_case\"\n",
- "extension": "hs"
- },
- {
- "title": "Capitalize Words",
- "description": "Capitalizes the first letter of each word in a string.",
- "author": "ACR1209",
- "tags": ["string", "capitalize", "words"],
- "contributors": [],
- "code": "import Data.Char (toUpper)\n\ncapitalizeWords :: String -> String\ncapitalizeWords = unwords . map capitalize . words\n where\n capitalize [] = []\n capitalize (x:xs) = toUpper x : xs\n\n-- Usage:\nmain :: IO ()\nmain = do\n let sentence = \"haskell is awesome\"\n print $ capitalizeWords sentence -- Output: \"Haskell Is Awesome\"\n",
- "extension": "hs"
- },
- {
- "title": "Count Word Occurrences in String",
- "description": "Counts the occurrences of each word in a given string.",
- "author": "ACR1209",
- "tags": ["string", "occurrences", "word-count"],
- "contributors": [],
- "code": "import Data.List (group, sort)\n\ncountWordOccurrences :: String -> [(String, Int)]\ncountWordOccurrences = map (\\(w:ws) -> (w, length (w:ws))) . group . sort . words\n\n-- Usage:\nmain :: IO ()\nmain = do\n let text = \"haskell is awesome and haskell is fun\"\n print $ countWordOccurrences text -- Output: [(\"and\",1),(\"awesome\",1),(\"fun\",1),(\"haskell\",2),(\"is\",2)]\n",
- "extension": "hs"
- },
- {
- "title": "Remove Punctuation",
- "description": "Removes all punctuation from a given string.",
- "author": "ACR1209",
- "tags": ["string", "punctuation", "remove"],
- "contributors": [],
- "code": "import Data.Char (isPunctuation)\n\nremovePunctuation :: String -> String\nremovePunctuation = filter (not . isPunctuation)\n\n-- Usage:\nmain :: IO ()\nmain = do\n let text = \"Hello, Haskell! How's it going?\"\n print $ removePunctuation text -- Output: \"Hello Haskell Hows it going\"\n",
- "extension": "hs"
- },
- {
- "title": "Snake_Case to CamelCase",
- "description": "Converts a Snake Case string to Camel Case.",
- "author": "ACR1209",
- "tags": ["string", "convert", "snake-case", "camel-case", "utilty"],
- "contributors": [],
- "code": "import Data.Char (toUpper)\n\nsnakeToCamel :: String -> String\nsnakeToCamel [] = []\nsnakeToCamel ('_':x:xs) = toUpper x : snakeToCamel xs\nsnakeToCamel (x:xs) = x : snakeToCamel xs\n\n-- Usage:\nmain :: IO ()\nmain = do\n let snakeCase = \"snake_case_to_camel_case\"\n print $ snakeToCamel snakeCase -- Output: \"snakeCaseToCamelCase\"\n",
- "extension": "hs"
- },
- {
- "title": "Truncate String",
- "description": "Truncates a string to a specified length, optionally adding an ellipsis.",
- "author": "ACR1209",
- "tags": ["string", "truncate", "utility"],
- "contributors": [],
- "code": "truncateString :: Int -> String -> String\ntruncateString maxLength str\n | length str <= maxLength = str\n | otherwise = take (maxLength - 3) str ++ \"...\"\n\n-- Usage:\nmain :: IO ()\nmain = do\n let longString = \"Haskell is a powerful functional programming language.\"\n print $ truncateString 20 longString -- Output: \"Haskell is a powe...\"\n print $ truncateString 54 longString -- Output: \"Haskell is a powerful functional programming language.\"\n",
- "extension": "hs"
- }
- ]
- }
-]
+ {
+ "name": "Array Manipulation",
+ "snippets": [
+ {
+ "title": "Binary Search",
+ "description": "Searches for an element in a sorted array using binary search.",
+ "author": "ACR1209",
+ "tags": [
+ "array",
+ "binary-search",
+ "search"
+ ],
+ "contributors": [],
+ "code": "binarySearch :: Ord a => a -> [a] -> Maybe Int\nbinarySearch _ [] = Nothing\nbinarySearch target xs = go 0 (length xs - 1)\n where\n go low high\n | low > high = Nothing\n | midElem < target = go (mid + 1) high\n | midElem > target = go low (mid - 1)\n | otherwise = Just mid\n where\n mid = (low + high) `div` 2\n midElem = xs !! mid\n\n-- Usage:\nmain :: IO ()\nmain = do\n let array = [1, 2, 3, 4, 5]\n print $ binarySearch 3 array -- Output: Just 2\n print $ binarySearch 6 array -- Output: Nothing\n",
+ "extension": "hs"
+ },
+ {
+ "title": "Chunk Array",
+ "description": "Splits an array into chunks of a specified size.",
+ "author": "ACR1209",
+ "tags": [
+ "array",
+ "chunk",
+ "utility"
+ ],
+ "contributors": [],
+ "code": "chunkArray :: Int -> [a] -> [[a]]\nchunkArray _ [] = []\nchunkArray n xs = take n xs : chunkArray n (drop n xs)\n\n-- Usage:\nmain :: IO ()\nmain = do\n let array = [1, 2, 3, 4, 5, 6]\n print $ chunkArray 2 array -- Output: [[1, 2], [3, 4], [5, 6]]\n",
+ "extension": "hs"
+ },
+ {
+ "title": "Matrix Transpose",
+ "description": "Transposes a 2D matrix.",
+ "author": "ACR1209",
+ "tags": [
+ "array",
+ "matrix",
+ "transpose"
+ ],
+ "contributors": [],
+ "code": "transposeMatrix :: [[a]] -> [[a]]\ntransposeMatrix [] = []\ntransposeMatrix ([]:_) = []\ntransposeMatrix xs = map head xs : transposeMatrix (map tail xs)\n\n-- Usage:\nmain :: IO ()\nmain = do\n let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n print $ transposeMatrix matrix -- Output: [[1,4,7],[2,5,8],[3,6,9]]\n",
+ "extension": "hs"
+ }
+ ]
+ },
+ {
+ "name": "Basics",
+ "snippets": [
+ {
+ "title": "Hello, World!",
+ "description": "Prints Hello, World! to the terminal.",
+ "author": "ACR1209",
+ "tags": [
+ "printing",
+ "hello-world",
+ "utility"
+ ],
+ "contributors": [],
+ "code": "putStrLn \"Hello, World!\"\n",
+ "extension": "haskell"
+ }
+ ]
+ },
+ {
+ "name": "File Handling",
+ "snippets": [
+ {
+ "title": "Find Files in Directory by Type",
+ "description": "Finds all files in a directory with a specific extension.",
+ "author": "ACR1209",
+ "tags": [
+ "file",
+ "search",
+ "extension",
+ "filesystem"
+ ],
+ "contributors": [],
+ "code": "import System.Directory (listDirectory)\nimport System.FilePath (takeExtension)\n\nfindFilesByExtension :: FilePath -> String -> IO [FilePath]\nfindFilesByExtension dir ext = do\n files <- listDirectory dir\n return $ filter (\\f -> takeExtension f == ext) files\n\n-- Usage:\nmain :: IO ()\nmain = do\n let directory = \".\"\n let ext = \".txt\"\n files <- findFilesByExtension directory ext\n mapM_ putStrLn files -- Output: list of txt files on the current directory\n",
+ "extension": "hs"
+ },
+ {
+ "title": "Read File in Chunks",
+ "description": "Reads a file in chunks grouped by lines.",
+ "author": "ACR1209",
+ "tags": [
+ "file",
+ "read",
+ "chunks",
+ "utility"
+ ],
+ "contributors": [],
+ "code": "import System.IO (openFile, IOMode(ReadMode), hGetContents)\nimport Data.List (unfoldr)\n\nreadFileInChunks :: FilePath -> Int -> IO [[String]]\nreadFileInChunks filePath chunkSize = do\n handle <- openFile filePath ReadMode\n contents <- hGetContents handle\n let linesList = lines contents\n return $ go linesList\n where\n go [] = []\n go xs = take chunkSize xs : go (drop chunkSize xs)\n\n-- Usage:\nmain :: IO ()\nmain = do\n let file = \"example.txt\"\n let chunkSize = 3 -- Number of lines per chunk\n chunks <- readFileInChunks file chunkSize\n mapM_ (putStrLn . unlines) chunks\n\n",
+ "extension": "hs"
+ }
+ ]
+ },
+ {
+ "name": "Monads",
+ "snippets": [
+ {
+ "title": "Either Monad for Error Handling",
+ "description": "Using the Either monad to handle errors in a computation.",
+ "author": "ACR1209",
+ "tags": [
+ "monads",
+ "either",
+ "error handling"
+ ],
+ "contributors": [],
+ "code": "safeDiv :: Int -> Int -> Either String Int\nsafeDiv _ 0 = Left \"Division by zero error\"\nsafeDiv x y = Right (x `div` y)\n\n-- Usage:\nmain :: IO ()\nmain = do\n let result = do\n a <- safeDiv 10 2\n b <- safeDiv a 0 -- This will trigger an error\n return b\n print result -- Output: Left \"Division by zero error\"\n",
+ "extension": "hs"
+ },
+ {
+ "title": "Maybe Monad",
+ "description": "Using the Maybe monad to handle computations that might fail.",
+ "author": "ACR1209",
+ "tags": [
+ "monads",
+ "maybe"
+ ],
+ "contributors": [],
+ "code": "safeDiv :: Int -> Int -> Maybe Int\nsafeDiv _ 0 = Nothing\nsafeDiv x y = Just (x `div` y)\n\n-- Usage:\nmain :: IO ()\nmain = do\n let result = do\n a <- safeDiv 10 2\n b <- safeDiv a 2\n return b\n print result -- Output: Just 2\n",
+ "extension": "hs"
+ },
+ {
+ "title": "State Monad",
+ "description": "Managing mutable state using the State monad.",
+ "author": "ACR1209",
+ "tags": [
+ "monads",
+ "state",
+ "state-management"
+ ],
+ "contributors": [],
+ "code": "import Control.Monad.State\n\nincrement :: State Int Int\nincrement = do\n count <- get\n put (count + 1)\n return count\n\n-- Usage:\nmain :: IO ()\nmain = do\n let (res1, intermediateState) = runState increment 0\n print res1 -- Output: 0\n let (result, finalState) = runState increment intermediateState\n print result -- Output: 1\n print finalState -- Output: 2\n\n",
+ "extension": "hs"
+ },
+ {
+ "title": "Writer Monad",
+ "description": "Using the Writer monad to accumulate logs or other outputs alongside a computation.",
+ "author": "ACR1209",
+ "tags": [
+ "monads",
+ "writer",
+ "logs"
+ ],
+ "contributors": [],
+ "code": "import Control.Monad.Writer\n\naddAndLog :: Int -> Int -> Writer [String] Int\naddAndLog x y = do\n tell [\"Adding \" ++ show x ++ \" and \" ++ show y]\n return (x + y)\n\n-- Usage:\nmain :: IO ()\nmain = do\n let (result, logs) = runWriter $ do\n res1 <- addAndLog 3 5\n addAndLog res1 1\n print result -- Output: 9\n print logs -- Output: [\"Adding 3 and 5\", \"Adding 8 and 1\"]\n",
+ "extension": "hs"
+ }
+ ]
+ },
+ {
+ "name": "String Manipulation",
+ "snippets": [
+ {
+ "title": "CamelCase to snake_case",
+ "description": "Converts a Camel Case string to Snake case.",
+ "author": "ACR1209",
+ "tags": [
+ "string",
+ "convert",
+ "camel-case",
+ "snake-case",
+ "utility"
+ ],
+ "contributors": [],
+ "code": "import Data.Char (isUpper, toLower)\n\ncamelToSnake :: String -> String\ncamelToSnake [] = []\ncamelToSnake (x:xs)\n | isUpper x = '_' : toLower x : camelToSnake xs\n | otherwise = x : camelToSnake xs\n\n-- Usage:\nmain :: IO ()\nmain = do\n let camelCase = \"camelCaseToSnakeCase\"\n print $ camelToSnake camelCase -- Output: \"camel_case_to_snake_case\"\n",
+ "extension": "hs"
+ },
+ {
+ "title": "Capitalize Words",
+ "description": "Capitalizes the first letter of each word in a string.",
+ "author": "ACR1209",
+ "tags": [
+ "string",
+ "capitalize",
+ "words"
+ ],
+ "contributors": [],
+ "code": "import Data.Char (toUpper)\n\ncapitalizeWords :: String -> String\ncapitalizeWords = unwords . map capitalize . words\n where\n capitalize [] = []\n capitalize (x:xs) = toUpper x : xs\n\n-- Usage:\nmain :: IO ()\nmain = do\n let sentence = \"haskell is awesome\"\n print $ capitalizeWords sentence -- Output: \"Haskell Is Awesome\"\n",
+ "extension": "hs"
+ },
+ {
+ "title": "Count Word Occurrences in String",
+ "description": "Counts the occurrences of each word in a given string.",
+ "author": "ACR1209",
+ "tags": [
+ "string",
+ "occurrences",
+ "word-count"
+ ],
+ "contributors": [],
+ "code": "import Data.List (group, sort)\n\ncountWordOccurrences :: String -> [(String, Int)]\ncountWordOccurrences = map (\\(w:ws) -> (w, length (w:ws))) . group . sort . words\n\n-- Usage:\nmain :: IO ()\nmain = do\n let text = \"haskell is awesome and haskell is fun\"\n print $ countWordOccurrences text -- Output: [(\"and\",1),(\"awesome\",1),(\"fun\",1),(\"haskell\",2),(\"is\",2)]\n",
+ "extension": "hs"
+ },
+ {
+ "title": "Remove Punctuation",
+ "description": "Removes all punctuation from a given string.",
+ "author": "ACR1209",
+ "tags": [
+ "string",
+ "punctuation",
+ "remove"
+ ],
+ "contributors": [],
+ "code": "import Data.Char (isPunctuation)\n\nremovePunctuation :: String -> String\nremovePunctuation = filter (not . isPunctuation)\n\n-- Usage:\nmain :: IO ()\nmain = do\n let text = \"Hello, Haskell! How's it going?\"\n print $ removePunctuation text -- Output: \"Hello Haskell Hows it going\"\n",
+ "extension": "hs"
+ },
+ {
+ "title": "Snake_Case to CamelCase",
+ "description": "Converts a Snake Case string to Camel Case.",
+ "author": "ACR1209",
+ "tags": [
+ "string",
+ "convert",
+ "snake-case",
+ "camel-case",
+ "utilty"
+ ],
+ "contributors": [],
+ "code": "import Data.Char (toUpper)\n\nsnakeToCamel :: String -> String\nsnakeToCamel [] = []\nsnakeToCamel ('_':x:xs) = toUpper x : snakeToCamel xs\nsnakeToCamel (x:xs) = x : snakeToCamel xs\n\n-- Usage:\nmain :: IO ()\nmain = do\n let snakeCase = \"snake_case_to_camel_case\"\n print $ snakeToCamel snakeCase -- Output: \"snakeCaseToCamelCase\"\n",
+ "extension": "hs"
+ },
+ {
+ "title": "Truncate String",
+ "description": "Truncates a string to a specified length, optionally adding an ellipsis.",
+ "author": "ACR1209",
+ "tags": [
+ "string",
+ "truncate",
+ "utility"
+ ],
+ "contributors": [],
+ "code": "truncateString :: Int -> String -> String\ntruncateString maxLength str\n | length str <= maxLength = str\n | otherwise = take (maxLength - 3) str ++ \"...\"\n\n-- Usage:\nmain :: IO ()\nmain = do\n let longString = \"Haskell is a powerful functional programming language.\"\n print $ truncateString 20 longString -- Output: \"Haskell is a powe...\"\n print $ truncateString 54 longString -- Output: \"Haskell is a powerful functional programming language.\"\n",
+ "extension": "hs"
+ }
+ ]
+ }
+]
\ No newline at end of file
diff --git a/backend/data/consolidated/html.json b/backend/data/consolidated/html.json
index 10112504..e62ed638 100644
--- a/backend/data/consolidated/html.json
+++ b/backend/data/consolidated/html.json
@@ -1,25 +1,37 @@
[
- {
- "name": "Basic Layouts",
- "snippets": [
- {
- "title": "Grid Layout with Navigation",
- "description": "Full-height grid layout with header navigation using nesting syntax.",
- "author": "GreenMan36",
- "tags": ["css", "layout", "sticky", "grid", "full-height"],
- "contributors": [],
- "code": "\n\n \n \n \n \n \n Main Content
\n \n \n\n",
- "extension": "html"
- },
- {
- "title": "Sticky Header-Footer Layout",
- "description": "Full-height layout with sticky header and footer, using modern viewport units and flexbox.",
- "author": "GreenMan36",
- "tags": ["css", "layout", "sticky", "flexbox", "viewport"],
- "contributors": [],
- "code": "\n\n \n \n \n \n \n body/content
\n \n \n\n",
- "extension": "html"
- }
- ]
- }
-]
+ {
+ "name": "Basic Layouts",
+ "snippets": [
+ {
+ "title": "Grid Layout with Navigation",
+ "description": "Full-height grid layout with header navigation using nesting syntax.",
+ "author": "GreenMan36",
+ "tags": [
+ "css",
+ "layout",
+ "sticky",
+ "grid",
+ "full-height"
+ ],
+ "contributors": [],
+ "code": "\n\n \n \n \n \n \n Main Content
\n \n \n\n",
+ "extension": "html"
+ },
+ {
+ "title": "Sticky Header-Footer Layout",
+ "description": "Full-height layout with sticky header and footer, using modern viewport units and flexbox.",
+ "author": "GreenMan36",
+ "tags": [
+ "css",
+ "layout",
+ "sticky",
+ "flexbox",
+ "viewport"
+ ],
+ "contributors": [],
+ "code": "\n\n \n \n \n \n \n body/content
\n \n \n\n",
+ "extension": "html"
+ }
+ ]
+ }
+]
\ No newline at end of file
diff --git a/backend/data/consolidated/java.json b/backend/data/consolidated/java.json
index 3b331fff..8c66af67 100644
--- a/backend/data/consolidated/java.json
+++ b/backend/data/consolidated/java.json
@@ -1,465 +1,670 @@
[
- {
- "name": "Array Manipulation",
- "snippets": [
- {
- "title": "Remove duplicates",
- "description": "Removes duplicate elements from an list",
- "author": "Mcbencrafter",
- "tags": ["list", "duplicates", "unique"],
- "contributors": [],
- "code": "import java.util.List;\nimport java.util.stream.Collectors;\n\npublic static List removeDuplicates(List list) {\n return list.stream()\n .distinct()\n .collect(Collectors.toList());\n}\n\n// Usage:\nList list = List.of(1, 2, 3, 4, 5, 1, 2, 3, 4, 5);\nList result = removeDuplicates(list);\nSystem.out.println(\"List with duplicates removed: \" + result); // [1, 2, 3, 4, 5]\n",
- "extension": "java"
- },
- {
- "title": "Zip Two Lists",
- "description": "Zips two lists into a list of paired elements, combining corresponding elements from both lists.",
- "author": "davidanukam",
- "tags": ["lists", "zip", "stream-api", "collections"],
- "contributors": [],
- "code": "import java.util.*; // Importing utility classes for List and Arrays\nimport java.util.stream.IntStream; // Importing IntStream for range and mapping\nimport java.util.stream.Collectors; // Importing Collectors for collecting stream results\n\npublic List> zip(List list1, List list2) {\n // Create pairs by iterating through the indices of both lists\n return IntStream.range(0, Math.min(list1.size(), list2.size())) // Limit the range to the smaller list\n .mapToObj(i -> Arrays.asList(list1.get(i), list2.get(i))) // Pair elements from both lists at index i\n .collect(Collectors.toList()); // Collect the pairs into a List\n}\n\n// Usage:\nList arr1 = Arrays.asList(\"a\", \"b\", \"c\");\nList arr2 = Arrays.asList(1, 2, 3);\nList> zipped = zip(arr1, arr2);\n\nSystem.out.println(zipped); // Output: [[a, 1], [b, 2], [c, 3]]\n",
- "extension": "java"
- }
- ]
- },
- {
- "name": "Basics",
- "snippets": [
- {
- "title": "Hello-World",
- "description": "Prints Hello world in the console",
- "author": "SarvariHarshitha",
- "tags": ["java", "console", "printing"],
- "contributors": [],
- "code": "// This is the main class of the Java program\npublic class Main {\n // The main method is the entry point of the program\n public static void main(String args[]) {\n // This statement prints \"Hello, World!\" to the console\n System.out.println(\"Hello, World!\");\n }\n}\n\n",
- "extension": "java"
- }
- ]
- },
- {
- "name": "Bit Manipulation",
- "snippets": [
- {
- "title": "Bit Counting",
- "description": "Counts the set bits in the binary representation of an integer",
- "author": "Mcbencrafter",
- "tags": ["math", "number", "bits", "bit-counting"],
- "contributors": [],
- "code": "public static int countBits(int number) {\n int bits = 0;\n \n while (number > 0) {\n bits += number & 1;\n number >>= 1;\n }\n\n return bits;\n}\n\n// Usage:\nint number = 5;\nSystem.out.println(countBits(5)); // 2 (101)\n",
- "extension": "java"
- },
- {
- "title": "Is Power Of Two",
- "description": "Checks if a number is a power of two",
- "author": "Mcbencrafter",
- "tags": ["math", "number", "bit", "power-of-two"],
- "contributors": [],
- "code": "public static boolean isPowerOfTwo(int number) {\n return (number > 0) && ((number & (number - 1)) == 0);\n}\n\n// Usage:\nint number = 16;\nSystem.out.println(isPowerOfTwo(number)); // true (2^4)\n",
- "extension": "java"
- }
- ]
- },
- {
- "name": "Date Time",
- "snippets": [
- {
- "title": "Date Time Formatting American",
- "description": "Formats a timestamp to a human-readable date-time string in the format \"MM/dd/yyyy hh:mm:ss a\"",
- "author": "Mcbencrafter",
- "tags": ["date", "time", "date-time", "formatting", "american"],
- "contributors": [],
- "code": "import java.time.Instant;\nimport java.time.ZoneId;\nimport java.time.format.DateTimeFormatter;\nimport java.util.concurrent.TimeUnit;\n\n// using the system default time zone\npublic static String formatDateTimeAmerican(long time, TimeUnit timeUnit) {\n return formatDateTimeAmerican(time, timeUnit, ZoneId.systemDefault());\n}\n\npublic static String formatDateTimeAmerican(long time, TimeUnit timeUnit, ZoneId timeZone) {\n return DateTimeFormatter.ofPattern(\"MM/dd/yyyy hh:mm:ss a\")\n .withZone(\n timeZone != null ? timeZone : ZoneId.systemDefault()\n )\n .format(Instant.ofEpochSecond(\n timeUnit.toSeconds(time)\n ));\n}\n\n// Usage:\nSystem.out.println(formatDateTimeAmerican(1735689599, TimeUnit.SECONDS)); // \"12/31/2024 | 11:59:59 PM\" for GMT+0000\nSystem.out.println(formatDateTimeAmerican(1735689599, TimeUnit.SECONDS, ZoneId.of(\"GMT+0000\"))); // \"12/31/2024 | 11:59:59 PM\"\n",
- "extension": "java"
- },
- {
- "title": "Date Time Formatting European",
- "description": "Formats a timestamp to a human-readable date-time string in the format \"dd.MM.yyyy HH:mm:ss\"",
- "author": "Mcbencrafter",
- "tags": ["date", "time", "date-time", "formatting", "european"],
- "contributors": [],
- "code": "import java.time.Instant;\nimport java.time.ZoneId;\nimport java.time.format.DateTimeFormatter;\nimport java.util.concurrent.TimeUnit;\n\n// using the system default time zone\npublic static String formatDateTimeEuropean(long time, TimeUnit timeUnit) {\n return formatDateTimeEuropean(time, timeUnit, ZoneId.systemDefault());\n}\n\npublic static String formatDateTimeEuropean(long time, TimeUnit timeUnit, ZoneId timeZone) {\n return DateTimeFormatter.ofPattern(\"dd.MM.yyyy HH:mm:ss\")\n .withZone(\n timeZone != null ? timeZone : ZoneId.systemDefault()\n )\n .format(Instant.ofEpochSecond(\n timeUnit.toSeconds(time)\n ));\n}\n\n// Usage:\nSystem.out.println(formatDateTimeEuropean(1735689599, TimeUnit.SECONDS)); // \"31.12.2024 | 23:59:59\" for GMT+0000\nSystem.out.println(formatDateTimeEuropean(1735689599, TimeUnit.SECONDS, ZoneId.of(\"GMT+0000\"))); // \"31.12.2024 | 23:59:59\"\n",
- "extension": "java"
- },
- {
- "title": "Duration Formatting Hours Minutes Seconds",
- "description": "Converts a given time duration to a human-readable string in the format \"hh:mm(:ss)\"",
- "author": "Mcbencrafter",
- "tags": ["time", "formatting", "hours", "minutes", "seconds"],
- "contributors": [],
- "code": "import java.util.concurrent.TimeUnit;\n \npublic static String formatDurationToHoursMinutesAndSeconds(int time, TimeUnit timeUnit, boolean showSeconds) {\n long totalSeconds = timeUnit.toSeconds(time);\n\n if (totalSeconds < 0)\n throw new IllegalArgumentException(\"Duration must be a non-negative value.\");\n\n // These variables can be directly used in the return statement,\n // but are kept as separate variables here for better readability.\n long hours = totalSeconds / 3600;\n long minutes = (totalSeconds % 3600) / 60;\n long seconds = totalSeconds % 60;\n\n if (showSeconds) {\n return String.format(\"%02d:%02d:%02d\", hours, minutes, seconds);\n } else {\n return String.format(\"%02d:%02d\", hours, minutes);\n }\n}\n\n// Usage:\nSystem.out.println(formatDurationToHoursMinutesAndSeconds(3810, TimeUnit.SECONDS, true)); // \"01:03:30\"\nSystem.out.println(formatDurationToHoursMinutesAndSeconds(3810, TimeUnit.SECONDS, false)); // \"01:03\"\n",
- "extension": "java"
- },
- {
- "title": "Duration Formatting Minutes Seconds",
- "description": "Converts a given time duration to a human-readable string in the format \"mm:ss\"",
- "author": "Mcbencrafter",
- "tags": ["time", "formatting", "minutes", "seconds"],
- "contributors": [],
- "code": "import java.util.concurrent.TimeUnit;\n\npublic static String formatDurationToMinutesAndSeconds(int time, TimeUnit timeUnit) {\n long totalSeconds = timeUnit.toSeconds(time);\n\n if (totalSeconds < 0)\n throw new IllegalArgumentException(\"Duration must be a non-negative value.\");\n\n // These variables can be directly used in the return statement,\n // but are kept here as separate variables for better readability.\n long minutes = totalSeconds / 60;\n long seconds = totalSeconds % 60;\n\n return String.format(\"%02d:%02d\", minutes, seconds);\n}\n\n// Usage:\nSystem.out.println(formatDurationToMinutesAndSeconds(120, TimeUnit.SECONDS)); // \"02:00\"\nSystem.out.println(formatDurationToMinutesAndSeconds(75, TimeUnit.SECONDS)); // \"01:15\"\n",
- "extension": "java"
- }
- ]
- },
- {
- "name": "Math",
- "snippets": [
- {
- "title": "Checksum",
- "description": "Calculates the checksum of an int",
- "author": "Mcbencrafter",
- "tags": ["math", "number", "checksum"],
- "contributors": [],
- "code": "public static int checksum(int number) {\n number = Math.abs(number);\n int sum = 0;\n\n while (number != 0) {\n sum += number % 10;\n number /= 10;\n }\n\n return sum;\n}\n\n// Usage:\nint number = 12345;\nSystem.out.println(checksum(number)); // 15 = 1+2+3+4+5\n",
- "extension": "java"
- },
- {
- "title": "Factorial",
- "description": "Computes the factorial of a given number",
- "author": "Mcbencrafter",
- "tags": ["math", "number", "factorial"],
- "contributors": [],
- "code": "import java.math.BigInteger;\n\npublic static BigInteger factorial(int number) {\n BigInteger result = BigInteger.ONE;\n\n for (int currentNumber = 1; currentNumber <= number; currentNumber++) {\n result = result.multiply(BigInteger.valueOf(currentNumber));\n }\n\n return result;\n}\n\n// Usage:\nint number = 6;\nSystem.out.println(factorial(number)); // 720 = 6*5*4*3*2\n",
- "extension": "java"
- },
- {
- "title": "Fibonacci",
- "description": "Calculates the nth fibonacci number",
- "author": "Mcbencrafter",
- "tags": ["math", "number", "fibonacci"],
- "contributors": [],
- "code": "public static int fibonacci(int number) {\n if (number <= 1) \n return number;\n \n return fibonacci(number - 1) + fibonacci(number - 2);\n}\n\n// Usage:\nint number = 5;\nSystem.out.println(fibonacci(number)) // 3 (0, 1, 1, 2, 3)\n",
- "extension": "java"
- },
- {
- "title": "Greatest Common Divisor",
- "description": "Calculates the greatest common divisor (gcd) of two numbers",
- "author": "Mcbencrafter",
- "tags": [
- "math",
- "number",
- "greatest-common-devisor",
- "gcd",
- "euclidean-algorithm"
- ],
- "contributors": [],
- "code": "public static int gcd(int number1, int number2) {\n while (number2 != 0) {\n int remainder = number2;\n number2 = number1 % number2;\n number1 = remainder;\n }\n\n return number1;\n}\n\n// Usage:\nint a = 16;\nint b = 12;\nSystem.out.println(gcd(a, b)); // 4\n",
- "extension": "java"
- },
- {
- "title": "Least Common Multiple",
- "description": "Calculates the least common multiple (lcm) of two numbers",
- "author": "Mcbencrafter",
- "tags": [
- "math",
- "number",
- "least-common-multiple",
- "lcm",
- "euclidean-algorithm"
- ],
- "contributors": [],
- "code": "public static int lcm(int number1, int number2) {\n int gcdNumber1 = number1;\n int gcdNumber2 = number2;\n \n while (gcdNumber2 != 0) {\n int remainder = gcdNumber2;\n gcdNumber2 = gcdNumber1 % gcdNumber2;\n gcdNumber1 = remainder;\n }\n \n return (number1 / gcdNumber1) * number2;\n}\n\n// Usage:\nint a = 16;\nint b = 12;\nSystem.out.println(lcm(a, b)); // 48\n",
- "extension": "java"
- },
- {
- "title": "Prime Check",
- "description": "Checks if a number is a prime",
- "author": "Mcbencrafter",
- "tags": ["math", "number", "prime"],
- "contributors": [],
- "code": "public static boolean isPrime(int number) {\n if (number <= 1) \n return false;\n\n if (number <= 3) \n return true;\n\n boolean prime = true;\n for (int divisor = 3; divisor < number; divisor++) {\n if (number % divisor != 0)\n continue;\n\n prime = false;\n break;\n }\n\n return prime;\n}\n\n// Usage:\nint number = 31;\nSystem.out.println(isPrime(number)); // true\n",
- "extension": "java"
- }
- ]
- },
- {
- "name": "String Manipulation",
- "snippets": [
- {
- "title": "Ascii To String",
- "description": "Converts a list of ascii numbers into a string",
- "author": "Mcbencrafter",
- "tags": ["string", "ascii", "encoding", "decode", "conversion"],
- "contributors": [],
- "code": "import java.util.List;\n\npublic static String asciiToString(List asciiCodes) {\n StringBuilder text = new StringBuilder();\n\n for (int asciiCode : asciiCodes) {\n text.append((char) asciiCode);\n }\n\n return text.toString();\n}\n\n// Usage:\nSystem.out.println(asciiToString(List.of(104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100))); // \"hello world\"\n",
- "extension": "java"
- },
- {
- "title": "camelCase to snake_case",
- "description": "Converts a camelCase string into snake_case",
- "author": "Mcbencrafter",
- "tags": ["string", "conversion", "camel-case", "snake-case"],
- "contributors": [],
- "code": "public static String camelToSnake(String camelCase) {\n return camelCase.replaceAll(\"([a-z])([A-Z])\", \"$1_$2\").toLowerCase();\n}\n\n// Usage:\nSystem.out.println(camelToSnake(\"helloWorld\")); // \"hello_world\"\n",
- "extension": "java"
- },
- {
- "title": "Capitalize Words",
- "description": "Capitalizes the first letter of each word in a string",
- "author": "Mcbencrafter",
- "tags": ["string", "capitalize", "words"],
- "contributors": [],
- "code": "public static String capitalizeWords(String text) {\n String[] words = text.split(\"(?<=\\\\S)(?=\\\\s+)|(?<=\\\\s+)(?=\\\\S)\"); // this is needed to preserve spaces (text.split(\" \") would remove multiple spaces)\n StringBuilder capitalizedText = new StringBuilder();\n \n for (String word : words) {\n if (word.trim().isEmpty()) {\n capitalizedText.append(word);\n continue;\n }\n capitalizedText.append(Character.toUpperCase(word.charAt(0)))\n .append(word.substring(1));\n }\n \n return capitalizedText.toString();\n}\n\n// Usage:\nSystem.out.println(capitalizeWords(\"hello world\")); // \"Hello World\"\n",
- "extension": "java"
- },
- {
- "title": "Check Anagram",
- "description": "Checks if two strings are anagrams, meaning they contain the same characters ignoring order, spaces and case sensitivity",
- "author": "Mcbencrafter",
- "tags": ["string", "anagram", "compare", "arrays"],
- "contributors": [],
- "code": "import java.util.Arrays;\n\npublic static boolean isAnagram(String text1, String text2) {\n String text1Normalized = text1.replaceAll(\"\\\\s+\", \"\");\n String text2Normalized = text2.replaceAll(\"\\\\s+\", \"\");\n\n if (text1Normalized.length() != text2Normalized.length())\n return false;\n \n char[] text1Array = text1Normalized.toCharArray();\n char[] text2Array = text2Normalized.toCharArray();\n Arrays.sort(text1Array);\n Arrays.sort(text2Array);\n return Arrays.equals(text1Array, text2Array);\n}\n\n// Usage:\nSystem.out.println(isAnagram(\"listen\", \"silent\")); // true\nSystem.out.println(isAnagram(\"hello\", \"world\")); // false\n",
- "extension": "java"
- },
- {
- "title": "Check Palindrome",
- "description": "Checks if a string reads the same backward as forward, ignoring whitespaces and case sensitivity",
- "author": "Mcbencrafter",
- "tags": ["string", "palindrome", "compare", "reverse"],
- "contributors": [],
- "code": "public static boolean isPalindrome(String text) {\n String cleanText = text.toLowerCase().replaceAll(\"\\\\s+\", \"\");\n \n return new StringBuilder(cleanText)\n .reverse()\n .toString()\n .equals(cleanText);\n}\n\n// Usage:\nSystem.out.println(isPalindrome(\"A man a plan a canal Panama\")); // true\n",
- "extension": "java"
- },
- {
- "title": "Count Character Frequency",
- "description": "Counts the frequency of each character in a string",
- "author": "Mcbencrafter",
- "tags": ["string", "character", "frequency", "character-frequency"],
- "contributors": [],
- "code": "public static Map characterFrequency(String text, boolean countSpaces, boolean caseSensitive) {\n Map frequencyMap = new HashMap<>();\n\n for (char character : text.toCharArray()) {\n if (character == ' ' && !countSpaces)\n continue;\n\n if (!caseSensitive)\n character = Character.toLowerCase(character);\n\n frequencyMap.put(character, frequencyMap.getOrDefault(character, 0) + 1);\n }\n\n return frequencyMap;\n}\n\n// Usage:\nSystem.out.println(characterFrequency(\"hello world\", false, false)); // {r=1, d=1, e=1, w=1, h=1, l=3, o=2}\n",
- "extension": "java"
- },
- {
- "title": "Count Character Occurrences",
- "description": "Counts the occurrences of the specified characters in a given string",
- "author": "Mcbencrafter",
- "tags": ["string", "characters", "counter", "occurence"],
- "contributors": [],
- "code": "import java.util.List;\n\npublic static int countCharacterOccurrences(String text, List characters) {\n int count = 0;\n \n for (char character : text.toCharArray()) {\n if (characters.indexOf(character) == -1)\n continue;\n \n count++;\n }\n \n return count;\n}\n\n// Usage:\nSystem.out.println(countCharacterOccurrences(\"hello world\", List.of('l', 'o'))); // 5\n",
- "extension": "java"
- },
- {
- "title": "Count Words",
- "description": "Counts the number of words in a string",
- "author": "Mcbencrafter",
- "tags": ["string", "word", "count"],
- "contributors": [],
- "code": "public static int countWords(String text) {\n return text.split(\"\\\\s+\").length;\n}\n\n// Usage:\nSystem.out.println(countWords(\"hello world\")); // 2\n",
- "extension": "java"
- },
- {
- "title": "Extract Text Between Delimiters",
- "description": "Extracts a text between two given delimiters from a string",
- "author": "Mcbencrafter",
- "tags": ["string", "delimiters", "start", "end"],
- "contributors": [],
- "code": "public static String extractBetweenDelimiters(String text, String start, String end) {\n int startIndex = text.indexOf(start);\n int endIndex = text.indexOf(end, startIndex + start.length());\n \n if (startIndex == -1 || endIndex == -1)\n return \"\";\n \n return text.substring(startIndex + start.length(), endIndex);\n}\n\n// Usage:\nSystem.out.println(extractBetweenDelimiters(\"hello, world!\", \",\", \"!\")); // \" world\"\n",
- "extension": "java"
- },
- {
- "title": "Find Longest Word",
- "description": "Returns the longest word in a string",
- "author": "Mcbencrafter",
- "tags": ["string", "length", "words"],
- "contributors": [],
- "code": "public static String findLongestWord(String text) {\n String[] words = text.split(\"\\\\s+\");\n String longestWord = words[0];\n \n for (String word : words) {\n if (word.length() <= longestWord.length())\n continue;\n \n longestWord = word;\n }\n\n return longestWord;\n}\n\n// Usage:\nSystem.out.println(findLongestWord(\"hello world123\")); // \"world123\"\n",
- "extension": "java"
- },
- {
- "title": "Find Unique Characters",
- "description": "Returns a set of unique characters from a string, with options to include spaces and control case sensitivity",
- "author": "Mcbencrafter",
- "tags": ["string", "unique", "characters", "case-sensitive"],
- "contributors": [],
- "code": "public static Set findUniqueCharacters(String text, boolean countSpaces, boolean caseSensitive) {\n Set uniqueCharacters = new TreeSet<>();\n \n for (char character : text.toCharArray()) {\n if (character == ' ' && !countSpaces)\n continue;\n if (!caseSensitive)\n character = Character.toLowerCase(character);\n uniqueCharacters.add(character);\n }\n \n return uniqueCharacters;\n}\n\n// Usage:\nSystem.out.println(findUniqueCharacters(\"hello world\", false, true)); // Output: [d, e, h, l, o, r, w]\n",
- "extension": "java"
- },
- {
- "title": "Mask Text",
- "description": "Masks portions of a string, leaving specific parts at the beginning and end visible while replacing the rest with a specified character",
- "author": "Mcbencrafter",
- "tags": ["string", "mask", "hide"],
- "contributors": [],
- "code": "public static String partialMask(String text, int maskLengthStart, int maskLengthEnd, char mask) \n if (text == null)\n return null;\n \n StringBuilder maskedText = new StringBuilder();\n maskedText.append(text, 0, maskLengthStart);\n \n for (int currentChar = maskLengthStart; currentChar < text.length(); currentChar++) {\n maskedText.append(mask);\n }\n maskedText.append(text, text.length() - maskLengthEnd, text.length());\n return maskedText.toString();\n}\n\n// Usage:\nSystem.out.println(partialMask(\"1234567890\", 4, 2, '*')); // \"1234****90\"\n",
- "extension": "java"
- },
- {
- "title": "Normalize Whitespace",
- "description": "Replaces consecutive whitespaces with a single space",
- "author": "Mcbencrafter",
- "tags": ["string", "whitespace", "normalize"],
- "contributors": [],
- "code": "public static String normalizeWhitespace(String text) {\n return text.replaceAll(\" {2,}\", \" \");\n}\n\n// Usage:\nSystem.out.println(normalizeWhitespace(\"hello world\")); // \"hello world\"\n",
- "extension": "java"
- },
- {
- "title": "Password Generator",
- "description": "Generates a random string with specified length and character set, including options for letters, numbers, and special characters ",
- "author": "Mcbencrafter",
- "tags": [
- "string",
- "password",
- "generator",
- "security",
- "random",
- "token"
- ],
- "contributors": [],
- "code": "public static String randomString(int length, boolean useLetters, boolean useNumbers, boolean useSpecialCharacters) {\n String characters = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n String numbers = \"0123456789\";\n String specialCharacters = \"!@#$%^&*()_+-=[]{}|;:,.<>?\";\n \n String allowedCharacters = \"\";\n \n if (useLetters)\n allowedCharacters += characters;\n\n if (useNumbers)\n allowedCharacters += numbers;\n\n if (useSpecialCharacters)\n allowedCharacters += specialCharacters;\n\n SecureRandom random = new SecureRandom();\n StringBuilder result = new StringBuilder(length);\n\n for (int i = 0; i < length; i++) {\n int index = random.nextInt(allowedCharacters.length());\n result.append(allowedCharacters.charAt(index));\n }\n\n return result.toString();\n}\n\n// Usage:\nSystem.out.println(randomString(10, true, true, false)); // Random string containing letters, numbers but no special characters with 10 characters\n",
- "extension": "java"
- },
- {
- "title": "Remove Punctuation",
- "description": "Removes punctuation (, . !) from a string",
- "author": "Mcbencrafter",
- "tags": ["string", "punctuation", "clean", "normalization"],
- "contributors": [],
- "code": "public static String removePunctuation(String text) {\n return text.replaceAll(\"[,!.?;:]\", \"\");\n}\n\n// Usage:\nSystem.out.println(removePunctuation(\"hello, world!\")); // \"hello world\"\n",
- "extension": "java"
- },
- {
- "title": "Remove Special Characters",
- "description": "Removes any character which is not alphabetic (A-Z, a-z) or numeric (0-9)",
- "author": "Mcbencrafter",
- "tags": ["string", "special-characters", "clean", "normalization"],
- "contributors": [],
- "code": "public static String removeSpecialCharacters(String text) {\n return text.replaceAll(\"[^a-zA-Z0-9]\", \"\");\n}\n\n// Usage:\nSystem.out.println(removeSpecialCharacters(\"hello, world!#%\")); // \"hello world\"\n",
- "extension": "java"
- },
- {
- "title": "Reverse Word Contents",
- "description": "Reverses the characters of each word in a string while preserving word order",
- "author": "Mcbencrafter",
- "tags": ["string", "reverse", "words", "transformation", "order"],
- "contributors": [],
- "code": "public static String reverseWords(String text) {\n String[] words = text.split(\"\\\\s+\"); \n StringBuilder reversedText = new StringBuilder();\n\n for (String word : words) {\n StringBuilder reversedWord = new StringBuilder(word).reverse();\n reversedText.append(reversedWord).append(\" \");\n }\n\n return reversedText.toString().trim();\n}\n\n// Usage:\nSystem.out.println(reverseWordContents(\"hello world\")); // \"olleh dlrow\"\n",
- "extension": "java"
- },
- {
- "title": "Reverse Word Order",
- "description": "Reverses the order of words in a sentence while preserving the content of each word",
- "author": "Mcbencrafter",
- "tags": ["string", "reverse", "words", "transformation", "sentence"],
- "contributors": [],
- "code": "public static String reverseWords(String text) {\n String[] words = text.split(\"\\\\s+\");\n StringBuilder reversedSentence = new StringBuilder();\n\n for (int currentWord = words.length - 1; currentWord >= 0; currentWord--) {\n reversedSentence.append(words[currentWord]).append(\" \");\n }\n\n return reversedSentence.toString().trim();\n}\n\n// Usage:\nSystem.out.println(reverseWords(\"hello world\")); // Output: world hello\n",
- "extension": "java"
- },
- {
- "title": "Slugify String",
- "description": "Converts a string into a URL-friendly slug format",
- "author": "Mcbencrafter",
- "tags": ["string", "slug", "slugify"],
- "contributors": [],
- "code": "public static String slugify(String text, String separator) {\n if (text == null)\n return \"\";\n\n // used to decompose accented characters to their base characters (e.g. \"é\" to \"e\")\n String normalizedString = Normalizer.normalize(text, Normalizer.Form.NFD);\n normalizedString = normalizedString.replaceAll(\"[\\\\p{InCombiningDiacriticalMarks}]\", \"\");\n\n String slug = normalizedString.trim()\n .toLowerCase()\n .replaceAll(\"\\\\s+\", separator)\n .replaceAll(\"[^a-z0-9\\\\-_\" + separator + \"]\", \"\")\n .replaceAll(\"_\", separator)\n .replaceAll(\"-\", separator)\n .replaceAll(separator + \"+\", separator)\n .replaceAll(separator + \"$\", \"\");\n\n return slug;\n}\n\n// Usage:\nSystem.out.println(slugify(\"Hello World-#123-é\", \"-\")); // \"hello-world-123-e\"\n",
- "extension": "java"
- },
- {
- "title": "snake_case to camelCase",
- "description": "Converts a snake_case string into camelCase",
- "author": "Mcbencrafter",
- "tags": ["string", "conversion", "camel-case", "snake-case"],
- "contributors": [],
- "code": "import java.util.regex.Pattern;\n\npublic static String snakeToCamel(String snakeCase) {\n return Pattern.compile(\"(_)([a-z])\")\n .matcher(snakeCase)\n .replaceAll(match -> match.group(2).toUpperCase());\n}\n\n// Usage:\nSystem.out.println(snakeToCamel(\"hello_world\")); // \"helloWorld\"\n",
- "extension": "java"
- },
- {
- "title": "Spaces To Tabs",
- "description": "Converts spaces into tabs",
- "author": "Mcbencrafter",
- "tags": ["string", "tab", "space", "conversion"],
- "contributors": [],
- "code": "public static String convertSpacesToTab(String text, int spacesPerTab) {\n return text.replaceAll(\" \".repeat(spacesPerTab), \"\\t\");\n}\n\n// Usage:\nSystem.out.println(convertSpacesToTab(\"hello world\", 4)); // Output: hello\\tworld\n",
- "extension": "java"
- },
- {
- "title": "String To Ascii",
- "description": "Converts a string into ascii numbers",
- "author": "Mcbencrafter",
- "tags": ["string", "ascii", "encoding", "conversion"],
- "contributors": [],
- "code": "import java.util.ArrayList;\nimport java.util.List;\n\npublic static List stringToAscii(String text) {\n List asciiCodes = new ArrayList<>();\n\n for (char character : text.toCharArray()) {\n asciiCodes.add((int) character);\n }\n\n return asciiCodes;\n}\n\n// Usage:\nSystem.out.println(stringToAscii(\"hello world\")); // [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]\n",
- "extension": "java"
- },
- {
- "title": "String To camelCase",
- "description": "Converts a string into camelCase",
- "author": "Mcbencrafter",
- "tags": ["string", "conversion", "camel-case"],
- "contributors": [],
- "code": "public static String stringToCamelCase(String text) {\n String[] words = text.split(\"\\\\s+\");\n StringBuilder camelCase = new StringBuilder(\n words[0].substring(0, 1).toLowerCase() + words[0].substring(1)\n );\n\n for (int i = 1; i < words.length; i++) {\n camelCase.append(words[i].substring(0, 1).toUpperCase());\n camelCase.append(words[i].substring(1));\n }\n\n return camelCase.toString();\n}\n\n// Usage:\nSystem.out.println(stringToCamelCase(\"Hello world test\")); // \"helloWorldTest\"\n",
- "extension": "java"
- },
- {
- "title": "String To param-case",
- "description": "Converts a string into param-case",
- "author": "Mcbencrafter",
- "tags": ["string", "conversion", "param-case"],
- "contributors": [],
- "code": "public static String stringToParamCase(String text) {\n return text.toLowerCase().replaceAll(\"\\\\s+\", \"-\");\n}\n\n// Usage:\nSystem.out.println(stringToParamCase(\"Hello World 123\")); // \"hello-world-123\"\n",
- "extension": "java"
- },
- {
- "title": "String To PascalCase",
- "description": "Converts a string into PascalCase",
- "author": "Mcbencrafter",
- "tags": ["string", "conversion", "pascal-case"],
- "contributors": [],
- "code": "public static String stringToPascalCase(String text) {\n String[] words = text.split(\"\\\\s+\");\n StringBuilder pascalCase = new StringBuilder();\n\n for (String word : words) {\n pascalCase.append(word.substring(0, 1).toUpperCase());\n pascalCase.append(word.substring(1).toLowerCase());\n }\n\n return pascalCase.toString();\n}\n\n// Usage:\nSystem.out.println(stringToPascalCase(\"hello world\")); // \"HelloWorld\"\n",
- "extension": "java"
- },
- {
- "title": "String To snake_case",
- "description": "Converts a string into snake_case",
- "author": "Mcbencrafter",
- "tags": ["string", "conversion", "snake-case"],
- "contributors": [],
- "code": "public static String stringToSnakeCase(String text) {\n return text.toLowerCase().replaceAll(\"\\\\s+\", \"_\");\n}\n\n// Usage:\nSystem.out.println(stringToSnakeCase(\"Hello World 123\")); // \"hello_world_123\"\n",
- "extension": "java"
- },
- {
- "title": "String To Titlecase",
- "description": "Converts a string into Title Case, where the first letter of each word is capitalized and the remaining letters are lowercase",
- "author": "Mcbencrafter",
- "tags": ["string", "conversion", "title-case"],
- "contributors": [],
- "code": "public static String convertToTitleCase(String text) {\n String[] words = text.split(\"(?<=\\\\S)(?=\\\\s+)|(?<=\\\\s+)(?=\\\\S)\"); // this is needed to preserve spaces (text.split(\" \") would remove multiple spaces)\n StringBuilder capitalizedText = new StringBuilder();\n\n for (String word : words) {\n if (word.trim().isEmpty()) {\n capitalizedText.append(word);\n continue;\n }\n\n capitalizedText.append(Character.toUpperCase(word.charAt(0)))\n .append(word.substring(1).toLowerCase());\n }\n\n return capitalizedText.toString().trim();\n}\n\n// Usage:\nSystem.out.println(convertToTitleCase(\"heLlo wOrld\")); // \"Hello World\"\n",
- "extension": "java"
- },
- {
- "title": "String To Unicode",
- "description": "Converts characters of a string into their unicode representation",
- "author": "Mcbencrafter",
- "tags": ["string", "unicode", "encoding", "conversion"],
- "contributors": [],
- "code": "public static String stringToUnicode(String text) {\n StringBuilder unicodeText = new StringBuilder();\n\n for (char character : text.toCharArray()) {\n unicodeText.append(String.format(\"\\\\u%04x\", (int) character));\n }\n\n return unicodeText.toString();\n}\n\n// Usage:\nSystem.out.println(stringToUnicode(\"hello world\")); // \\u0068\\u0065\\u006C\\u006C\\u006F\\u0020\\u0077\\u006F\\u0072\\u006C\\u0064\n",
- "extension": "java"
- },
- {
- "title": "Tabs To Spaces",
- "description": "Converts tabs into spaces",
- "author": "Mcbencrafter",
- "tags": ["string", "tab", "space", "conversion"],
- "contributors": [],
- "code": "public static String convertTabToSpace(String text, int spacesPerTab) {\n return text.replaceAll(\"\\t\", \" \".repeat(spacesPerTab));\n}\n\n// Usage:\nSystem.out.println(convertTabToSpace(\"hello\\tworld\", 2)); // \"hello world\"\n",
- "extension": "java"
- },
- {
- "title": "Truncate String",
- "description": "Truncates a string after a specified length (can also be used for hiding information)",
- "author": "Mcbencrafter",
- "tags": ["string", "truncate", "mask", "hide"],
- "contributors": [],
- "code": "public static String truncate(String text, int length, String suffix) {\n if (text.length() <= length)\n return text;\n \n return text.substring(0, length).trim() + (suffix != null ? suffix : \"\");\n}\n\n// Usage:\nSystem.out.println(truncate(\"hello world\", 5, \"...\")); // \"hello...\"\n",
- "extension": "java"
- },
- {
- "title": "Unicode To String",
- "description": "Converts a unicode String into its normal representation",
- "author": "Mcbencrafter",
- "tags": ["string", "unicode", "encoding", "decoding", "conversion"],
- "contributors": [],
- "code": "public static String unicodeToString(String unicode) {\n StringBuilder string = new StringBuilder();\n String[] hex = unicode.split(\"\\\\\\\\u\");\n\n for (int symbol = 1; symbol < hex.length; symbol++) {\n int data = Integer.parseInt(hex[symbol], 16);\n string.append((char) data);\n }\n\n return string.toString();\n}\n\n// Usage:\nSystem.out.println(unicodeToString(\"\\\\u0068\\\\u0065\\\\u006c\\\\u006c\\\\u006f\\\\u0020\\\\u0077\\\\u006f\\\\u0072\\\\u006c\\\\u0064\")); // \"hello world\"\n",
- "extension": "java"
- }
- ]
- }
-]
+ {
+ "name": "Array Manipulation",
+ "snippets": [
+ {
+ "title": "Remove duplicates",
+ "description": "Removes duplicate elements from an list",
+ "author": "Mcbencrafter",
+ "tags": [
+ "list",
+ "duplicates",
+ "unique"
+ ],
+ "contributors": [],
+ "code": "import java.util.List;\nimport java.util.stream.Collectors;\n\npublic static List removeDuplicates(List list) {\n return list.stream()\n .distinct()\n .collect(Collectors.toList());\n}\n\n// Usage:\nList list = List.of(1, 2, 3, 4, 5, 1, 2, 3, 4, 5);\nList result = removeDuplicates(list);\nSystem.out.println(\"List with duplicates removed: \" + result); // [1, 2, 3, 4, 5]\n",
+ "extension": "java"
+ },
+ {
+ "title": "Zip Two Lists",
+ "description": "Zips two lists into a list of paired elements, combining corresponding elements from both lists.",
+ "author": "davidanukam",
+ "tags": [
+ "lists",
+ "zip",
+ "stream-api",
+ "collections"
+ ],
+ "contributors": [],
+ "code": "import java.util.*; // Importing utility classes for List and Arrays\nimport java.util.stream.IntStream; // Importing IntStream for range and mapping\nimport java.util.stream.Collectors; // Importing Collectors for collecting stream results\n\npublic List> zip(List list1, List list2) {\n // Create pairs by iterating through the indices of both lists\n return IntStream.range(0, Math.min(list1.size(), list2.size())) // Limit the range to the smaller list\n .mapToObj(i -> Arrays.asList(list1.get(i), list2.get(i))) // Pair elements from both lists at index i\n .collect(Collectors.toList()); // Collect the pairs into a List\n}\n\n// Usage:\nList arr1 = Arrays.asList(\"a\", \"b\", \"c\");\nList arr2 = Arrays.asList(1, 2, 3);\nList> zipped = zip(arr1, arr2);\n\nSystem.out.println(zipped); // Output: [[a, 1], [b, 2], [c, 3]]\n",
+ "extension": "java"
+ }
+ ]
+ },
+ {
+ "name": "Basics",
+ "snippets": [
+ {
+ "title": "Hello-World",
+ "description": "Prints Hello world in the console",
+ "author": "SarvariHarshitha",
+ "tags": [
+ "java",
+ "console",
+ "printing"
+ ],
+ "contributors": [],
+ "code": "// This is the main class of the Java program\npublic class Main {\n // The main method is the entry point of the program\n public static void main(String args[]) {\n // This statement prints \"Hello, World!\" to the console\n System.out.println(\"Hello, World!\");\n }\n}\n\n",
+ "extension": "java"
+ }
+ ]
+ },
+ {
+ "name": "Bit Manipulation",
+ "snippets": [
+ {
+ "title": "Bit Counting",
+ "description": "Counts the set bits in the binary representation of an integer",
+ "author": "Mcbencrafter",
+ "tags": [
+ "math",
+ "number",
+ "bits",
+ "bit-counting"
+ ],
+ "contributors": [],
+ "code": "public static int countBits(int number) {\n int bits = 0;\n \n while (number > 0) {\n bits += number & 1;\n number >>= 1;\n }\n\n return bits;\n}\n\n// Usage:\nint number = 5;\nSystem.out.println(countBits(5)); // 2 (101)\n",
+ "extension": "java"
+ },
+ {
+ "title": "Is Power Of Two",
+ "description": "Checks if a number is a power of two",
+ "author": "Mcbencrafter",
+ "tags": [
+ "math",
+ "number",
+ "bit",
+ "power-of-two"
+ ],
+ "contributors": [],
+ "code": "public static boolean isPowerOfTwo(int number) {\n return (number > 0) && ((number & (number - 1)) == 0);\n}\n\n// Usage:\nint number = 16;\nSystem.out.println(isPowerOfTwo(number)); // true (2^4)\n",
+ "extension": "java"
+ }
+ ]
+ },
+ {
+ "name": "Date Time",
+ "snippets": [
+ {
+ "title": "Date Time Formatting American",
+ "description": "Formats a timestamp to a human-readable date-time string in the format \"MM/dd/yyyy hh:mm:ss a\"",
+ "author": "Mcbencrafter",
+ "tags": [
+ "date",
+ "time",
+ "date-time",
+ "formatting",
+ "american"
+ ],
+ "contributors": [],
+ "code": "import java.time.Instant;\nimport java.time.ZoneId;\nimport java.time.format.DateTimeFormatter;\nimport java.util.concurrent.TimeUnit;\n\n// using the system default time zone\npublic static String formatDateTimeAmerican(long time, TimeUnit timeUnit) {\n return formatDateTimeAmerican(time, timeUnit, ZoneId.systemDefault());\n}\n\npublic static String formatDateTimeAmerican(long time, TimeUnit timeUnit, ZoneId timeZone) {\n return DateTimeFormatter.ofPattern(\"MM/dd/yyyy hh:mm:ss a\")\n .withZone(\n timeZone != null ? timeZone : ZoneId.systemDefault()\n )\n .format(Instant.ofEpochSecond(\n timeUnit.toSeconds(time)\n ));\n}\n\n// Usage:\nSystem.out.println(formatDateTimeAmerican(1735689599, TimeUnit.SECONDS)); // \"12/31/2024 | 11:59:59 PM\" for GMT+0000\nSystem.out.println(formatDateTimeAmerican(1735689599, TimeUnit.SECONDS, ZoneId.of(\"GMT+0000\"))); // \"12/31/2024 | 11:59:59 PM\"\n",
+ "extension": "java"
+ },
+ {
+ "title": "Date Time Formatting European",
+ "description": "Formats a timestamp to a human-readable date-time string in the format \"dd.MM.yyyy HH:mm:ss\"",
+ "author": "Mcbencrafter",
+ "tags": [
+ "date",
+ "time",
+ "date-time",
+ "formatting",
+ "european"
+ ],
+ "contributors": [],
+ "code": "import java.time.Instant;\nimport java.time.ZoneId;\nimport java.time.format.DateTimeFormatter;\nimport java.util.concurrent.TimeUnit;\n\n// using the system default time zone\npublic static String formatDateTimeEuropean(long time, TimeUnit timeUnit) {\n return formatDateTimeEuropean(time, timeUnit, ZoneId.systemDefault());\n}\n\npublic static String formatDateTimeEuropean(long time, TimeUnit timeUnit, ZoneId timeZone) {\n return DateTimeFormatter.ofPattern(\"dd.MM.yyyy HH:mm:ss\")\n .withZone(\n timeZone != null ? timeZone : ZoneId.systemDefault()\n )\n .format(Instant.ofEpochSecond(\n timeUnit.toSeconds(time)\n ));\n}\n\n// Usage:\nSystem.out.println(formatDateTimeEuropean(1735689599, TimeUnit.SECONDS)); // \"31.12.2024 | 23:59:59\" for GMT+0000\nSystem.out.println(formatDateTimeEuropean(1735689599, TimeUnit.SECONDS, ZoneId.of(\"GMT+0000\"))); // \"31.12.2024 | 23:59:59\"\n",
+ "extension": "java"
+ },
+ {
+ "title": "Duration Formatting Hours Minutes Seconds",
+ "description": "Converts a given time duration to a human-readable string in the format \"hh:mm(:ss)\"",
+ "author": "Mcbencrafter",
+ "tags": [
+ "time",
+ "formatting",
+ "hours",
+ "minutes",
+ "seconds"
+ ],
+ "contributors": [],
+ "code": "import java.util.concurrent.TimeUnit;\n \npublic static String formatDurationToHoursMinutesAndSeconds(int time, TimeUnit timeUnit, boolean showSeconds) {\n long totalSeconds = timeUnit.toSeconds(time);\n\n if (totalSeconds < 0)\n throw new IllegalArgumentException(\"Duration must be a non-negative value.\");\n\n // These variables can be directly used in the return statement,\n // but are kept as separate variables here for better readability.\n long hours = totalSeconds / 3600;\n long minutes = (totalSeconds % 3600) / 60;\n long seconds = totalSeconds % 60;\n\n if (showSeconds) {\n return String.format(\"%02d:%02d:%02d\", hours, minutes, seconds);\n } else {\n return String.format(\"%02d:%02d\", hours, minutes);\n }\n}\n\n// Usage:\nSystem.out.println(formatDurationToHoursMinutesAndSeconds(3810, TimeUnit.SECONDS, true)); // \"01:03:30\"\nSystem.out.println(formatDurationToHoursMinutesAndSeconds(3810, TimeUnit.SECONDS, false)); // \"01:03\"\n",
+ "extension": "java"
+ },
+ {
+ "title": "Duration Formatting Minutes Seconds",
+ "description": "Converts a given time duration to a human-readable string in the format \"mm:ss\"",
+ "author": "Mcbencrafter",
+ "tags": [
+ "time",
+ "formatting",
+ "minutes",
+ "seconds"
+ ],
+ "contributors": [],
+ "code": "import java.util.concurrent.TimeUnit;\n\npublic static String formatDurationToMinutesAndSeconds(int time, TimeUnit timeUnit) {\n long totalSeconds = timeUnit.toSeconds(time);\n\n if (totalSeconds < 0)\n throw new IllegalArgumentException(\"Duration must be a non-negative value.\");\n\n // These variables can be directly used in the return statement,\n // but are kept here as separate variables for better readability.\n long minutes = totalSeconds / 60;\n long seconds = totalSeconds % 60;\n\n return String.format(\"%02d:%02d\", minutes, seconds);\n}\n\n// Usage:\nSystem.out.println(formatDurationToMinutesAndSeconds(120, TimeUnit.SECONDS)); // \"02:00\"\nSystem.out.println(formatDurationToMinutesAndSeconds(75, TimeUnit.SECONDS)); // \"01:15\"\n",
+ "extension": "java"
+ }
+ ]
+ },
+ {
+ "name": "Math",
+ "snippets": [
+ {
+ "title": "Checksum",
+ "description": "Calculates the checksum of an int",
+ "author": "Mcbencrafter",
+ "tags": [
+ "math",
+ "number",
+ "checksum"
+ ],
+ "contributors": [],
+ "code": "public static int checksum(int number) {\n number = Math.abs(number);\n int sum = 0;\n\n while (number != 0) {\n sum += number % 10;\n number /= 10;\n }\n\n return sum;\n}\n\n// Usage:\nint number = 12345;\nSystem.out.println(checksum(number)); // 15 = 1+2+3+4+5\n",
+ "extension": "java"
+ },
+ {
+ "title": "Factorial",
+ "description": "Computes the factorial of a given number",
+ "author": "Mcbencrafter",
+ "tags": [
+ "math",
+ "number",
+ "factorial"
+ ],
+ "contributors": [],
+ "code": "import java.math.BigInteger;\n\npublic static BigInteger factorial(int number) {\n BigInteger result = BigInteger.ONE;\n\n for (int currentNumber = 1; currentNumber <= number; currentNumber++) {\n result = result.multiply(BigInteger.valueOf(currentNumber));\n }\n\n return result;\n}\n\n// Usage:\nint number = 6;\nSystem.out.println(factorial(number)); // 720 = 6*5*4*3*2\n",
+ "extension": "java"
+ },
+ {
+ "title": "Fibonacci",
+ "description": "Calculates the nth fibonacci number",
+ "author": "Mcbencrafter",
+ "tags": [
+ "math",
+ "number",
+ "fibonacci"
+ ],
+ "contributors": [],
+ "code": "public static int fibonacci(int number) {\n if (number <= 1) \n return number;\n \n return fibonacci(number - 1) + fibonacci(number - 2);\n}\n\n// Usage:\nint number = 5;\nSystem.out.println(fibonacci(number)) // 3 (0, 1, 1, 2, 3)\n",
+ "extension": "java"
+ },
+ {
+ "title": "Greatest Common Divisor",
+ "description": "Calculates the greatest common divisor (gcd) of two numbers",
+ "author": "Mcbencrafter",
+ "tags": [
+ "math",
+ "number",
+ "greatest-common-devisor",
+ "gcd",
+ "euclidean-algorithm"
+ ],
+ "contributors": [],
+ "code": "public static int gcd(int number1, int number2) {\n while (number2 != 0) {\n int remainder = number2;\n number2 = number1 % number2;\n number1 = remainder;\n }\n\n return number1;\n}\n\n// Usage:\nint a = 16;\nint b = 12;\nSystem.out.println(gcd(a, b)); // 4\n",
+ "extension": "java"
+ },
+ {
+ "title": "Least Common Multiple",
+ "description": "Calculates the least common multiple (lcm) of two numbers",
+ "author": "Mcbencrafter",
+ "tags": [
+ "math",
+ "number",
+ "least-common-multiple",
+ "lcm",
+ "euclidean-algorithm"
+ ],
+ "contributors": [],
+ "code": "public static int lcm(int number1, int number2) {\n int gcdNumber1 = number1;\n int gcdNumber2 = number2;\n \n while (gcdNumber2 != 0) {\n int remainder = gcdNumber2;\n gcdNumber2 = gcdNumber1 % gcdNumber2;\n gcdNumber1 = remainder;\n }\n \n return (number1 / gcdNumber1) * number2;\n}\n\n// Usage:\nint a = 16;\nint b = 12;\nSystem.out.println(lcm(a, b)); // 48\n",
+ "extension": "java"
+ },
+ {
+ "title": "Prime Check",
+ "description": "Checks if a number is a prime",
+ "author": "Mcbencrafter",
+ "tags": [
+ "math",
+ "number",
+ "prime"
+ ],
+ "contributors": [],
+ "code": "public static boolean isPrime(int number) {\n if (number <= 1) \n return false;\n\n if (number <= 3) \n return true;\n\n boolean prime = true;\n for (int divisor = 3; divisor < number; divisor++) {\n if (number % divisor != 0)\n continue;\n\n prime = false;\n break;\n }\n\n return prime;\n}\n\n// Usage:\nint number = 31;\nSystem.out.println(isPrime(number)); // true\n",
+ "extension": "java"
+ }
+ ]
+ },
+ {
+ "name": "String Manipulation",
+ "snippets": [
+ {
+ "title": "Ascii To String",
+ "description": "Converts a list of ascii numbers into a string",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "ascii",
+ "encoding",
+ "decode",
+ "conversion"
+ ],
+ "contributors": [],
+ "code": "import java.util.List;\n\npublic static String asciiToString(List asciiCodes) {\n StringBuilder text = new StringBuilder();\n\n for (int asciiCode : asciiCodes) {\n text.append((char) asciiCode);\n }\n\n return text.toString();\n}\n\n// Usage:\nSystem.out.println(asciiToString(List.of(104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100))); // \"hello world\"\n",
+ "extension": "java"
+ },
+ {
+ "title": "camelCase to snake_case",
+ "description": "Converts a camelCase string into snake_case",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "conversion",
+ "camel-case",
+ "snake-case"
+ ],
+ "contributors": [],
+ "code": "public static String camelToSnake(String camelCase) {\n return camelCase.replaceAll(\"([a-z])([A-Z])\", \"$1_$2\").toLowerCase();\n}\n\n// Usage:\nSystem.out.println(camelToSnake(\"helloWorld\")); // \"hello_world\"\n",
+ "extension": "java"
+ },
+ {
+ "title": "Capitalize Words",
+ "description": "Capitalizes the first letter of each word in a string",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "capitalize",
+ "words"
+ ],
+ "contributors": [],
+ "code": "public static String capitalizeWords(String text) {\n String[] words = text.split(\"(?<=\\\\S)(?=\\\\s+)|(?<=\\\\s+)(?=\\\\S)\"); // this is needed to preserve spaces (text.split(\" \") would remove multiple spaces)\n StringBuilder capitalizedText = new StringBuilder();\n \n for (String word : words) {\n if (word.trim().isEmpty()) {\n capitalizedText.append(word);\n continue;\n }\n capitalizedText.append(Character.toUpperCase(word.charAt(0)))\n .append(word.substring(1));\n }\n \n return capitalizedText.toString();\n}\n\n// Usage:\nSystem.out.println(capitalizeWords(\"hello world\")); // \"Hello World\"\n",
+ "extension": "java"
+ },
+ {
+ "title": "Check Anagram",
+ "description": "Checks if two strings are anagrams, meaning they contain the same characters ignoring order, spaces and case sensitivity",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "anagram",
+ "compare",
+ "arrays"
+ ],
+ "contributors": [],
+ "code": "import java.util.Arrays;\n\npublic static boolean isAnagram(String text1, String text2) {\n String text1Normalized = text1.replaceAll(\"\\\\s+\", \"\");\n String text2Normalized = text2.replaceAll(\"\\\\s+\", \"\");\n\n if (text1Normalized.length() != text2Normalized.length())\n return false;\n \n char[] text1Array = text1Normalized.toCharArray();\n char[] text2Array = text2Normalized.toCharArray();\n Arrays.sort(text1Array);\n Arrays.sort(text2Array);\n return Arrays.equals(text1Array, text2Array);\n}\n\n// Usage:\nSystem.out.println(isAnagram(\"listen\", \"silent\")); // true\nSystem.out.println(isAnagram(\"hello\", \"world\")); // false\n",
+ "extension": "java"
+ },
+ {
+ "title": "Check Palindrome",
+ "description": "Checks if a string reads the same backward as forward, ignoring whitespaces and case sensitivity",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "palindrome",
+ "compare",
+ "reverse"
+ ],
+ "contributors": [],
+ "code": "public static boolean isPalindrome(String text) {\n String cleanText = text.toLowerCase().replaceAll(\"\\\\s+\", \"\");\n \n return new StringBuilder(cleanText)\n .reverse()\n .toString()\n .equals(cleanText);\n}\n\n// Usage:\nSystem.out.println(isPalindrome(\"A man a plan a canal Panama\")); // true\n",
+ "extension": "java"
+ },
+ {
+ "title": "Count Character Frequency",
+ "description": "Counts the frequency of each character in a string",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "character",
+ "frequency",
+ "character-frequency"
+ ],
+ "contributors": [],
+ "code": "public static Map characterFrequency(String text, boolean countSpaces, boolean caseSensitive) {\n Map frequencyMap = new HashMap<>();\n\n for (char character : text.toCharArray()) {\n if (character == ' ' && !countSpaces)\n continue;\n\n if (!caseSensitive)\n character = Character.toLowerCase(character);\n\n frequencyMap.put(character, frequencyMap.getOrDefault(character, 0) + 1);\n }\n\n return frequencyMap;\n}\n\n// Usage:\nSystem.out.println(characterFrequency(\"hello world\", false, false)); // {r=1, d=1, e=1, w=1, h=1, l=3, o=2}\n",
+ "extension": "java"
+ },
+ {
+ "title": "Count Character Occurrences",
+ "description": "Counts the occurrences of the specified characters in a given string",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "characters",
+ "counter",
+ "occurence"
+ ],
+ "contributors": [],
+ "code": "import java.util.List;\n\npublic static int countCharacterOccurrences(String text, List characters) {\n int count = 0;\n \n for (char character : text.toCharArray()) {\n if (characters.indexOf(character) == -1)\n continue;\n \n count++;\n }\n \n return count;\n}\n\n// Usage:\nSystem.out.println(countCharacterOccurrences(\"hello world\", List.of('l', 'o'))); // 5\n",
+ "extension": "java"
+ },
+ {
+ "title": "Count Words",
+ "description": "Counts the number of words in a string",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "word",
+ "count"
+ ],
+ "contributors": [],
+ "code": "public static int countWords(String text) {\n return text.split(\"\\\\s+\").length;\n}\n\n// Usage:\nSystem.out.println(countWords(\"hello world\")); // 2\n",
+ "extension": "java"
+ },
+ {
+ "title": "Extract Text Between Delimiters",
+ "description": "Extracts a text between two given delimiters from a string",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "delimiters",
+ "start",
+ "end"
+ ],
+ "contributors": [],
+ "code": "public static String extractBetweenDelimiters(String text, String start, String end) {\n int startIndex = text.indexOf(start);\n int endIndex = text.indexOf(end, startIndex + start.length());\n \n if (startIndex == -1 || endIndex == -1)\n return \"\";\n \n return text.substring(startIndex + start.length(), endIndex);\n}\n\n// Usage:\nSystem.out.println(extractBetweenDelimiters(\"hello, world!\", \",\", \"!\")); // \" world\"\n",
+ "extension": "java"
+ },
+ {
+ "title": "Find Longest Word",
+ "description": "Returns the longest word in a string",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "length",
+ "words"
+ ],
+ "contributors": [],
+ "code": "public static String findLongestWord(String text) {\n String[] words = text.split(\"\\\\s+\");\n String longestWord = words[0];\n \n for (String word : words) {\n if (word.length() <= longestWord.length())\n continue;\n \n longestWord = word;\n }\n\n return longestWord;\n}\n\n// Usage:\nSystem.out.println(findLongestWord(\"hello world123\")); // \"world123\"\n",
+ "extension": "java"
+ },
+ {
+ "title": "Find Unique Characters",
+ "description": "Returns a set of unique characters from a string, with options to include spaces and control case sensitivity",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "unique",
+ "characters",
+ "case-sensitive"
+ ],
+ "contributors": [],
+ "code": "public static Set findUniqueCharacters(String text, boolean countSpaces, boolean caseSensitive) {\n Set uniqueCharacters = new TreeSet<>();\n \n for (char character : text.toCharArray()) {\n if (character == ' ' && !countSpaces)\n continue;\n if (!caseSensitive)\n character = Character.toLowerCase(character);\n uniqueCharacters.add(character);\n }\n \n return uniqueCharacters;\n}\n\n// Usage:\nSystem.out.println(findUniqueCharacters(\"hello world\", false, true)); // Output: [d, e, h, l, o, r, w]\n",
+ "extension": "java"
+ },
+ {
+ "title": "Mask Text",
+ "description": "Masks portions of a string, leaving specific parts at the beginning and end visible while replacing the rest with a specified character",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "mask",
+ "hide"
+ ],
+ "contributors": [],
+ "code": "public static String partialMask(String text, int maskLengthStart, int maskLengthEnd, char mask) \n if (text == null)\n return null;\n \n StringBuilder maskedText = new StringBuilder();\n maskedText.append(text, 0, maskLengthStart);\n \n for (int currentChar = maskLengthStart; currentChar < text.length(); currentChar++) {\n maskedText.append(mask);\n }\n maskedText.append(text, text.length() - maskLengthEnd, text.length());\n return maskedText.toString();\n}\n\n// Usage:\nSystem.out.println(partialMask(\"1234567890\", 4, 2, '*')); // \"1234****90\"\n",
+ "extension": "java"
+ },
+ {
+ "title": "Normalize Whitespace",
+ "description": "Replaces consecutive whitespaces with a single space",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "whitespace",
+ "normalize"
+ ],
+ "contributors": [],
+ "code": "public static String normalizeWhitespace(String text) {\n return text.replaceAll(\" {2,}\", \" \");\n}\n\n// Usage:\nSystem.out.println(normalizeWhitespace(\"hello world\")); // \"hello world\"\n",
+ "extension": "java"
+ },
+ {
+ "title": "Password Generator",
+ "description": "Generates a random string with specified length and character set, including options for letters, numbers, and special characters ",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "password",
+ "generator",
+ "security",
+ "random",
+ "token"
+ ],
+ "contributors": [],
+ "code": "public static String randomString(int length, boolean useLetters, boolean useNumbers, boolean useSpecialCharacters) {\n String characters = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n String numbers = \"0123456789\";\n String specialCharacters = \"!@#$%^&*()_+-=[]{}|;:,.<>?\";\n \n String allowedCharacters = \"\";\n \n if (useLetters)\n allowedCharacters += characters;\n\n if (useNumbers)\n allowedCharacters += numbers;\n\n if (useSpecialCharacters)\n allowedCharacters += specialCharacters;\n\n SecureRandom random = new SecureRandom();\n StringBuilder result = new StringBuilder(length);\n\n for (int i = 0; i < length; i++) {\n int index = random.nextInt(allowedCharacters.length());\n result.append(allowedCharacters.charAt(index));\n }\n\n return result.toString();\n}\n\n// Usage:\nSystem.out.println(randomString(10, true, true, false)); // Random string containing letters, numbers but no special characters with 10 characters\n",
+ "extension": "java"
+ },
+ {
+ "title": "Remove Punctuation",
+ "description": "Removes punctuation (, . !) from a string",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "punctuation",
+ "clean",
+ "normalization"
+ ],
+ "contributors": [],
+ "code": "public static String removePunctuation(String text) {\n return text.replaceAll(\"[,!.?;:]\", \"\");\n}\n\n// Usage:\nSystem.out.println(removePunctuation(\"hello, world!\")); // \"hello world\"\n",
+ "extension": "java"
+ },
+ {
+ "title": "Remove Special Characters",
+ "description": "Removes any character which is not alphabetic (A-Z, a-z) or numeric (0-9)",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "special-characters",
+ "clean",
+ "normalization"
+ ],
+ "contributors": [],
+ "code": "public static String removeSpecialCharacters(String text) {\n return text.replaceAll(\"[^a-zA-Z0-9]\", \"\");\n}\n\n// Usage:\nSystem.out.println(removeSpecialCharacters(\"hello, world!#%\")); // \"hello world\"\n",
+ "extension": "java"
+ },
+ {
+ "title": "Reverse Word Contents",
+ "description": "Reverses the characters of each word in a string while preserving word order",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "reverse",
+ "words",
+ "transformation",
+ "order"
+ ],
+ "contributors": [],
+ "code": "public static String reverseWords(String text) {\n String[] words = text.split(\"\\\\s+\"); \n StringBuilder reversedText = new StringBuilder();\n\n for (String word : words) {\n StringBuilder reversedWord = new StringBuilder(word).reverse();\n reversedText.append(reversedWord).append(\" \");\n }\n\n return reversedText.toString().trim();\n}\n\n// Usage:\nSystem.out.println(reverseWordContents(\"hello world\")); // \"olleh dlrow\"\n",
+ "extension": "java"
+ },
+ {
+ "title": "Reverse Word Order",
+ "description": "Reverses the order of words in a sentence while preserving the content of each word",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "reverse",
+ "words",
+ "transformation",
+ "sentence"
+ ],
+ "contributors": [],
+ "code": "public static String reverseWords(String text) {\n String[] words = text.split(\"\\\\s+\");\n StringBuilder reversedSentence = new StringBuilder();\n\n for (int currentWord = words.length - 1; currentWord >= 0; currentWord--) {\n reversedSentence.append(words[currentWord]).append(\" \");\n }\n\n return reversedSentence.toString().trim();\n}\n\n// Usage:\nSystem.out.println(reverseWords(\"hello world\")); // Output: world hello\n",
+ "extension": "java"
+ },
+ {
+ "title": "Slugify String",
+ "description": "Converts a string into a URL-friendly slug format",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "slug",
+ "slugify"
+ ],
+ "contributors": [],
+ "code": "public static String slugify(String text, String separator) {\n if (text == null)\n return \"\";\n\n // used to decompose accented characters to their base characters (e.g. \"é\" to \"e\")\n String normalizedString = Normalizer.normalize(text, Normalizer.Form.NFD);\n normalizedString = normalizedString.replaceAll(\"[\\\\p{InCombiningDiacriticalMarks}]\", \"\");\n\n String slug = normalizedString.trim()\n .toLowerCase()\n .replaceAll(\"\\\\s+\", separator)\n .replaceAll(\"[^a-z0-9\\\\-_\" + separator + \"]\", \"\")\n .replaceAll(\"_\", separator)\n .replaceAll(\"-\", separator)\n .replaceAll(separator + \"+\", separator)\n .replaceAll(separator + \"$\", \"\");\n\n return slug;\n}\n\n// Usage:\nSystem.out.println(slugify(\"Hello World-#123-é\", \"-\")); // \"hello-world-123-e\"\n",
+ "extension": "java"
+ },
+ {
+ "title": "snake_case to camelCase",
+ "description": "Converts a snake_case string into camelCase",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "conversion",
+ "camel-case",
+ "snake-case"
+ ],
+ "contributors": [],
+ "code": "import java.util.regex.Pattern;\n\npublic static String snakeToCamel(String snakeCase) {\n return Pattern.compile(\"(_)([a-z])\")\n .matcher(snakeCase)\n .replaceAll(match -> match.group(2).toUpperCase());\n}\n\n// Usage:\nSystem.out.println(snakeToCamel(\"hello_world\")); // \"helloWorld\"\n",
+ "extension": "java"
+ },
+ {
+ "title": "Spaces To Tabs",
+ "description": "Converts spaces into tabs",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "tab",
+ "space",
+ "conversion"
+ ],
+ "contributors": [],
+ "code": "public static String convertSpacesToTab(String text, int spacesPerTab) {\n return text.replaceAll(\" \".repeat(spacesPerTab), \"\\t\");\n}\n\n// Usage:\nSystem.out.println(convertSpacesToTab(\"hello world\", 4)); // Output: hello\\tworld\n",
+ "extension": "java"
+ },
+ {
+ "title": "String To Ascii",
+ "description": "Converts a string into ascii numbers",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "ascii",
+ "encoding",
+ "conversion"
+ ],
+ "contributors": [],
+ "code": "import java.util.ArrayList;\nimport java.util.List;\n\npublic static List stringToAscii(String text) {\n List asciiCodes = new ArrayList<>();\n\n for (char character : text.toCharArray()) {\n asciiCodes.add((int) character);\n }\n\n return asciiCodes;\n}\n\n// Usage:\nSystem.out.println(stringToAscii(\"hello world\")); // [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]\n",
+ "extension": "java"
+ },
+ {
+ "title": "String To camelCase",
+ "description": "Converts a string into camelCase",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "conversion",
+ "camel-case"
+ ],
+ "contributors": [],
+ "code": "public static String stringToCamelCase(String text) {\n String[] words = text.split(\"\\\\s+\");\n StringBuilder camelCase = new StringBuilder(\n words[0].substring(0, 1).toLowerCase() + words[0].substring(1)\n );\n\n for (int i = 1; i < words.length; i++) {\n camelCase.append(words[i].substring(0, 1).toUpperCase());\n camelCase.append(words[i].substring(1));\n }\n\n return camelCase.toString();\n}\n\n// Usage:\nSystem.out.println(stringToCamelCase(\"Hello world test\")); // \"helloWorldTest\"\n",
+ "extension": "java"
+ },
+ {
+ "title": "String To param-case",
+ "description": "Converts a string into param-case",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "conversion",
+ "param-case"
+ ],
+ "contributors": [],
+ "code": "public static String stringToParamCase(String text) {\n return text.toLowerCase().replaceAll(\"\\\\s+\", \"-\");\n}\n\n// Usage:\nSystem.out.println(stringToParamCase(\"Hello World 123\")); // \"hello-world-123\"\n",
+ "extension": "java"
+ },
+ {
+ "title": "String To PascalCase",
+ "description": "Converts a string into PascalCase",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "conversion",
+ "pascal-case"
+ ],
+ "contributors": [],
+ "code": "public static String stringToPascalCase(String text) {\n String[] words = text.split(\"\\\\s+\");\n StringBuilder pascalCase = new StringBuilder();\n\n for (String word : words) {\n pascalCase.append(word.substring(0, 1).toUpperCase());\n pascalCase.append(word.substring(1).toLowerCase());\n }\n\n return pascalCase.toString();\n}\n\n// Usage:\nSystem.out.println(stringToPascalCase(\"hello world\")); // \"HelloWorld\"\n",
+ "extension": "java"
+ },
+ {
+ "title": "String To snake_case",
+ "description": "Converts a string into snake_case",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "conversion",
+ "snake-case"
+ ],
+ "contributors": [],
+ "code": "public static String stringToSnakeCase(String text) {\n return text.toLowerCase().replaceAll(\"\\\\s+\", \"_\");\n}\n\n// Usage:\nSystem.out.println(stringToSnakeCase(\"Hello World 123\")); // \"hello_world_123\"\n",
+ "extension": "java"
+ },
+ {
+ "title": "String To Titlecase",
+ "description": "Converts a string into Title Case, where the first letter of each word is capitalized and the remaining letters are lowercase",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "conversion",
+ "title-case"
+ ],
+ "contributors": [],
+ "code": "public static String convertToTitleCase(String text) {\n String[] words = text.split(\"(?<=\\\\S)(?=\\\\s+)|(?<=\\\\s+)(?=\\\\S)\"); // this is needed to preserve spaces (text.split(\" \") would remove multiple spaces)\n StringBuilder capitalizedText = new StringBuilder();\n\n for (String word : words) {\n if (word.trim().isEmpty()) {\n capitalizedText.append(word);\n continue;\n }\n\n capitalizedText.append(Character.toUpperCase(word.charAt(0)))\n .append(word.substring(1).toLowerCase());\n }\n\n return capitalizedText.toString().trim();\n}\n\n// Usage:\nSystem.out.println(convertToTitleCase(\"heLlo wOrld\")); // \"Hello World\"\n",
+ "extension": "java"
+ },
+ {
+ "title": "String To Unicode",
+ "description": "Converts characters of a string into their unicode representation",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "unicode",
+ "encoding",
+ "conversion"
+ ],
+ "contributors": [],
+ "code": "public static String stringToUnicode(String text) {\n StringBuilder unicodeText = new StringBuilder();\n\n for (char character : text.toCharArray()) {\n unicodeText.append(String.format(\"\\\\u%04x\", (int) character));\n }\n\n return unicodeText.toString();\n}\n\n// Usage:\nSystem.out.println(stringToUnicode(\"hello world\")); // \\u0068\\u0065\\u006C\\u006C\\u006F\\u0020\\u0077\\u006F\\u0072\\u006C\\u0064\n",
+ "extension": "java"
+ },
+ {
+ "title": "Tabs To Spaces",
+ "description": "Converts tabs into spaces",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "tab",
+ "space",
+ "conversion"
+ ],
+ "contributors": [],
+ "code": "public static String convertTabToSpace(String text, int spacesPerTab) {\n return text.replaceAll(\"\\t\", \" \".repeat(spacesPerTab));\n}\n\n// Usage:\nSystem.out.println(convertTabToSpace(\"hello\\tworld\", 2)); // \"hello world\"\n",
+ "extension": "java"
+ },
+ {
+ "title": "Truncate String",
+ "description": "Truncates a string after a specified length (can also be used for hiding information)",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "truncate",
+ "mask",
+ "hide"
+ ],
+ "contributors": [],
+ "code": "public static String truncate(String text, int length, String suffix) {\n if (text.length() <= length)\n return text;\n \n return text.substring(0, length).trim() + (suffix != null ? suffix : \"\");\n}\n\n// Usage:\nSystem.out.println(truncate(\"hello world\", 5, \"...\")); // \"hello...\"\n",
+ "extension": "java"
+ },
+ {
+ "title": "Unicode To String",
+ "description": "Converts a unicode String into its normal representation",
+ "author": "Mcbencrafter",
+ "tags": [
+ "string",
+ "unicode",
+ "encoding",
+ "decoding",
+ "conversion"
+ ],
+ "contributors": [],
+ "code": "public static String unicodeToString(String unicode) {\n StringBuilder string = new StringBuilder();\n String[] hex = unicode.split(\"\\\\\\\\u\");\n\n for (int symbol = 1; symbol < hex.length; symbol++) {\n int data = Integer.parseInt(hex[symbol], 16);\n string.append((char) data);\n }\n\n return string.toString();\n}\n\n// Usage:\nSystem.out.println(unicodeToString(\"\\\\u0068\\\\u0065\\\\u006c\\\\u006c\\\\u006f\\\\u0020\\\\u0077\\\\u006f\\\\u0072\\\\u006c\\\\u0064\")); // \"hello world\"\n",
+ "extension": "java"
+ }
+ ]
+ }
+]
\ No newline at end of file
diff --git a/backend/data/consolidated/javascript--react.json b/backend/data/consolidated/javascript--react.json
index 6a058ea9..5e1df433 100644
--- a/backend/data/consolidated/javascript--react.json
+++ b/backend/data/consolidated/javascript--react.json
@@ -1,16 +1,19 @@
[
- {
- "name": "Basics",
- "snippets": [
- {
- "title": "Hello, World!",
- "description": "Show Hello World on the page.",
- "author": "ACR1209",
- "tags": ["printing", "hello-world"],
- "contributors": [],
- "code": "import React from 'react';\nimport ReactDOM from 'react-dom';\n\nconst App = () => {\n return (\n \n
Hello, World!
\n
\n );\n};\n\nReactDOM.render(, document.getElementById('root'));\n",
- "extension": "tsx"
- }
- ]
- }
-]
+ {
+ "name": "Basics",
+ "snippets": [
+ {
+ "title": "Hello, World!",
+ "description": "Show Hello World on the page.",
+ "author": "ACR1209",
+ "tags": [
+ "printing",
+ "hello-world"
+ ],
+ "contributors": [],
+ "code": "import React from 'react';\nimport ReactDOM from 'react-dom';\n\nconst App = () => {\n return (\n \n
Hello, World!
\n
\n );\n};\n\nReactDOM.render(, document.getElementById('root'));\n",
+ "extension": "tsx"
+ }
+ ]
+ }
+]
\ No newline at end of file
diff --git a/backend/data/consolidated/javascript.json b/backend/data/consolidated/javascript.json
index d8f9e740..95f42b30 100644
--- a/backend/data/consolidated/javascript.json
+++ b/backend/data/consolidated/javascript.json
@@ -1,822 +1,1120 @@
[
- {
- "name": "Array Manipulation",
- "snippets": [
- {
- "title": "Compare Arrays",
- "description": "Deeply compares two arrays to check if they are equal to each other (supports nested arrays and objects).",
- "author": "KCSquid",
- "tags": ["array", "object", "compare", "equal"],
- "contributors": [],
- "code": "const compareArrays = (a, b) => {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;\n return a.every((v, i) => \n Array.isArray(v) && Array.isArray(b[i]) ? compareArrays(v, b[i]) :\n typeof v === \"object\" && typeof b[i] === \"object\" ? compareObjects(v, b[i]) :\n v === b[i]\n );\n};\n\nconst compareObjects = (a, b) => {\n if (typeof a !== \"object\" || typeof b !== \"object\" || Object.keys(a).length !== Object.keys(b).length) return false;\n return Object.keys(a).every(k => \n Array.isArray(a[k]) && Array.isArray(b[k]) ? compareArrays(a[k], b[k]) :\n typeof a[k] === \"object\" && typeof b[k] === \"object\" ? compareObjects(a[k], b[k]) :\n a[k] === b[k]\n );\n};\n\n// Usage:\ncompareArrays([1, 2, 3], [1, 2, 3]); // Returns: true\ncompareArrays([1, 2, 3], [3, 2, 1]); // Returns: false\ncompareArrays([{a:1}], [{a:1}]); // Returns: true\ncompareArrays([{a:1}], null); // Returns: false\n",
- "extension": "js"
- },
- {
- "title": "Partition Array",
- "description": "Splits an array into two arrays based on a callback function.",
- "author": "Swaraj-Singh-30",
- "tags": ["array", "partition", "reduce"],
- "contributors": [],
- "code": "const partition = (arr, callback) =>\n arr.reduce(\n ([pass, fail], elem) => (callback(elem) ? [[...pass, elem], fail] : [pass, [...fail, elem]]),\n [[], []]\n );\n\n// Usage:\nconst numbers = [1, 2, 3, 4, 5, 6];\nconst isEven = (n) => n % 2 === 0;\npartition(numbers, isEven); // Returns: [[2, 4, 6], [1, 3, 5]]\n",
- "extension": "js"
- },
- {
- "title": "Remove Duplicates",
- "description": "Removes duplicate values from an array.",
- "author": "technoph1le",
- "tags": ["array", "deduplicate"],
- "contributors": [],
- "code": "const removeDuplicates = (arr) => [...new Set(arr)];\n\n// Usage:\nconst numbers = [1, 2, 2, 3, 4, 4, 5];\nremoveDuplicates(numbers); // Returns: [1, 2, 3, 4, 5]\n",
- "extension": "js"
- },
- {
- "title": "Remove Falsy Values",
- "description": "Removes falsy values from an array.",
- "author": "mubasshir",
- "tags": ["array", "falsy", "filter"],
- "contributors": [],
- "code": "const removeFalsy = (arr) => arr.filter(Boolean);\n\n// Usage:\nconst array = [0, 1, false, 2, \"\", 3, null];\nremoveFalsy(array); // Returns: [1, 2, 3]\n",
- "extension": "js"
- },
- {
- "title": "Shuffle Array",
- "description": "Shuffles an Array.",
- "author": "loxt-nixo",
- "tags": ["array", "shuffle"],
- "contributors": [],
- "code": "function shuffleArray(array) {\n for (let i = array.length - 1; i >= 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n [array[i], array[j]] = [array[j], array[i]];\n }\n}\n\n// Usage:\nconst array = [1, 2, 3, 4, 5];\nshuffleArray(array); // Shuffles `array` in place\n",
- "extension": "js"
- },
- {
- "title": "Zip Arrays",
- "description": "Combines two arrays by pairing corresponding elements from each array.",
- "author": "Swaraj-Singh-30",
- "tags": ["array", "map"],
- "contributors": [],
- "code": "const zip = (arr1, arr2) => arr1.map((value, index) => [value, arr2[index]]);\n\n// Usage:\nconst arr1 = ['a', 'b', 'c'];\nconst arr2 = [1, 2, 3];\nconsole.log(zip(arr1, arr2)); // Output: [['a', 1], ['b', 2], ['c', 3]]\n",
- "extension": "js"
- }
- ]
- },
- {
- "name": "Basics",
- "snippets": [
- {
- "title": "Hello, World!",
- "description": "Prints Hello, World! to the terminal.",
- "author": "James-Beans",
- "tags": ["printing", "hello-world"],
- "contributors": [],
- "code": "console.log(\"Hello, World!\"); // Prints Hello, World! to the console\n",
- "extension": "js"
- }
- ]
- },
- {
- "name": "Color Manipulation",
- "snippets": [
- {
- "title": "Hex to RGB Color",
- "description": "Converts hexadecimal color code to RGB color values.",
- "author": "pvictordev",
- "tags": ["color", "conversion"],
- "contributors": [],
- "code": "function hexToRgb(hex) {\n let sanitizedHex = hex.startsWith(\"#\") ? hex.slice(1) : hex;\n\n if (sanitizedHex.length === 3) {\n sanitizedHex = [...sanitizedHex].map((char) => char + char).join(\"\");\n }\n\n const bigint = parseInt(sanitizedHex, 16);\n\n return {\n r: (bigint >> 16) & 0xff, \n g: (bigint >> 8) & 0xff, \n b: bigint & 0xff, \n };\n}\n\n// Usage:\nconsole.log(hexToRgb(\"#ff5733\")); // { r: 255, g: 87, b: 51 }\nconsole.log(hexToRgb(\"#ffff\")); // { r: 0, g: 255, b: 255 }\n",
- "extension": "js"
- },
- {
- "title": "HSL to RGB Color",
- "description": "Converts HSL color values to RGB color values.",
- "author": "pvictordev",
- "tags": ["color", "conversion"],
- "contributors": [],
- "code": "function hslToRgb(h, s, l) {\n s /= 100;\n l /= 100;\n const c = (1 - Math.abs(2 * l - 1)) * s;\n const x = c * (1 - Math.abs((h / 60) % 2 - 1));\n const m = l - c / 2;\n\n const [r, g, b] = \n h < 60 ? [c, x, 0] :\n h < 120 ? [x, c, 0] :\n h < 180 ? [0, c, x] :\n h < 240 ? [0, x, c] :\n h < 300 ? [x, 0, c] :\n [c, 0, x];\n\n return {\n r: Math.round((r + m) * 255),\n g: Math.round((g + m) * 255),\n b: Math.round((b + m) * 255),\n };\n}\n\n// Usage:\nconsole.log(hslToRgb(14, 100, 60)); // { r: 255, g: 87, b: 51 }\nconsole.log(hslToRgb(0, 0, 100)); // { r: 255, g: 255, b: 255 }\n",
- "extension": "js"
- },
- {
- "title": "RGB to Hex Color",
- "description": "Converts RGB color values to hexadecimal color code.",
- "author": "jjcantu",
- "tags": ["color", "conversion"],
- "contributors": [],
- "code": "function rgbToHex(r, g, b) {\n const toHex = (n) => {\n const hex = n.toString(16);\n return hex.length === 1 ? \"0\" + hex : hex;\n };\n\n return \"#\" + toHex(r) + toHex(g) + toHex(b);\n}\n\n// Usage:\nconsole.log(rgbToHex(255, 128, 0)); // Output: \"#ff8000\"\nconsole.log(rgbToHex(0, 255, 0)); // Output: \"#00ff00\"\n",
- "extension": "js"
- },
- {
- "title": "RGB to HSL Color",
- "description": "Converts RGB color values to HSL color values.",
- "author": "pvictordev",
- "tags": ["color", "conversion"],
- "contributors": [],
- "code": "function rgbToHsl(r, g, b) {\n [r, g, b] = [r, g, b].map((v) => v / 255);\n\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n const delta = max - min;\n\n const l = (max + min) / 2;\n\n if (delta === 0) return { h: 0, s: 0, l: Math.round(l * 100) };\n\n const s = l > 0.5 ? delta / (2 - max - min) : delta / (max + min);\n\n const h = \n max === r ? ((g - b) / delta + (g < b ? 6 : 0)) :\n max === g ? (b - r) / delta + 2 :\n (r - g) / delta + 4;\n\n return {\n h: Math.round(h * 60), \n s: Math.round(s * 100),\n l: Math.round(l * 100), \n };\n}\n\n// Usage:\nconsole.log(rgbToHsl(255, 87, 51)); // { h: 14, s: 100, l: 60 }\nconsole.log(rgbToHsl(255, 255, 255)); // { h: 0, s: 0, l: 100 }\n",
- "extension": "js"
- }
- ]
- },
- {
- "name": "Date And Time",
- "snippets": [
- {
- "title": "Check Leap Year",
- "description": "Determines if a given year is a leap year.",
- "author": "axorax",
- "tags": ["date", "leap-year"],
- "contributors": [],
- "code": "const isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n\n// Usage:\nisLeapYear(2024); // Returns: true\nisLeapYear(2023); // Returns: false\n",
- "extension": "js"
- },
- {
- "title": "Convert to Unix Timestamp",
- "description": "Converts a date to a Unix timestamp in seconds.",
- "author": "Yugveer06",
- "tags": ["date", "unix", "timestamp"],
- "contributors": [],
- "code": "function convertToUnixSeconds(input) {\n if (typeof input === 'string') {\n if (!input.trim()) {\n throw new Error('Date string cannot be empty or whitespace');\n }\n } else if (!input) {\n throw new Error('Input is required');\n }\n\n let date;\n\n if (typeof input === 'string') {\n date = new Date(input);\n } else if (input instanceof Date) {\n date = input;\n } else {\n throw new Error('Input must be a valid date string or Date object');\n }\n\n if (isNaN(date.getTime())) {\n throw new Error('Invalid date provided');\n }\n\n return Math.floor(date.getTime() / 1000);\n}\n\n// Usage:\nconvertToUnixSeconds('2025-01-01T12:00:00Z'); // Returns: 1735732800\nconvertToUnixSeconds(new Date('2025-01-01T12:00:00Z')); // Returns: 1735732800\nconvertToUnixSeconds(new Date()); // Returns: Current Unix timestamp in seconds\n",
- "extension": "js"
- },
- {
- "title": "Format Date",
- "description": "Formats a date in 'YYYY-MM-DD' format.",
- "author": "technoph1le",
- "tags": ["date", "format"],
- "contributors": [],
- "code": "const formatDate = (date) => date.toISOString().split('T')[0];\n\n// Usage:\nformatDate(new Date(2024, 11, 10)); // Returns: '2024-12-10'\n",
- "extension": "js"
- },
- {
- "title": "Get Day of the Year",
- "description": "Calculates the day of the year (1-365 or 1-366 for leap years) for a given date.",
- "author": "axorax",
- "tags": ["date", "day-of-year"],
- "contributors": [],
- "code": "const getDayOfYear = (date) => {\n const startOfYear = new Date(date.getFullYear(), 0, 0);\n const diff = date - startOfYear + (startOfYear.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000;\n return Math.floor(diff / (1000 * 60 * 60 * 24));\n};\n\n// Usage:\ngetDayOfYear(new Date('2024-12-31')) // Returns: 366 (Leap year)\n",
- "extension": "js"
- },
- {
- "title": "Get Days in Month",
- "description": "Calculates the number of days in a specific month of a given year.",
- "author": "axorax",
- "tags": ["date", "days-in-month"],
- "contributors": [],
- "code": "const getDaysInMonth = (year, month) => new Date(year, month + 1, 0).getDate();\n\n// Usage:\ngetDaysInMonth(2024, 1); // Returns: 29 (February in a leap year)\ngetDaysInMonth(2023, 1); // Returns: 28\n",
- "extension": "js"
- },
- {
- "title": "Get Time Difference",
- "description": "Calculates the time difference in days between two dates.",
- "author": "technoph1le",
- "tags": ["date", "time-difference"],
- "contributors": [],
- "code": "const getTimeDifference = (date1, date2) => {\n const diff = Math.abs(date2 - date1);\n return Math.ceil(diff / (1000 * 60 * 60 * 24));\n};\n\n// Usage:\nconst date1 = new Date('2024-01-01');\nconst date2 = new Date('2024-12-31');\ngetTimeDifference(date1, date2); // Returns: 365\n",
- "extension": "js"
- },
- {
- "title": "Relative Time Formatter",
- "description": "Displays how long ago a date occurred or how far in the future a date is.",
- "author": "Yugveer06",
- "tags": ["date", "time", "relative", "future", "past"],
- "contributors": [],
- "code": "const getRelativeTime = (date) => {\n const now = Date.now();\n const diff = date.getTime() - now;\n const seconds = Math.abs(Math.floor(diff / 1000));\n const minutes = Math.abs(Math.floor(seconds / 60));\n const hours = Math.abs(Math.floor(minutes / 60));\n const days = Math.abs(Math.floor(hours / 24));\n const years = Math.abs(Math.floor(days / 365));\n\n if (Math.abs(diff) < 1000) return 'just now';\n\n const isFuture = diff > 0;\n\n if (years > 0) return `${isFuture ? 'in ' : ''}${years} ${years === 1 ? 'year' : 'years'}${isFuture ? '' : ' ago'}`;\n if (days > 0) return `${isFuture ? 'in ' : ''}${days} ${days === 1 ? 'day' : 'days'}${isFuture ? '' : ' ago'}`;\n if (hours > 0) return `${isFuture ? 'in ' : ''}${hours} ${hours === 1 ? 'hour' : 'hours'}${isFuture ? '' : ' ago'}`;\n if (minutes > 0) return `${isFuture ? 'in ' : ''}${minutes} ${minutes === 1 ? 'minute' : 'minutes'}${isFuture ? '' : ' ago'}`;\n\n return `${isFuture ? 'in ' : ''}${seconds} ${seconds === 1 ? 'second' : 'seconds'}${isFuture ? '' : ' ago'}`;\n}\n\n// Usage:\nconst pastDate = new Date('2021-12-29 13:00:00');\nconst futureDate = new Date('2099-12-29 13:00:00');\ngetRelativeTime(pastDate); // x years ago\ngetRelativeTime(new Date()); // just now\ngetRelativeTime(futureDate); // in x years\n",
- "extension": "js"
- },
- {
- "title": "Start of the Day",
- "description": "Returns the start of the day (midnight) for a given date.",
- "author": "axorax",
- "tags": ["date", "start-of-day"],
- "contributors": [],
- "code": "const startOfDay = (date) => new Date(date.setHours(0, 0, 0, 0));\n\n// Usage:\nconst today = new Date();\nstartOfDay(today); // Returns: Date object for midnight\n",
- "extension": "js"
- }
- ]
- },
- {
- "name": "Dom Manipulation",
- "snippets": [
- {
- "title": "Change Element Style",
- "description": "Changes the inline style of an element.",
- "author": "axorax",
- "tags": ["dom", "style"],
- "contributors": [],
- "code": "const changeElementStyle = (element, styleObj) => {\n Object.entries(styleObj).forEach(([property, value]) => {\n element.style[property] = value;\n });\n};\n\n// Usage:\nconst element = document.querySelector('.my-element');\nchangeElementStyle(element, { color: 'red', backgroundColor: 'yellow' });\n",
- "extension": "js"
- },
- {
- "title": "Remove Element",
- "description": "Removes a specified element from the DOM.",
- "author": "axorax",
- "tags": ["dom", "remove"],
- "contributors": [],
- "code": "const removeElement = (element) => {\n if (element && element.parentNode) {\n element.parentNode.removeChild(element);\n }\n};\n\n// Usage:\nconst element = document.querySelector('.my-element');\nremoveElement(element);\n",
- "extension": "js"
- }
- ]
- },
- {
- "name": "Function Utilities",
- "snippets": [
- {
- "title": "Compose Functions",
- "description": "Composes multiple functions into a single function, where the output of one function becomes the input of the next.",
- "author": "axorax",
- "tags": ["function", "compose"],
- "contributors": [],
- "code": "const compose = (...funcs) => (initialValue) => {\n return funcs.reduce((acc, func) => func(acc), initialValue);\n};\n\n// Usage:\nconst add2 = (x) => x + 2;\nconst multiply3 = (x) => x * 3;\nconst composed = compose(multiply3, add2);\ncomposed(5); // Returns: 17 ((5 * 3) + 2)\n",
- "extension": "js"
- },
- {
- "title": "Curry Function",
- "description": "Transforms a function into its curried form.",
- "author": "axorax",
- "tags": ["curry", "function"],
- "contributors": [],
- "code": "const curry = (func) => {\n const curried = (...args) => {\n if (args.length >= func.length) {\n return func(...args);\n }\n return (...nextArgs) => curried(...args, ...nextArgs);\n };\n return curried;\n};\n\n// Usage:\nconst add = (a, b, c) => a + b + c;\nconst curriedAdd = curry(add);\ncurriedAdd(1)(2)(3); // Returns: 6\ncurriedAdd(1, 2)(3); // Returns: 6\n",
- "extension": "js"
- },
- {
- "title": "Debounce Function",
- "description": "Delays a function execution until after a specified time.",
- "author": "technoph1le",
- "tags": ["debounce", "performance"],
- "contributors": [],
- "code": "const debounce = (func, delay) => {\n let timeout;\n\n return (...args) => {\n clearTimeout(timeout);\n timeout = setTimeout(() => func(...args), delay);\n };\n};\n\n// Usage:\nwindow.addEventListener(\n 'resize',\n debounce(() => console.log('Resized!'), 500), // Will only output after resizing has stopped for 500ms\n);\n",
- "extension": "js"
- },
- {
- "title": "Get Contrast Color",
- "description": "Returns either black or white text color based on the brightness of the provided hex color.",
- "author": "yaya12085",
- "tags": ["color", "hex", "contrast", "brightness"],
- "contributors": [],
- "code": "const getContrastColor = (hexColor) => {\n // Expand short hex color to full format\n if (hexColor.length === 4) {\n hexColor = `#${hexColor[1]}${hexColor[1]}${hexColor[2]}${hexColor[2]}${hexColor[3]}${hexColor[3]}`;\n }\n const r = parseInt(hexColor.slice(1, 3), 16);\n const g = parseInt(hexColor.slice(3, 5), 16);\n const b = parseInt(hexColor.slice(5, 7), 16);\n const brightness = (r * 299 + g * 587 + b * 114) / 1000;\n return brightness >= 128 ? \"#000000\" : \"#FFFFFF\";\n};\n\n// Usage:\ngetContrastColor('#fff'); // Returns: #000000 (black)\ngetContrastColor('#123456'); // Returns: #FFFFFF (white)\ngetContrastColor('#ff6347'); // Returns: #000000 (black)\ngetContrastColor('#f4f'); // Returns: #000000 (black)\n",
- "extension": "js"
- },
- {
- "title": "Memoize Function",
- "description": "Caches the result of a function based on its arguments to improve performance.",
- "author": "axorax",
- "tags": ["memoization", "optimization"],
- "contributors": [],
- "code": "const memoize = (func) => {\n const cache = new Map();\n return (...args) => {\n const key = JSON.stringify(args);\n if (cache.has(key)) {\n return cache.get(key);\n }\n const result = func(...args);\n cache.set(key, result);\n return result;\n };\n};\n\n// Usage:\nconst factorial = memoize((n) => (n <= 1 ? 1 : n * factorial(n - 1)));\nfactorial(5); // Returns: 120\nfactorial(5); // Returns: 120 (retrieved from cache)\n",
- "extension": "js"
- },
- {
- "title": "Once Function",
- "description": "Ensures a function is only called once.",
- "author": "axorax",
- "tags": ["function", "once"],
- "contributors": [],
- "code": "const once = (func) => {\n let called = false;\n return (...args) => {\n if (!called) {\n called = true;\n return func(...args);\n }\n };\n};\n\n// Usage:\nconst initialize = once(() => console.log('Initialized!'));\ninitialize(); // Output: Initialized!\ninitialize(); // No output\n",
- "extension": "js"
- },
- {
- "title": "Rate Limit Function",
- "description": "Limits how often a function can be executed within a given time window.",
- "author": "axorax",
- "tags": ["function", "rate-limiting"],
- "contributors": [],
- "code": "const rateLimit = (func, limit, timeWindow) => {\n let queue = [];\n setInterval(() => {\n if (queue.length) {\n const next = queue.shift();\n func(...next.args);\n }\n }, timeWindow);\n return (...args) => {\n if (queue.length < limit) {\n queue.push({ args });\n }\n };\n};\n\n// Usage:\nconst fetchData = () => console.log('Fetching data...');\nconst rateLimitedFetch = rateLimit(fetchData, 2, 1000);\nsetInterval(() => rateLimitedFetch(), 200); // Limits fetchData calls to twice a seconds\n",
- "extension": "js"
- },
- {
- "title": "Repeat Function Invocation",
- "description": "Invokes a function a specified number of times.",
- "author": "technoph1le",
- "tags": ["function", "repeat"],
- "contributors": [],
- "code": "const times = (func, n) => {\n Array.from(Array(n)).forEach(() => {\n func();\n });\n};\n\n// Usage:\nconst randomFunction = () => console.log('Function called!');\ntimes(randomFunction, 3); // Logs 'Function called!' three times\n",
- "extension": "js"
- },
- {
- "title": "Sleep Function",
- "description": "Waits for a specified amount of milliseconds before resolving.",
- "author": "0xHouss",
- "tags": ["javascript", "sleep", "delay", "utility", "promises"],
- "contributors": [],
- "code": "const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\n// Usage:\nconsole.log('Hello');\nawait sleep(2000); // Waits for 2 seconds\nconsole.log('World!');\n",
- "extension": "js"
- },
- {
- "title": "Throttle Function",
- "description": "Ensures a function is only called at most once in a specified time interval. Useful for optimizing events like scrolling or resizing.",
- "author": "WizardOfDigits",
- "tags": ["throttle", "performance", "optimization"],
- "contributors": [],
- "code": "const throttle = (func, limit) => {\n let inThrottle;\n return (...args) => {\n if (!inThrottle) {\n func(...args);\n inThrottle = true;\n setTimeout(() => (inThrottle = false), limit);\n }\n };\n};\n\n// Usage:\n// Ensures the function can only be called once every 1000 milliseconds\nconst logScroll = throttle(() => console.log(\"Scroll event triggered\"), 1000);\n\n// Attach to scroll event\nwindow.addEventListener(\"scroll\", logScroll);\n",
- "extension": "js"
- }
- ]
- },
- {
- "name": "Local Storage",
- "snippets": [
- {
- "title": "Add Item to localStorage",
- "description": "Stores a value in localStorage under the given key.",
- "author": "technoph1le",
- "tags": ["localStorage", "storage"],
- "contributors": [],
- "code": "const addToLocalStorage = (key, value) => {\n localStorage.setItem(key, JSON.stringify(value));\n};\n\n// Usage:\naddToLocalStorage('user', { name: 'John', age: 30 });\n",
- "extension": "js"
- },
- {
- "title": "Check if Item Exists in localStorage",
- "description": "Checks if a specific item exists in localStorage.",
- "author": "axorax",
- "tags": ["localStorage", "storage"],
- "contributors": [],
- "code": "const isItemInLocalStorage = (key) => {\n return localStorage.getItem(key) !== null;\n};\n\n// Usage:\nconsole.log(isItemInLocalStorage('user')); // Output: true or false\n",
- "extension": "js"
- },
- {
- "title": "Retrieve Item from localStorage",
- "description": "Retrieves a value from localStorage by key and parses it.",
- "author": "technoph1le",
- "tags": ["localStorage", "storage"],
- "contributors": [],
- "code": "const getFromLocalStorage = (key) => {\n const item = localStorage.getItem(key);\n return item ? JSON.parse(item) : null;\n};\n\n// Usage:\ngetFromLocalStorage('user'); // Returns: { name: 'John', age: 30 }\n",
- "extension": "js"
- }
- ]
- },
- {
- "name": "Mathematical Functions",
- "snippets": [
- {
- "title": "Combinations",
- "description": "Calculates the number of combinations (denoted as C(n,r) or \"n choose r\"), which determines how many ways you can select r items from n items without considering the order.",
- "author": "JanluOfficial",
- "tags": ["math", "number-theory", "algebra"],
- "contributors": [],
- "code": "function combinations(n, r) {\n if (n < 0 || r < 0 || n < r) {\n throw new Error('Invalid input: n and r must be non-negative and n must be greater than or equal to r.');\n }\n\n function factorial(x) {\n if (x === 0 || x === 1) return 1;\n let result = 1;\n for (let i = 2; i <= x; i++) {\n result *= i;\n }\n return result;\n }\n\n const numerator = factorial(n);\n const denominator = factorial(r) * factorial(n - r);\n return numerator / denominator;\n}\n\n// Usage:\ncombinations(24,22); // Returns: 276\ncombinations(5,3); // Returns: 10\n",
- "extension": "js"
- },
- {
- "title": "Cross Product",
- "description": "Computes the cross product of two 3D vectors, which results in a vector perpendicular to both.",
- "author": "JanluOfficial",
- "tags": ["math", "vector-algebra"],
- "contributors": [],
- "code": "function crossProduct(a, b) {\n if (a.length !== 3 || b.length !== 3) {\n throw new Error('Vectors must be 3-dimensional');\n }\n\n return [\n a[1] * b[2] - a[2] * b[1],\n a[2] * b[0] - a[0] * b[2],\n a[0] * b[1] - a[1] * b[0]\n ];\n}\n\n// Usage:\ncrossProduct([1, 2, 3], [4, 5, 6]); // Returns: [-3, 6, -3] \n",
- "extension": "js"
- },
- {
- "title": "Dot Product",
- "description": "Computes the dot product of two vectors, which is the sum of the products of corresponding elements.",
- "author": "JanluOfficial",
- "tags": ["math", "vector-algebra"],
- "contributors": [],
- "code": "function dotProduct(a, b) {\n if (a.length !== b.length) {\n throw new Error('Vectors must be of the same length');\n }\n\n return a.reduce((sum, value, index) => sum + value * b[index], 0);\n}\n\n// Usage:\ndotProduct([1, 2, 3], [4, 5, 6]); // Returns: 32\n",
- "extension": "js"
- },
- {
- "title": "Error function",
- "description": "Computes the error function (erf(x)) for a given input x, which is a mathematical function used frequently in probability, statistics, and partial differential equations.",
- "author": "JanluOfficial",
- "tags": ["math"],
- "contributors": [],
- "code": "function erf(x) {\n const sign = Math.sign(x);\n const absX = Math.abs(x);\n const t = 1 / (1 + 0.3275911 * absX);\n const a1 = 0.254829592, a2 = -0.284496736, a3 = 1.421413741, a4 = -1.453152027, a5 = 1.061405429;\n const poly = t * (a1 + t * (a2 + t * (a3 + t * (a4 + t * a5))));\n return sign * (1 - poly * Math.exp(-absX * absX));\n}\n\n// Usage:\nerf(-1); // Returns: -0.8427006897475899\nerf(1); // Returns: 0.8427006897475899\n",
- "extension": "js"
- },
- {
- "title": "Greatest Common Divisor",
- "description": "Calculates the largest positive integer that divides each of the integers without leaving a remainder. Useful for calculating aspect ratios.",
- "author": "JanluOfficial",
- "tags": ["math", "division", "number-theory", "algebra"],
- "contributors": [],
- "code": "function gcd(a, b) {\n while (b !== 0) {\n let temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n}\n\n// Usage:\ngcd(1920, 1080); // Returns: 120\ngcd(1920, 1200); // Returns: 240\ngcd(5,12); // Returns: 1\n",
- "extension": "js"
- },
- {
- "title": "Least common multiple",
- "description": "Computes the least common multiple (LCM) of two numbers 𝑎 and b. The LCM is the smallest positive integer that is divisible by both a and b.",
- "author": "JanluOfficial",
- "tags": ["math", "number-theory", "algebra"],
- "contributors": [],
- "code": "function lcm(a, b) {\n function gcd(x, y) {\n while (y !== 0) {\n const temp = y;\n y = x % y;\n x = temp;\n }\n return Math.abs(x);\n }\n return Math.abs(a * b) / gcd(a, b);\n}\n\n// Usage:\nlcm(12,16); // Returns: 48\nlcm(8,20); // Returns: 40\nlcm(16,17); // Returns: 272\n",
- "extension": "js"
- },
- {
- "title": "Linear Mapping",
- "description": "remaps a value from one range to another",
- "author": "JasimAlrawie",
- "tags": ["math", "number-theory", "algebra"],
- "contributors": [],
- "code": "function linearMapping(value, minIn, maxIn, minOut, maxOut) {\n return (value - minIn) * (maxOut - minOut)/(maxIn - minIn) + minOut\n}\n\n// Usage:\nlinearMapping(value, 0, 1, 0, 255) // remaps the value from (0,1) to (0,255)\nlinearMapping(value, 0, PI*2, 0, 360) // remaps the value from rad to deg\nlinearMapping(value, -1, 1, 1, 8) // remaps the value from (-1,1) to (1,8)\n",
- "extension": "js"
- },
- {
- "title": "Matrix Multiplication",
- "description": "Multiplies two matrices, where the number of columns in the first matrix equals the number of rows in the second.",
- "author": "JanluOfficial",
- "tags": ["math", "matrix-algebra"],
- "contributors": [],
- "code": "function matrixMultiply(A, B) {\n const rowsA = A.length;\n const colsA = A[0].length;\n const rowsB = B.length;\n const colsB = B[0].length;\n\n if (colsA !== rowsB) {\n throw new Error('Number of columns of A must equal the number of rows of B');\n }\n\n let result = Array.from({ length: rowsA }, () => Array(colsB).fill(0));\n\n for (let i = 0; i < rowsA; i++) {\n for (let j = 0; j < colsB; j++) {\n for (let k = 0; k < colsA; k++) {\n result[i][j] += A[i][k] * B[k][j];\n }\n }\n }\n\n return result;\n}\n\n// Usage:\nmatrixMultiply([[1, 2], [3, 4]], [[5, 6], [7, 8]]); // Returns: [[19, 22], [43, 50]]\n",
- "extension": "js"
- },
- {
- "title": "Modular Inverse",
- "description": "Computes the modular multiplicative inverse of a number a under modulo m, which is the integer x such that (a*x) mod m=1.",
- "author": "JanluOfficial",
- "tags": ["math", "number-theory", "algebra"],
- "contributors": [],
- "code": "function modInverse(a, m) {\n function extendedGCD(a, b) {\n if (b === 0) {\n return { gcd: a, x: 1, y: 0 };\n }\n const { gcd, x: x1, y: y1 } = extendedGCD(b, a % b);\n const x = y1;\n const y = x1 - Math.floor(a / b) * y1;\n return { gcd, x, y };\n }\n\n const { gcd, x } = extendedGCD(a, m);\n\n if (gcd !== 1) {\n return null;\n }\n\n return (x % m + m) % m;\n}\n\n// Usage:\nmodInverse(3, 26); // Returns: 9\nmodInverse(10, 17); // Returns: 12\nmodInverse(6, 9); // Returns: null\n",
- "extension": "js"
- },
- {
- "title": "Prime Number",
- "description": "Checks if a number is a prime number or not.",
- "author": "JanluOfficial",
- "tags": ["math", "number-theory", "algebra"],
- "contributors": [],
- "code": "function isPrime(num) {\n if (num <= 1) return false; // 0 and 1 are not prime numbers\n if (num <= 3) return true; // 2 and 3 are prime numbers\n if (num % 2 === 0 || num % 3 === 0) return false; // Exclude multiples of 2 and 3\n\n // Check divisors from 5 to √num, skipping multiples of 2 and 3\n for (let i = 5; i * i <= num; i += 6) {\n if (num % i === 0 || num % (i + 2) === 0) return false;\n }\n return true;\n}\n\n// Usage:\nisPrime(69); // Returns: false\nisPrime(17); // Returns: true\n",
- "extension": "js"
- }
- ]
- },
- {
- "name": "Number Formatting",
- "snippets": [
- {
- "title": "Convert Number to Currency",
- "description": "Converts a number to a currency format with a specific locale.",
- "author": "axorax",
- "tags": ["number", "currency"],
- "contributors": [],
- "code": "const convertToCurrency = (num, locale = 'en-US', currency = 'USD') => {\n return new Intl.NumberFormat(locale, {\n style: 'currency',\n currency: currency\n }).format(num);\n};\n\n// Usage:\nconvertToCurrency(1234567.89); // Returns: '$1,234,567.89'\nconvertToCurrency(987654.32, 'de-DE', 'EUR'); // Returns: '987.654,32 €'\n",
- "extension": "js"
- },
- {
- "title": "Convert Number to Roman Numerals",
- "description": "Converts a number to Roman numeral representation.",
- "author": "axorax",
- "tags": ["number", "roman"],
- "contributors": [],
- "code": "const numberToRoman = (num) => {\n const romanNumerals = {\n 1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L',\n 90: 'XC', 100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M'\n };\n let result = '';\n Object.keys(romanNumerals).reverse().forEach(value => {\n while (num >= value) {\n result += romanNumerals[value];\n num -= value;\n }\n });\n return result;\n};\n\n// Usage:\nnumberToRoman(1994); // Returns: 'MCMXCIV'\nnumberToRoman(58); // Returns: 'LVIII'\n",
- "extension": "js"
- },
- {
- "title": "Convert to Scientific Notation",
- "description": "Converts a number to scientific notation.",
- "author": "axorax",
- "tags": ["number", "scientific"],
- "contributors": [],
- "code": "const toScientificNotation = (num) => {\n if (isNaN(num)) {\n throw new Error('Input must be a number');\n }\n if (num === 0) {\n return '0e+0';\n }\n const exponent = Math.floor(Math.log10(Math.abs(num)));\n const mantissa = num / Math.pow(10, exponent);\n return `${mantissa.toFixed(2)}e${exponent >= 0 ? '+' : ''}${exponent}`;\n};\n\n// Usage:\ntoScientificNotation(12345); // Returns: '1.23e+4'\ntoScientificNotation(0.0005678); // Returns: '5.68e-4'\ntoScientificNotation(1000); // Returns: '1.00e+3'\ntoScientificNotation(0); // Returns: '0e+0'\ntoScientificNotation(-54321); // Returns: '-5.43e+4'\n",
- "extension": "js"
- },
- {
- "title": "Format File Size",
- "description": "Converts bytes into human-readable file size format.",
- "author": "jjcantu",
- "tags": ["format", "size"],
- "contributors": [],
- "code": "function formatFileSize(bytes) {\n if (bytes === 0) return '0 Bytes';\n \n const k = 1024;\n const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n \n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n}\n\n// Usage:\nconsole.log(formatFileSize(1234)); // Output: \"1.21 KB\"\nconsole.log(formatFileSize(1234567)); // Output: \"1.18 MB\"\n",
- "extension": "js"
- },
- {
- "title": "Format Number with Commas",
- "description": "Formats a number with commas for better readability (e.g., 1000 -> 1,000).",
- "author": "axorax",
- "tags": ["number", "format"],
- "contributors": [],
- "code": "const formatNumberWithCommas = (num) => {\n return num.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n};\n\n// Usage:\nformatNumberWithCommas(1000); // Returns: '1,000'\nformatNumberWithCommas(1234567); // Returns: '1,234,567'\nformatNumberWithCommas(987654321); // Returns: '987,654,321'\n",
- "extension": "js"
- },
- {
- "title": "Number Formatter",
- "description": "Formats a number with suffixes (K, M, B, etc.).",
- "author": "realvishalrana",
- "tags": ["number", "format"],
- "contributors": [],
- "code": "const nFormatter = (num) => {\n if (!num) return;\n num = parseFloat(num.toString().replace(/[^0-9.]/g, ''));\n const suffixes = ['', 'K', 'M', 'B', 'T', 'P', 'E'];\n let index = 0;\n while (num >= 1000 && index < suffixes.length - 1) {\n num /= 1000;\n index++;\n }\n return num.toFixed(2).replace(/\\.0+$|(\\.[0-9]*[1-9])0+$/, '$1') + suffixes[index];\n};\n\n// Usage:\nnFormatter(1234567); // Returns: '1.23M'\n",
- "extension": "js"
- },
- {
- "title": "Number to Words Converter",
- "description": "Converts a number to its word representation in English.",
- "author": "axorax",
- "tags": ["number", "words"],
- "contributors": [],
- "code": "const numberToWords = (num) => {\n const below20 = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'];\n const tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];\n const above1000 = ['Hundred', 'Thousand', 'Million', 'Billion'];\n if (num < 20) return below20[num];\n let words = '';\n for (let i = 0; num > 0; i++) {\n if (i > 0 && num % 1000 !== 0) words = above1000[i] + ' ' + words;\n if (num % 100 >= 20) {\n words = tens[Math.floor(num / 10)] + ' ' + words;\n num %= 10;\n }\n if (num < 20) words = below20[num] + ' ' + words;\n num = Math.floor(num / 100);\n }\n return words.trim();\n};\n\n// Usage:\nnumberToWords(123); // Returns: 'One Hundred Twenty Three'\nnumberToWords(2045); // Returns: 'Two Thousand Forty Five'\n",
- "extension": "js"
- }
- ]
- },
- {
- "name": "Object Manipulation",
- "snippets": [
- {
- "title": "Check if Object is Empty",
- "description": "Checks whether an object has no own enumerable properties.",
- "author": "axorax",
- "tags": ["object", "check", "empty"],
- "contributors": [],
- "code": "function isEmptyObject(obj) {\n return Object.keys(obj).length === 0;\n}\n\n// Usage:\nisEmptyObject({}); // Returns: true\nisEmptyObject({ a: 1 }); // Returns: false\n",
- "extension": "js"
- },
- {
- "title": "Compare Two Objects Shallowly",
- "description": "Compares two objects shallowly and returns whether they are equal.",
- "author": "axorax",
- "tags": ["object", "compare", "shallow"],
- "contributors": [],
- "code": "function shallowEqual(obj1, obj2) {\n const keys1 = Object.keys(obj1);\n const keys2 = Object.keys(obj2);\n if (keys1.length !== keys2.length) return false;\n return keys1.every(key => obj1[key] === obj2[key]);\n}\n\n// Usage:\nconst obj1 = { a: 1, b: 2 };\nconst obj2 = { a: 1, b: 2 };\nconst obj3 = { a: 1, b: 3 };\nshallowEqual(obj1, obj2); // Returns: true\nshallowEqual(obj1, obj3); // Returns: false\n",
- "extension": "js"
- },
- {
- "title": "Convert Object to Query String",
- "description": "Converts an object to a query string for use in URLs.",
- "author": "axorax",
- "tags": ["object", "query string", "url"],
- "contributors": [],
- "code": "function toQueryString(obj) {\n return Object.entries(obj)\n .map(([key, value]) => encodeURIComponent(key) + '=' + encodeURIComponent(value))\n .join('&');\n}\n\n// Usage:\nconst params = { search: 'test', page: 1 };\ntoQueryString(params); // Returns: 'search=test&page=1'\n",
- "extension": "js"
- },
- {
- "title": "Count Properties in Object",
- "description": "Counts the number of own properties in an object.",
- "author": "axorax",
- "tags": ["object", "count", "properties"],
- "contributors": [],
- "code": "function countProperties(obj) {\n return Object.keys(obj).length;\n}\n\n// Usage:\nconst obj = { a: 1, b: 2, c: 3 };\ncountProperties(obj); // Returns: 3\n",
- "extension": "js"
- },
- {
- "title": "Deep Clone Object",
- "description": "Creates a deep copy of an object or array without reference.",
- "author": "jjcantu",
- "tags": ["object", "clone"],
- "contributors": [],
- "code": "function deepClone(obj) {\n if (obj === null || typeof obj !== 'object') return obj;\n \n const clone = Array.isArray(obj) ? [] : {};\n \n for (let key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clone[key] = deepClone(obj[key]);\n }\n }\n \n return clone;\n}\n\n// Usage:\nconst original = { a: 1, b: { c: 2 }, d: [1, 2, 3] };\nconst cloned = deepClone(original);\nconsole.log(cloned); // Output: 'original' but cloned\n",
- "extension": "js"
- },
- {
- "title": "Filter Object",
- "description": "Filter out entries in an object where the value is falsy, including empty strings, empty objects, null, and undefined.",
- "author": "realvishalrana",
- "tags": ["object", "filter"],
- "contributors": [],
- "code": "export const filterObject = (object = {}) =>\n Object.fromEntries(\n Object.entries(object)\n .filter(([key, value]) => value !== null && value !== undefined && value !== '' && (typeof value !== 'object' || Object.keys(value).length > 0))\n );\n\n// Usage:\nconst obj1 = { a: 1, b: null, c: undefined, d: 4, e: '', f: {} };\nfilterObject(obj1); // Returns: { a: 1, d: 4 }\n\nconst obj2 = { x: 0, y: false, z: 'Hello', w: [] };\nfilterObject(obj2); // Returns: { z: 'Hello' }\n\nconst obj3 = { name: 'John', age: null, address: { city: 'New York' }, phone: '' };\nfilterObject(obj3); // Returns: { name: 'John', address: { city: 'New York' } }\n\nconst obj4 = { a: 0, b: '', c: false, d: {}, e: 'Valid' };\nfilterObject(obj4); // Returns: { e: 'Valid' }\n",
- "extension": "js"
- },
- {
- "title": "Flatten Nested Object",
- "description": "Flattens a nested object into a single-level object with dot notation for keys.",
- "author": "axorax",
- "tags": ["object", "flatten"],
- "contributors": [],
- "code": "function flattenObject(obj, prefix = '') {\n return Object.keys(obj).reduce((acc, key) => {\n const fullPath = prefix ? `${prefix}.${key}` : key;\n if (typeof obj[key] === 'object' && obj[key] !== null) {\n Object.assign(acc, flattenObject(obj[key], fullPath));\n } else {\n acc[fullPath] = obj[key];\n }\n return acc;\n }, {});\n}\n\n// Usage:\nconst nestedObj = { a: { b: { c: 1 }, d: 2 }, e: 3 };\nflattenObject(nestedObj); // Returns: { 'a.b.c': 1, 'a.d': 2, e: 3 }\n",
- "extension": "js"
- },
- {
- "title": "Freeze Object",
- "description": "Freezes an object to make it immutable.",
- "author": "axorax",
- "tags": ["object", "freeze", "immutable"],
- "contributors": [],
- "code": "function freezeObject(obj) {\n return Object.freeze(obj);\n}\n\n// Usage:\nconst obj = { a: 1, b: 2 };\nconst frozenObj = freezeObject(obj);\nfrozenObj.a = 42; // This will fail silently in strict mode.\nfrozenObj.a; // Returns: 1\n",
- "extension": "js"
- },
- {
- "title": "Get Nested Value",
- "description": "Retrieves the value at a given path in a nested object.",
- "author": "realvishalrana",
- "tags": ["object", "nested"],
- "contributors": [],
- "code": "const getNestedValue = (obj, path) => {\n const keys = path.split('.');\n return keys.reduce((currentObject, key) => {\n return currentObject && typeof currentObject === 'object' ? currentObject[key] : undefined;\n }, obj);\n};\n\n// Usage:\nconst obj = { a: { b: { c: 42 } } };\ngetNestedValue(obj, 'a.b.c'); // Returns: 42\n",
- "extension": "js"
- },
- {
- "title": "Invert Object Keys and Values",
- "description": "Creates a new object by swapping keys and values of the given object.",
- "author": "axorax",
- "tags": ["object", "invert"],
- "contributors": [],
- "code": "function invertObject(obj) {\n return Object.fromEntries(\n Object.entries(obj).map(([key, value]) => [value, key])\n );\n}\n\n// Usage:\nconst obj = { a: 1, b: 2, c: 3 };\ninvertObject(obj); // Returns: { '1': 'a', '2': 'b', '3': 'c' }\n",
- "extension": "js"
- },
- {
- "title": "Merge Objects Deeply",
- "description": "Deeply merges two or more objects, including nested properties.",
- "author": "axorax",
- "tags": ["object", "merge", "deep"],
- "contributors": [],
- "code": "function deepMerge(...objects) {\n return objects.reduce((acc, obj) => {\n Object.keys(obj).forEach(key => {\n if (typeof obj[key] === 'object' && obj[key] !== null) {\n acc[key] = deepMerge(acc[key] || {}, obj[key]);\n } else {\n acc[key] = obj[key];\n }\n });\n return acc;\n }, {});\n}\n\n// Usage:\nconst obj1 = { a: 1, b: { c: 2 } };\nconst obj2 = { b: { d: 3 }, e: 4 };\ndeepMerge(obj1, obj2); // Returns: { a: 1, b: { c: 2, d: 3 }, e: 4 }\n",
- "extension": "js"
- },
- {
- "title": "Omit Keys from Object",
- "description": "Creates a new object with specific keys omitted.",
- "author": "axorax",
- "tags": ["object", "omit"],
- "contributors": [],
- "code": "function omitKeys(obj, keys) {\n return Object.fromEntries(\n Object.entries(obj).filter(([key]) => !keys.includes(key))\n );\n}\n\n// Usage:\nconst obj = { a: 1, b: 2, c: 3 };\nomitKeys(obj, ['b', 'c']); // Returns: { a: 1 }\n",
- "extension": "js"
- },
- {
- "title": "Pick Keys from Object",
- "description": "Creates a new object with only the specified keys.",
- "author": "axorax",
- "tags": ["object", "pick"],
- "contributors": [],
- "code": "function pickKeys(obj, keys) {\n return Object.fromEntries(\n Object.entries(obj).filter(([key]) => keys.includes(key))\n );\n}\n\n// Usage:\nconst obj = { a: 1, b: 2, c: 3 };\npickKeys(obj, ['a', 'c']); // Returns: { a: 1, c: 3 }\n",
- "extension": "js"
- },
- {
- "title": "Unique By Key",
- "description": "Filters an array of objects to only include unique objects by a specified key.",
- "author": "realvishalrana",
- "tags": ["array", "unique"],
- "contributors": [],
- "code": "const uniqueByKey = (key, arr) =>\n arr.filter((obj, index, self) => index === self.findIndex((t) => t?.[key] === obj?.[key]));\n\n// Usage:\nconst arr = [\n { id: 1, name: 'John' },\n { id: 2, name: 'Jane' },\n { id: 1, name: 'John' }\n];\nuniqueByKey('id', arr); // Returns: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]\n",
- "extension": "js"
- }
- ]
- },
- {
- "name": "String Manipulation",
- "snippets": [
- {
- "title": "Capitalize String",
- "description": "Capitalizes the first letter of a string.",
- "author": "technoph1le",
- "tags": ["string", "capitalize"],
- "contributors": [],
- "code": "function capitalize(str) {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n// Usage:\ncapitalize('hello'); // Returns: 'Hello'\n",
- "extension": "js"
- },
- {
- "title": "Check if String is a Palindrome",
- "description": "Checks whether a given string is a palindrome.",
- "author": "axorax",
- "tags": ["check", "palindrome", "string"],
- "contributors": [],
- "code": "function isPalindrome(str) {\n const cleanStr = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();\n return cleanStr === cleanStr.split('').reverse().join('');\n}\n\n// Example usage:\nisPalindrome('A man, a plan, a canal, Panama'); // Returns: true\n",
- "extension": "js"
- },
- {
- "title": "Convert String to Camel Case",
- "description": "Converts a given string into camelCase.",
- "author": "aumirza",
- "tags": ["string", "case", "camelCase"],
- "contributors": [],
- "code": "function toCamelCase(str) {\n return str.replace(/\\W+(.)/g, (match, chr) => chr.toUpperCase());\n}\n\n// Usage:\ntoCamelCase('hello world test'); // Returns: 'helloWorldTest'\n",
- "extension": "js"
- },
- {
- "title": "Convert String to Param Case",
- "description": "Converts a given string into param-case.",
- "author": "aumirza",
- "tags": ["string", "case", "paramCase"],
- "contributors": [],
- "code": "function toParamCase(str) {\n return str.toLowerCase().replace(/\\s+/g, '-');\n}\n\n// Usage:\ntoParamCase('Hello World Test'); // Returns: 'hello-world-test'\n",
- "extension": "js"
- },
- {
- "title": "Convert String to Pascal Case",
- "description": "Converts a given string into Pascal Case.",
- "author": "aumirza",
- "tags": ["string", "case", "pascalCase"],
- "contributors": [],
- "code": "function toPascalCase(str) {\n return str.replace(/\\b\\w/g, (s) => s.toUpperCase()).replace(/\\W+(.)/g, (match, chr) => chr.toUpperCase());\n}\n\n// Usage:\ntoPascalCase('hello world test'); // Returns: 'HelloWorldTest'\n",
- "extension": "js"
- },
- {
- "title": "Convert String to Snake Case",
- "description": "Converts a given string into snake_case.",
- "author": "axorax",
- "tags": ["string", "case", "snake_case"],
- "contributors": [],
- "code": "function toSnakeCase(str) {\n return str.replace(/([a-z])([A-Z])/g, '$1_$2')\n .replace(/\\s+/g, '_')\n .toLowerCase();\n}\n\n// Usage:\ntoSnakeCase('Hello World Test'); // Returns: 'hello_world_test'\n",
- "extension": "js"
- },
- {
- "title": "Convert String to Title Case",
- "description": "Converts a given string into Title Case.",
- "author": "aumirza",
- "tags": ["string", "case", "titleCase"],
- "contributors": [],
- "code": "function toTitleCase(str) {\n return str.toLowerCase().replace(/\\b\\w/g, (s) => s.toUpperCase());\n}\n\n// Usage:\ntoTitleCase('hello world test'); // Returns: 'Hello World Test'\n",
- "extension": "js"
- },
- {
- "title": "Convert Tabs to Spaces",
- "description": "Converts all tab characters in a string to spaces.",
- "author": "axorax",
- "tags": ["string", "tabs", "spaces"],
- "contributors": [],
- "code": "function tabsToSpaces(str, spacesPerTab = 4) {\n return str.replace(/\\t/g, ' '.repeat(spacesPerTab));\n}\n\n// Usage:\ntabsToSpaces('Hello\\tWorld', 2); // Returns: 'Hello World'\n",
- "extension": "js"
- },
- {
- "title": "Count Words in a String",
- "description": "Counts the number of words in a string.",
- "author": "axorax",
- "tags": ["string", "manipulation", "word count", "count"],
- "contributors": [],
- "code": "function countWords(str) {\n return str.trim().split(/\\s+/).length;\n}\n\n// Usage:\ncountWords('Hello world! This is a test.'); // Returns: 6\n",
- "extension": "js"
- },
- {
- "title": "Data with Prefix",
- "description": "Adds a prefix and postfix to data, with a fallback value.",
- "author": "realvishalrana",
- "tags": ["data", "prefix", "postfix", "format"],
- "contributors": [],
- "code": "const dataWithPrefix = (data, fallback = '-', prefix = '', postfix = '') => {\n return data ? `${prefix}${data}${postfix}` : fallback;\n};\n\n// Usage:\ndataWithPrefix('123', '-', '(', ')'); // Returns: '(123)'\ndataWithPrefix('', '-', '(', ')'); // Returns: '-'\ndataWithPrefix('Hello', 'N/A', 'Mr. ', ''); // Returns: 'Mr. Hello'\ndataWithPrefix(null, 'N/A', 'Mr. ', ''); // Returns: 'N/A'\n",
- "extension": "js"
- },
- {
- "title": "Extract Initials from Name",
- "description": "Extracts and returns the initials from a full name.",
- "author": "axorax",
- "tags": ["string", "initials", "name"],
- "contributors": [],
- "code": "function getInitials(name) {\n return name.split(' ').map(part => part.charAt(0).toUpperCase()).join('');\n}\n\n// Usage:\ngetInitials('John Doe'); // Returns: 'JD'\n",
- "extension": "js"
- },
- {
- "title": "Generate UUID",
- "description": "Generates a UUID (v4) string.",
- "author": "jjcantu",
- "tags": ["uuid", "generate", "string"],
- "contributors": [],
- "code": "function generateUUID() {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n const r = Math.random() * 16 | 0;\n const v = c === 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n}\n\n// Usage:\nconsole.log(generateUUID()); // Output: \"a1b2c3d4-e5f6-4g7h-8i9j-k0l1m2n3o4p5\"\n",
- "extension": "js"
- },
- {
- "title": "Mask Sensitive Information",
- "description": "Masks parts of a sensitive string, like a credit card or email address.",
- "author": "axorax",
- "tags": ["string", "mask", "sensitive"],
- "contributors": [],
- "code": "function maskSensitiveInfo(str, visibleCount = 4, maskChar = '*') {\n return str.slice(0, visibleCount) + maskChar.repeat(Math.max(0, str.length - visibleCount));\n}\n\n// Usage:\nmaskSensitiveInfo('123456789', 4); // Returns: '1234*****'\nmaskSensitiveInfo('example@mail.com', 2, '#'); // Returns: 'ex#############'\n",
- "extension": "js"
- },
- {
- "title": "Pad String on Both Sides",
- "description": "Pads a string on both sides with a specified character until it reaches the desired length.",
- "author": "axorax",
- "tags": ["string", "pad", "manipulation"],
- "contributors": [],
- "code": "function padString(str, length, char = ' ') {\n const totalPad = length - str.length;\n const padStart = Math.floor(totalPad / 2);\n const padEnd = totalPad - padStart;\n return char.repeat(padStart) + str + char.repeat(padEnd);\n}\n\n// Usage:\npadString('hello', 10, '*'); // Returns: '**hello***'\n",
- "extension": "js"
- },
- {
- "title": "Random string",
- "description": "Generates a random string of characters of a certain length",
- "author": "kruimol",
- "tags": ["function", "random"],
- "contributors": [],
- "code": "function makeid(length, characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {\n return Array.from({ length }, () => characters.charAt(Math.floor(Math.random() * characters.length))).join('');\n}\n\nmakeid(3); // Returns: gDs (Random)\nmakeid(5, \"1234\" /* (optional) */); // Returns: \"35453\" (Random)\n",
- "extension": "js"
- },
- {
- "title": "Remove All Whitespace",
- "description": "Removes all whitespace from a string.",
- "author": "axorax",
- "tags": ["string", "whitespace"],
- "contributors": [],
- "code": "function removeWhitespace(str) {\n return str.replace(/\\s+/g, '');\n}\n\n// Usage:\nremoveWhitespace('Hello world!'); // Returns: 'Helloworld!'\n",
- "extension": "js"
- },
- {
- "title": "Remove Vowels from a String",
- "description": "Removes all vowels from a given string.",
- "author": "axorax",
- "tags": ["string", "remove", "vowels"],
- "contributors": [],
- "code": "function removeVowels(str) {\n return str.replace(/[aeiouAEIOU]/g, '');\n}\n\n// Usage:\nremoveVowels('Hello World'); // Returns: 'Hll Wrld'\n",
- "extension": "js"
- },
- {
- "title": "Reverse String",
- "description": "Reverses the characters in a string.",
- "author": "technoph1le",
- "tags": ["string", "reverse"],
- "contributors": [],
- "code": "const reverseString = (str) => str.split('').reverse().join('');\n\n// Usage:\nreverseString('hello'); // Returns: 'olleh'\n",
- "extension": "js"
- },
- {
- "title": "Slugify String",
- "description": "Converts a string into a URL-friendly slug format.",
- "author": "technoph1le",
- "tags": ["string", "slug"],
- "contributors": [],
- "code": "const slugify = (string, separator = \"-\") => {\n return string\n .toString() // Cast to string (optional)\n .toLowerCase() // Convert the string to lowercase letters\n .trim() // Remove whitespace from both sides of a string (optional)\n .replace(/\\s+/g, separator) // Replace spaces with {separator}\n .replace(/[^\\w\\-]+/g, \"\") // Remove all non-word chars\n .replace(/\\_/g, separator) // Replace _ with {separator}\n .replace(/\\-\\-+/g, separator) // Replace multiple - with single {separator}\n .replace(/\\-$/g, \"\"); // Remove trailing -\n};\n\n// Usage:\nconst title = \"Hello, World! This is a Test.\";\nslugify(title); // Returns: 'hello-world-this-is-a-test'\nslugify(title, \"_\"); // Returns: 'hello_world_this_is_a_test'\n",
- "extension": "js"
- },
- {
- "title": "Truncate Text",
- "description": "Truncates the text to a maximum length and appends '...' if the text exceeds the maximum length.",
- "author": "realvishalrana",
- "tags": ["string", "truncate", "text"],
- "contributors": [],
- "code": "const truncateText = (text = '', maxLength = 50) => {\n return `${text.slice(0, maxLength)}${text.length >= maxLength ? '...' : ''}`;\n};\n\n// Usage:\nconst title = \"Hello, World! This is a Test.\";\ntruncateText(title); // Returns: 'Hello, World! This is a Test.'\ntruncateText(title, 10); // Returns: 'Hello, Wor...'\n",
- "extension": "js"
- }
- ]
- }
-]
+ {
+ "name": "Array Manipulation",
+ "snippets": [
+ {
+ "title": "Compare Arrays",
+ "description": "Deeply compares two arrays to check if they are equal to each other (supports nested arrays and objects).",
+ "author": "KCSquid",
+ "tags": [
+ "array",
+ "object",
+ "compare",
+ "equal"
+ ],
+ "contributors": [],
+ "code": "const compareArrays = (a, b) => {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;\n return a.every((v, i) => \n Array.isArray(v) && Array.isArray(b[i]) ? compareArrays(v, b[i]) :\n typeof v === \"object\" && typeof b[i] === \"object\" ? compareObjects(v, b[i]) :\n v === b[i]\n );\n};\n\nconst compareObjects = (a, b) => {\n if (typeof a !== \"object\" || typeof b !== \"object\" || Object.keys(a).length !== Object.keys(b).length) return false;\n return Object.keys(a).every(k => \n Array.isArray(a[k]) && Array.isArray(b[k]) ? compareArrays(a[k], b[k]) :\n typeof a[k] === \"object\" && typeof b[k] === \"object\" ? compareObjects(a[k], b[k]) :\n a[k] === b[k]\n );\n};\n\n// Usage:\ncompareArrays([1, 2, 3], [1, 2, 3]); // Returns: true\ncompareArrays([1, 2, 3], [3, 2, 1]); // Returns: false\ncompareArrays([{a:1}], [{a:1}]); // Returns: true\ncompareArrays([{a:1}], null); // Returns: false\n",
+ "extension": "js"
+ },
+ {
+ "title": "Partition Array",
+ "description": "Splits an array into two arrays based on a callback function.",
+ "author": "Swaraj-Singh-30",
+ "tags": [
+ "array",
+ "partition",
+ "reduce"
+ ],
+ "contributors": [],
+ "code": "const partition = (arr, callback) =>\n arr.reduce(\n ([pass, fail], elem) => (callback(elem) ? [[...pass, elem], fail] : [pass, [...fail, elem]]),\n [[], []]\n );\n\n// Usage:\nconst numbers = [1, 2, 3, 4, 5, 6];\nconst isEven = (n) => n % 2 === 0;\npartition(numbers, isEven); // Returns: [[2, 4, 6], [1, 3, 5]]\n",
+ "extension": "js"
+ },
+ {
+ "title": "Remove Duplicates",
+ "description": "Removes duplicate values from an array.",
+ "author": "technoph1le",
+ "tags": [
+ "array",
+ "deduplicate"
+ ],
+ "contributors": [],
+ "code": "const removeDuplicates = (arr) => [...new Set(arr)];\n\n// Usage:\nconst numbers = [1, 2, 2, 3, 4, 4, 5];\nremoveDuplicates(numbers); // Returns: [1, 2, 3, 4, 5]\n",
+ "extension": "js"
+ },
+ {
+ "title": "Remove Falsy Values",
+ "description": "Removes falsy values from an array.",
+ "author": "mubasshir",
+ "tags": [
+ "array",
+ "falsy",
+ "filter"
+ ],
+ "contributors": [],
+ "code": "const removeFalsy = (arr) => arr.filter(Boolean);\n\n// Usage:\nconst array = [0, 1, false, 2, \"\", 3, null];\nremoveFalsy(array); // Returns: [1, 2, 3]\n",
+ "extension": "js"
+ },
+ {
+ "title": "Shuffle Array",
+ "description": "Shuffles an Array.",
+ "author": "loxt-nixo",
+ "tags": [
+ "array",
+ "shuffle"
+ ],
+ "contributors": [],
+ "code": "function shuffleArray(array) {\n for (let i = array.length - 1; i >= 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n [array[i], array[j]] = [array[j], array[i]];\n }\n}\n\n// Usage:\nconst array = [1, 2, 3, 4, 5];\nshuffleArray(array); // Shuffles `array` in place\n",
+ "extension": "js"
+ },
+ {
+ "title": "Zip Arrays",
+ "description": "Combines two arrays by pairing corresponding elements from each array.",
+ "author": "Swaraj-Singh-30",
+ "tags": [
+ "array",
+ "map"
+ ],
+ "contributors": [],
+ "code": "const zip = (arr1, arr2) => arr1.map((value, index) => [value, arr2[index]]);\n\n// Usage:\nconst arr1 = ['a', 'b', 'c'];\nconst arr2 = [1, 2, 3];\nconsole.log(zip(arr1, arr2)); // Output: [['a', 1], ['b', 2], ['c', 3]]\n",
+ "extension": "js"
+ }
+ ]
+ },
+ {
+ "name": "Basics",
+ "snippets": [
+ {
+ "title": "Hello, World!",
+ "description": "Prints Hello, World! to the terminal.",
+ "author": "James-Beans",
+ "tags": [
+ "printing",
+ "hello-world"
+ ],
+ "contributors": [],
+ "code": "console.log(\"Hello, World!\"); // Prints Hello, World! to the console\n",
+ "extension": "js"
+ }
+ ]
+ },
+ {
+ "name": "Color Manipulation",
+ "snippets": [
+ {
+ "title": "Hex to RGB Color",
+ "description": "Converts hexadecimal color code to RGB color values.",
+ "author": "pvictordev",
+ "tags": [
+ "color",
+ "conversion"
+ ],
+ "contributors": [],
+ "code": "function hexToRgb(hex) {\n let sanitizedHex = hex.startsWith(\"#\") ? hex.slice(1) : hex;\n\n if (sanitizedHex.length === 3) {\n sanitizedHex = [...sanitizedHex].map((char) => char + char).join(\"\");\n }\n\n const bigint = parseInt(sanitizedHex, 16);\n\n return {\n r: (bigint >> 16) & 0xff, \n g: (bigint >> 8) & 0xff, \n b: bigint & 0xff, \n };\n}\n\n// Usage:\nconsole.log(hexToRgb(\"#ff5733\")); // { r: 255, g: 87, b: 51 }\nconsole.log(hexToRgb(\"#ffff\")); // { r: 0, g: 255, b: 255 }\n",
+ "extension": "js"
+ },
+ {
+ "title": "HSL to RGB Color",
+ "description": "Converts HSL color values to RGB color values.",
+ "author": "pvictordev",
+ "tags": [
+ "color",
+ "conversion"
+ ],
+ "contributors": [],
+ "code": "function hslToRgb(h, s, l) {\n s /= 100;\n l /= 100;\n const c = (1 - Math.abs(2 * l - 1)) * s;\n const x = c * (1 - Math.abs((h / 60) % 2 - 1));\n const m = l - c / 2;\n\n const [r, g, b] = \n h < 60 ? [c, x, 0] :\n h < 120 ? [x, c, 0] :\n h < 180 ? [0, c, x] :\n h < 240 ? [0, x, c] :\n h < 300 ? [x, 0, c] :\n [c, 0, x];\n\n return {\n r: Math.round((r + m) * 255),\n g: Math.round((g + m) * 255),\n b: Math.round((b + m) * 255),\n };\n}\n\n// Usage:\nconsole.log(hslToRgb(14, 100, 60)); // { r: 255, g: 87, b: 51 }\nconsole.log(hslToRgb(0, 0, 100)); // { r: 255, g: 255, b: 255 }\n",
+ "extension": "js"
+ },
+ {
+ "title": "RGB to Hex Color",
+ "description": "Converts RGB color values to hexadecimal color code.",
+ "author": "jjcantu",
+ "tags": [
+ "color",
+ "conversion"
+ ],
+ "contributors": [],
+ "code": "function rgbToHex(r, g, b) {\n const toHex = (n) => {\n const hex = n.toString(16);\n return hex.length === 1 ? \"0\" + hex : hex;\n };\n\n return \"#\" + toHex(r) + toHex(g) + toHex(b);\n}\n\n// Usage:\nconsole.log(rgbToHex(255, 128, 0)); // Output: \"#ff8000\"\nconsole.log(rgbToHex(0, 255, 0)); // Output: \"#00ff00\"\n",
+ "extension": "js"
+ },
+ {
+ "title": "RGB to HSL Color",
+ "description": "Converts RGB color values to HSL color values.",
+ "author": "pvictordev",
+ "tags": [
+ "color",
+ "conversion"
+ ],
+ "contributors": [],
+ "code": "function rgbToHsl(r, g, b) {\n [r, g, b] = [r, g, b].map((v) => v / 255);\n\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n const delta = max - min;\n\n const l = (max + min) / 2;\n\n if (delta === 0) return { h: 0, s: 0, l: Math.round(l * 100) };\n\n const s = l > 0.5 ? delta / (2 - max - min) : delta / (max + min);\n\n const h = \n max === r ? ((g - b) / delta + (g < b ? 6 : 0)) :\n max === g ? (b - r) / delta + 2 :\n (r - g) / delta + 4;\n\n return {\n h: Math.round(h * 60), \n s: Math.round(s * 100),\n l: Math.round(l * 100), \n };\n}\n\n// Usage:\nconsole.log(rgbToHsl(255, 87, 51)); // { h: 14, s: 100, l: 60 }\nconsole.log(rgbToHsl(255, 255, 255)); // { h: 0, s: 0, l: 100 }\n",
+ "extension": "js"
+ }
+ ]
+ },
+ {
+ "name": "Date And Time",
+ "snippets": [
+ {
+ "title": "Check Leap Year",
+ "description": "Determines if a given year is a leap year.",
+ "author": "axorax",
+ "tags": [
+ "date",
+ "leap-year"
+ ],
+ "contributors": [],
+ "code": "const isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n\n// Usage:\nisLeapYear(2024); // Returns: true\nisLeapYear(2023); // Returns: false\n",
+ "extension": "js"
+ },
+ {
+ "title": "Convert to Unix Timestamp",
+ "description": "Converts a date to a Unix timestamp in seconds.",
+ "author": "Yugveer06",
+ "tags": [
+ "date",
+ "unix",
+ "timestamp"
+ ],
+ "contributors": [],
+ "code": "function convertToUnixSeconds(input) {\n if (typeof input === 'string') {\n if (!input.trim()) {\n throw new Error('Date string cannot be empty or whitespace');\n }\n } else if (!input) {\n throw new Error('Input is required');\n }\n\n let date;\n\n if (typeof input === 'string') {\n date = new Date(input);\n } else if (input instanceof Date) {\n date = input;\n } else {\n throw new Error('Input must be a valid date string or Date object');\n }\n\n if (isNaN(date.getTime())) {\n throw new Error('Invalid date provided');\n }\n\n return Math.floor(date.getTime() / 1000);\n}\n\n// Usage:\nconvertToUnixSeconds('2025-01-01T12:00:00Z'); // Returns: 1735732800\nconvertToUnixSeconds(new Date('2025-01-01T12:00:00Z')); // Returns: 1735732800\nconvertToUnixSeconds(new Date()); // Returns: Current Unix timestamp in seconds\n",
+ "extension": "js"
+ },
+ {
+ "title": "Format Date",
+ "description": "Formats a date in 'YYYY-MM-DD' format.",
+ "author": "technoph1le",
+ "tags": [
+ "date",
+ "format"
+ ],
+ "contributors": [],
+ "code": "const formatDate = (date) => date.toISOString().split('T')[0];\n\n// Usage:\nformatDate(new Date(2024, 11, 10)); // Returns: '2024-12-10'\n",
+ "extension": "js"
+ },
+ {
+ "title": "Get Day of the Year",
+ "description": "Calculates the day of the year (1-365 or 1-366 for leap years) for a given date.",
+ "author": "axorax",
+ "tags": [
+ "date",
+ "day-of-year"
+ ],
+ "contributors": [],
+ "code": "const getDayOfYear = (date) => {\n const startOfYear = new Date(date.getFullYear(), 0, 0);\n const diff = date - startOfYear + (startOfYear.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000;\n return Math.floor(diff / (1000 * 60 * 60 * 24));\n};\n\n// Usage:\ngetDayOfYear(new Date('2024-12-31')) // Returns: 366 (Leap year)\n",
+ "extension": "js"
+ },
+ {
+ "title": "Get Days in Month",
+ "description": "Calculates the number of days in a specific month of a given year.",
+ "author": "axorax",
+ "tags": [
+ "date",
+ "days-in-month"
+ ],
+ "contributors": [],
+ "code": "const getDaysInMonth = (year, month) => new Date(year, month + 1, 0).getDate();\n\n// Usage:\ngetDaysInMonth(2024, 1); // Returns: 29 (February in a leap year)\ngetDaysInMonth(2023, 1); // Returns: 28\n",
+ "extension": "js"
+ },
+ {
+ "title": "Get Time Difference",
+ "description": "Calculates the time difference in days between two dates.",
+ "author": "technoph1le",
+ "tags": [
+ "date",
+ "time-difference"
+ ],
+ "contributors": [],
+ "code": "const getTimeDifference = (date1, date2) => {\n const diff = Math.abs(date2 - date1);\n return Math.ceil(diff / (1000 * 60 * 60 * 24));\n};\n\n// Usage:\nconst date1 = new Date('2024-01-01');\nconst date2 = new Date('2024-12-31');\ngetTimeDifference(date1, date2); // Returns: 365\n",
+ "extension": "js"
+ },
+ {
+ "title": "Relative Time Formatter",
+ "description": "Displays how long ago a date occurred or how far in the future a date is.",
+ "author": "Yugveer06",
+ "tags": [
+ "date",
+ "time",
+ "relative",
+ "future",
+ "past"
+ ],
+ "contributors": [],
+ "code": "const getRelativeTime = (date) => {\n const now = Date.now();\n const diff = date.getTime() - now;\n const seconds = Math.abs(Math.floor(diff / 1000));\n const minutes = Math.abs(Math.floor(seconds / 60));\n const hours = Math.abs(Math.floor(minutes / 60));\n const days = Math.abs(Math.floor(hours / 24));\n const years = Math.abs(Math.floor(days / 365));\n\n if (Math.abs(diff) < 1000) return 'just now';\n\n const isFuture = diff > 0;\n\n if (years > 0) return `${isFuture ? 'in ' : ''}${years} ${years === 1 ? 'year' : 'years'}${isFuture ? '' : ' ago'}`;\n if (days > 0) return `${isFuture ? 'in ' : ''}${days} ${days === 1 ? 'day' : 'days'}${isFuture ? '' : ' ago'}`;\n if (hours > 0) return `${isFuture ? 'in ' : ''}${hours} ${hours === 1 ? 'hour' : 'hours'}${isFuture ? '' : ' ago'}`;\n if (minutes > 0) return `${isFuture ? 'in ' : ''}${minutes} ${minutes === 1 ? 'minute' : 'minutes'}${isFuture ? '' : ' ago'}`;\n\n return `${isFuture ? 'in ' : ''}${seconds} ${seconds === 1 ? 'second' : 'seconds'}${isFuture ? '' : ' ago'}`;\n}\n\n// Usage:\nconst pastDate = new Date('2021-12-29 13:00:00');\nconst futureDate = new Date('2099-12-29 13:00:00');\ngetRelativeTime(pastDate); // x years ago\ngetRelativeTime(new Date()); // just now\ngetRelativeTime(futureDate); // in x years\n",
+ "extension": "js"
+ },
+ {
+ "title": "Start of the Day",
+ "description": "Returns the start of the day (midnight) for a given date.",
+ "author": "axorax",
+ "tags": [
+ "date",
+ "start-of-day"
+ ],
+ "contributors": [],
+ "code": "const startOfDay = (date) => new Date(date.setHours(0, 0, 0, 0));\n\n// Usage:\nconst today = new Date();\nstartOfDay(today); // Returns: Date object for midnight\n",
+ "extension": "js"
+ }
+ ]
+ },
+ {
+ "name": "Dom Manipulation",
+ "snippets": [
+ {
+ "title": "Change Element Style",
+ "description": "Changes the inline style of an element.",
+ "author": "axorax",
+ "tags": [
+ "dom",
+ "style"
+ ],
+ "contributors": [],
+ "code": "const changeElementStyle = (element, styleObj) => {\n Object.entries(styleObj).forEach(([property, value]) => {\n element.style[property] = value;\n });\n};\n\n// Usage:\nconst element = document.querySelector('.my-element');\nchangeElementStyle(element, { color: 'red', backgroundColor: 'yellow' });\n",
+ "extension": "js"
+ },
+ {
+ "title": "Remove Element",
+ "description": "Removes a specified element from the DOM.",
+ "author": "axorax",
+ "tags": [
+ "dom",
+ "remove"
+ ],
+ "contributors": [],
+ "code": "const removeElement = (element) => {\n if (element && element.parentNode) {\n element.parentNode.removeChild(element);\n }\n};\n\n// Usage:\nconst element = document.querySelector('.my-element');\nremoveElement(element);\n",
+ "extension": "js"
+ }
+ ]
+ },
+ {
+ "name": "Function Utilities",
+ "snippets": [
+ {
+ "title": "Compose Functions",
+ "description": "Composes multiple functions into a single function, where the output of one function becomes the input of the next.",
+ "author": "axorax",
+ "tags": [
+ "function",
+ "compose"
+ ],
+ "contributors": [],
+ "code": "const compose = (...funcs) => (initialValue) => {\n return funcs.reduce((acc, func) => func(acc), initialValue);\n};\n\n// Usage:\nconst add2 = (x) => x + 2;\nconst multiply3 = (x) => x * 3;\nconst composed = compose(multiply3, add2);\ncomposed(5); // Returns: 17 ((5 * 3) + 2)\n",
+ "extension": "js"
+ },
+ {
+ "title": "Curry Function",
+ "description": "Transforms a function into its curried form.",
+ "author": "axorax",
+ "tags": [
+ "curry",
+ "function"
+ ],
+ "contributors": [],
+ "code": "const curry = (func) => {\n const curried = (...args) => {\n if (args.length >= func.length) {\n return func(...args);\n }\n return (...nextArgs) => curried(...args, ...nextArgs);\n };\n return curried;\n};\n\n// Usage:\nconst add = (a, b, c) => a + b + c;\nconst curriedAdd = curry(add);\ncurriedAdd(1)(2)(3); // Returns: 6\ncurriedAdd(1, 2)(3); // Returns: 6\n",
+ "extension": "js"
+ },
+ {
+ "title": "Debounce Function",
+ "description": "Delays a function execution until after a specified time.",
+ "author": "technoph1le",
+ "tags": [
+ "debounce",
+ "performance"
+ ],
+ "contributors": [],
+ "code": "const debounce = (func, delay) => {\n let timeout;\n\n return (...args) => {\n clearTimeout(timeout);\n timeout = setTimeout(() => func(...args), delay);\n };\n};\n\n// Usage:\nwindow.addEventListener(\n 'resize',\n debounce(() => console.log('Resized!'), 500), // Will only output after resizing has stopped for 500ms\n);\n",
+ "extension": "js"
+ },
+ {
+ "title": "Get Contrast Color",
+ "description": "Returns either black or white text color based on the brightness of the provided hex color.",
+ "author": "yaya12085",
+ "tags": [
+ "color",
+ "hex",
+ "contrast",
+ "brightness"
+ ],
+ "contributors": [],
+ "code": "const getContrastColor = (hexColor) => {\n // Expand short hex color to full format\n if (hexColor.length === 4) {\n hexColor = `#${hexColor[1]}${hexColor[1]}${hexColor[2]}${hexColor[2]}${hexColor[3]}${hexColor[3]}`;\n }\n const r = parseInt(hexColor.slice(1, 3), 16);\n const g = parseInt(hexColor.slice(3, 5), 16);\n const b = parseInt(hexColor.slice(5, 7), 16);\n const brightness = (r * 299 + g * 587 + b * 114) / 1000;\n return brightness >= 128 ? \"#000000\" : \"#FFFFFF\";\n};\n\n// Usage:\ngetContrastColor('#fff'); // Returns: #000000 (black)\ngetContrastColor('#123456'); // Returns: #FFFFFF (white)\ngetContrastColor('#ff6347'); // Returns: #000000 (black)\ngetContrastColor('#f4f'); // Returns: #000000 (black)\n",
+ "extension": "js"
+ },
+ {
+ "title": "Memoize Function",
+ "description": "Caches the result of a function based on its arguments to improve performance.",
+ "author": "axorax",
+ "tags": [
+ "memoization",
+ "optimization"
+ ],
+ "contributors": [],
+ "code": "const memoize = (func) => {\n const cache = new Map();\n return (...args) => {\n const key = JSON.stringify(args);\n if (cache.has(key)) {\n return cache.get(key);\n }\n const result = func(...args);\n cache.set(key, result);\n return result;\n };\n};\n\n// Usage:\nconst factorial = memoize((n) => (n <= 1 ? 1 : n * factorial(n - 1)));\nfactorial(5); // Returns: 120\nfactorial(5); // Returns: 120 (retrieved from cache)\n",
+ "extension": "js"
+ },
+ {
+ "title": "Once Function",
+ "description": "Ensures a function is only called once.",
+ "author": "axorax",
+ "tags": [
+ "function",
+ "once"
+ ],
+ "contributors": [],
+ "code": "const once = (func) => {\n let called = false;\n return (...args) => {\n if (!called) {\n called = true;\n return func(...args);\n }\n };\n};\n\n// Usage:\nconst initialize = once(() => console.log('Initialized!'));\ninitialize(); // Output: Initialized!\ninitialize(); // No output\n",
+ "extension": "js"
+ },
+ {
+ "title": "Rate Limit Function",
+ "description": "Limits how often a function can be executed within a given time window.",
+ "author": "axorax",
+ "tags": [
+ "function",
+ "rate-limiting"
+ ],
+ "contributors": [],
+ "code": "const rateLimit = (func, limit, timeWindow) => {\n let queue = [];\n setInterval(() => {\n if (queue.length) {\n const next = queue.shift();\n func(...next.args);\n }\n }, timeWindow);\n return (...args) => {\n if (queue.length < limit) {\n queue.push({ args });\n }\n };\n};\n\n// Usage:\nconst fetchData = () => console.log('Fetching data...');\nconst rateLimitedFetch = rateLimit(fetchData, 2, 1000);\nsetInterval(() => rateLimitedFetch(), 200); // Limits fetchData calls to twice a seconds\n",
+ "extension": "js"
+ },
+ {
+ "title": "Repeat Function Invocation",
+ "description": "Invokes a function a specified number of times.",
+ "author": "technoph1le",
+ "tags": [
+ "function",
+ "repeat"
+ ],
+ "contributors": [],
+ "code": "const times = (func, n) => {\n Array.from(Array(n)).forEach(() => {\n func();\n });\n};\n\n// Usage:\nconst randomFunction = () => console.log('Function called!');\ntimes(randomFunction, 3); // Logs 'Function called!' three times\n",
+ "extension": "js"
+ },
+ {
+ "title": "Sleep Function",
+ "description": "Waits for a specified amount of milliseconds before resolving.",
+ "author": "0xHouss",
+ "tags": [
+ "javascript",
+ "sleep",
+ "delay",
+ "utility",
+ "promises"
+ ],
+ "contributors": [],
+ "code": "const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\n// Usage:\nconsole.log('Hello');\nawait sleep(2000); // Waits for 2 seconds\nconsole.log('World!');\n",
+ "extension": "js"
+ },
+ {
+ "title": "Throttle Function",
+ "description": "Ensures a function is only called at most once in a specified time interval. Useful for optimizing events like scrolling or resizing.",
+ "author": "WizardOfDigits",
+ "tags": [
+ "throttle",
+ "performance",
+ "optimization"
+ ],
+ "contributors": [],
+ "code": "const throttle = (func, limit) => {\n let inThrottle;\n return (...args) => {\n if (!inThrottle) {\n func(...args);\n inThrottle = true;\n setTimeout(() => (inThrottle = false), limit);\n }\n };\n};\n\n// Usage:\n// Ensures the function can only be called once every 1000 milliseconds\nconst logScroll = throttle(() => console.log(\"Scroll event triggered\"), 1000);\n\n// Attach to scroll event\nwindow.addEventListener(\"scroll\", logScroll);\n",
+ "extension": "js"
+ }
+ ]
+ },
+ {
+ "name": "Local Storage",
+ "snippets": [
+ {
+ "title": "Add Item to localStorage",
+ "description": "Stores a value in localStorage under the given key.",
+ "author": "technoph1le",
+ "tags": [
+ "localStorage",
+ "storage"
+ ],
+ "contributors": [],
+ "code": "const addToLocalStorage = (key, value) => {\n localStorage.setItem(key, JSON.stringify(value));\n};\n\n// Usage:\naddToLocalStorage('user', { name: 'John', age: 30 });\n",
+ "extension": "js"
+ },
+ {
+ "title": "Check if Item Exists in localStorage",
+ "description": "Checks if a specific item exists in localStorage.",
+ "author": "axorax",
+ "tags": [
+ "localStorage",
+ "storage"
+ ],
+ "contributors": [],
+ "code": "const isItemInLocalStorage = (key) => {\n return localStorage.getItem(key) !== null;\n};\n\n// Usage:\nconsole.log(isItemInLocalStorage('user')); // Output: true or false\n",
+ "extension": "js"
+ },
+ {
+ "title": "Retrieve Item from localStorage",
+ "description": "Retrieves a value from localStorage by key and parses it.",
+ "author": "technoph1le",
+ "tags": [
+ "localStorage",
+ "storage"
+ ],
+ "contributors": [],
+ "code": "const getFromLocalStorage = (key) => {\n const item = localStorage.getItem(key);\n return item ? JSON.parse(item) : null;\n};\n\n// Usage:\ngetFromLocalStorage('user'); // Returns: { name: 'John', age: 30 }\n",
+ "extension": "js"
+ }
+ ]
+ },
+ {
+ "name": "Mathematical Functions",
+ "snippets": [
+ {
+ "title": "Combinations",
+ "description": "Calculates the number of combinations (denoted as C(n,r) or \"n choose r\"), which determines how many ways you can select r items from n items without considering the order.",
+ "author": "JanluOfficial",
+ "tags": [
+ "math",
+ "number-theory",
+ "algebra"
+ ],
+ "contributors": [],
+ "code": "function combinations(n, r) {\n if (n < 0 || r < 0 || n < r) {\n throw new Error('Invalid input: n and r must be non-negative and n must be greater than or equal to r.');\n }\n\n function factorial(x) {\n if (x === 0 || x === 1) return 1;\n let result = 1;\n for (let i = 2; i <= x; i++) {\n result *= i;\n }\n return result;\n }\n\n const numerator = factorial(n);\n const denominator = factorial(r) * factorial(n - r);\n return numerator / denominator;\n}\n\n// Usage:\ncombinations(24,22); // Returns: 276\ncombinations(5,3); // Returns: 10\n",
+ "extension": "js"
+ },
+ {
+ "title": "Cross Product",
+ "description": "Computes the cross product of two 3D vectors, which results in a vector perpendicular to both.",
+ "author": "JanluOfficial",
+ "tags": [
+ "math",
+ "vector-algebra"
+ ],
+ "contributors": [],
+ "code": "function crossProduct(a, b) {\n if (a.length !== 3 || b.length !== 3) {\n throw new Error('Vectors must be 3-dimensional');\n }\n\n return [\n a[1] * b[2] - a[2] * b[1],\n a[2] * b[0] - a[0] * b[2],\n a[0] * b[1] - a[1] * b[0]\n ];\n}\n\n// Usage:\ncrossProduct([1, 2, 3], [4, 5, 6]); // Returns: [-3, 6, -3] \n",
+ "extension": "js"
+ },
+ {
+ "title": "Dot Product",
+ "description": "Computes the dot product of two vectors, which is the sum of the products of corresponding elements.",
+ "author": "JanluOfficial",
+ "tags": [
+ "math",
+ "vector-algebra"
+ ],
+ "contributors": [],
+ "code": "function dotProduct(a, b) {\n if (a.length !== b.length) {\n throw new Error('Vectors must be of the same length');\n }\n\n return a.reduce((sum, value, index) => sum + value * b[index], 0);\n}\n\n// Usage:\ndotProduct([1, 2, 3], [4, 5, 6]); // Returns: 32\n",
+ "extension": "js"
+ },
+ {
+ "title": "Error function",
+ "description": "Computes the error function (erf(x)) for a given input x, which is a mathematical function used frequently in probability, statistics, and partial differential equations.",
+ "author": "JanluOfficial",
+ "tags": [
+ "math"
+ ],
+ "contributors": [],
+ "code": "function erf(x) {\n const sign = Math.sign(x);\n const absX = Math.abs(x);\n const t = 1 / (1 + 0.3275911 * absX);\n const a1 = 0.254829592, a2 = -0.284496736, a3 = 1.421413741, a4 = -1.453152027, a5 = 1.061405429;\n const poly = t * (a1 + t * (a2 + t * (a3 + t * (a4 + t * a5))));\n return sign * (1 - poly * Math.exp(-absX * absX));\n}\n\n// Usage:\nerf(-1); // Returns: -0.8427006897475899\nerf(1); // Returns: 0.8427006897475899\n",
+ "extension": "js"
+ },
+ {
+ "title": "Greatest Common Divisor",
+ "description": "Calculates the largest positive integer that divides each of the integers without leaving a remainder. Useful for calculating aspect ratios.",
+ "author": "JanluOfficial",
+ "tags": [
+ "math",
+ "division",
+ "number-theory",
+ "algebra"
+ ],
+ "contributors": [],
+ "code": "function gcd(a, b) {\n while (b !== 0) {\n let temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n}\n\n// Usage:\ngcd(1920, 1080); // Returns: 120\ngcd(1920, 1200); // Returns: 240\ngcd(5,12); // Returns: 1\n",
+ "extension": "js"
+ },
+ {
+ "title": "Least common multiple",
+ "description": "Computes the least common multiple (LCM) of two numbers 𝑎 and b. The LCM is the smallest positive integer that is divisible by both a and b.",
+ "author": "JanluOfficial",
+ "tags": [
+ "math",
+ "number-theory",
+ "algebra"
+ ],
+ "contributors": [],
+ "code": "function lcm(a, b) {\n function gcd(x, y) {\n while (y !== 0) {\n const temp = y;\n y = x % y;\n x = temp;\n }\n return Math.abs(x);\n }\n return Math.abs(a * b) / gcd(a, b);\n}\n\n// Usage:\nlcm(12,16); // Returns: 48\nlcm(8,20); // Returns: 40\nlcm(16,17); // Returns: 272\n",
+ "extension": "js"
+ },
+ {
+ "title": "Linear Mapping",
+ "description": "remaps a value from one range to another",
+ "author": "JasimAlrawie",
+ "tags": [
+ "math",
+ "number-theory",
+ "algebra"
+ ],
+ "contributors": [],
+ "code": "function linearMapping(value, minIn, maxIn, minOut, maxOut) {\n return (value - minIn) * (maxOut - minOut)/(maxIn - minIn) + minOut\n}\n\n// Usage:\nlinearMapping(value, 0, 1, 0, 255) // remaps the value from (0,1) to (0,255)\nlinearMapping(value, 0, PI*2, 0, 360) // remaps the value from rad to deg\nlinearMapping(value, -1, 1, 1, 8) // remaps the value from (-1,1) to (1,8)\n",
+ "extension": "js"
+ },
+ {
+ "title": "Matrix Multiplication",
+ "description": "Multiplies two matrices, where the number of columns in the first matrix equals the number of rows in the second.",
+ "author": "JanluOfficial",
+ "tags": [
+ "math",
+ "matrix-algebra"
+ ],
+ "contributors": [],
+ "code": "function matrixMultiply(A, B) {\n const rowsA = A.length;\n const colsA = A[0].length;\n const rowsB = B.length;\n const colsB = B[0].length;\n\n if (colsA !== rowsB) {\n throw new Error('Number of columns of A must equal the number of rows of B');\n }\n\n let result = Array.from({ length: rowsA }, () => Array(colsB).fill(0));\n\n for (let i = 0; i < rowsA; i++) {\n for (let j = 0; j < colsB; j++) {\n for (let k = 0; k < colsA; k++) {\n result[i][j] += A[i][k] * B[k][j];\n }\n }\n }\n\n return result;\n}\n\n// Usage:\nmatrixMultiply([[1, 2], [3, 4]], [[5, 6], [7, 8]]); // Returns: [[19, 22], [43, 50]]\n",
+ "extension": "js"
+ },
+ {
+ "title": "Modular Inverse",
+ "description": "Computes the modular multiplicative inverse of a number a under modulo m, which is the integer x such that (a*x) mod m=1.",
+ "author": "JanluOfficial",
+ "tags": [
+ "math",
+ "number-theory",
+ "algebra"
+ ],
+ "contributors": [],
+ "code": "function modInverse(a, m) {\n function extendedGCD(a, b) {\n if (b === 0) {\n return { gcd: a, x: 1, y: 0 };\n }\n const { gcd, x: x1, y: y1 } = extendedGCD(b, a % b);\n const x = y1;\n const y = x1 - Math.floor(a / b) * y1;\n return { gcd, x, y };\n }\n\n const { gcd, x } = extendedGCD(a, m);\n\n if (gcd !== 1) {\n return null;\n }\n\n return (x % m + m) % m;\n}\n\n// Usage:\nmodInverse(3, 26); // Returns: 9\nmodInverse(10, 17); // Returns: 12\nmodInverse(6, 9); // Returns: null\n",
+ "extension": "js"
+ },
+ {
+ "title": "Prime Number",
+ "description": "Checks if a number is a prime number or not.",
+ "author": "JanluOfficial",
+ "tags": [
+ "math",
+ "number-theory",
+ "algebra"
+ ],
+ "contributors": [],
+ "code": "function isPrime(num) {\n if (num <= 1) return false; // 0 and 1 are not prime numbers\n if (num <= 3) return true; // 2 and 3 are prime numbers\n if (num % 2 === 0 || num % 3 === 0) return false; // Exclude multiples of 2 and 3\n\n // Check divisors from 5 to √num, skipping multiples of 2 and 3\n for (let i = 5; i * i <= num; i += 6) {\n if (num % i === 0 || num % (i + 2) === 0) return false;\n }\n return true;\n}\n\n// Usage:\nisPrime(69); // Returns: false\nisPrime(17); // Returns: true\n",
+ "extension": "js"
+ }
+ ]
+ },
+ {
+ "name": "Number Formatting",
+ "snippets": [
+ {
+ "title": "Convert Number to Currency",
+ "description": "Converts a number to a currency format with a specific locale.",
+ "author": "axorax",
+ "tags": [
+ "number",
+ "currency"
+ ],
+ "contributors": [],
+ "code": "const convertToCurrency = (num, locale = 'en-US', currency = 'USD') => {\n return new Intl.NumberFormat(locale, {\n style: 'currency',\n currency: currency\n }).format(num);\n};\n\n// Usage:\nconvertToCurrency(1234567.89); // Returns: '$1,234,567.89'\nconvertToCurrency(987654.32, 'de-DE', 'EUR'); // Returns: '987.654,32 €'\n",
+ "extension": "js"
+ },
+ {
+ "title": "Convert Number to Roman Numerals",
+ "description": "Converts a number to Roman numeral representation.",
+ "author": "axorax",
+ "tags": [
+ "number",
+ "roman"
+ ],
+ "contributors": [],
+ "code": "const numberToRoman = (num) => {\n const romanNumerals = {\n 1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L',\n 90: 'XC', 100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M'\n };\n let result = '';\n Object.keys(romanNumerals).reverse().forEach(value => {\n while (num >= value) {\n result += romanNumerals[value];\n num -= value;\n }\n });\n return result;\n};\n\n// Usage:\nnumberToRoman(1994); // Returns: 'MCMXCIV'\nnumberToRoman(58); // Returns: 'LVIII'\n",
+ "extension": "js"
+ },
+ {
+ "title": "Convert to Scientific Notation",
+ "description": "Converts a number to scientific notation.",
+ "author": "axorax",
+ "tags": [
+ "number",
+ "scientific"
+ ],
+ "contributors": [],
+ "code": "const toScientificNotation = (num) => {\n if (isNaN(num)) {\n throw new Error('Input must be a number');\n }\n if (num === 0) {\n return '0e+0';\n }\n const exponent = Math.floor(Math.log10(Math.abs(num)));\n const mantissa = num / Math.pow(10, exponent);\n return `${mantissa.toFixed(2)}e${exponent >= 0 ? '+' : ''}${exponent}`;\n};\n\n// Usage:\ntoScientificNotation(12345); // Returns: '1.23e+4'\ntoScientificNotation(0.0005678); // Returns: '5.68e-4'\ntoScientificNotation(1000); // Returns: '1.00e+3'\ntoScientificNotation(0); // Returns: '0e+0'\ntoScientificNotation(-54321); // Returns: '-5.43e+4'\n",
+ "extension": "js"
+ },
+ {
+ "title": "Format File Size",
+ "description": "Converts bytes into human-readable file size format.",
+ "author": "jjcantu",
+ "tags": [
+ "format",
+ "size"
+ ],
+ "contributors": [],
+ "code": "function formatFileSize(bytes) {\n if (bytes === 0) return '0 Bytes';\n \n const k = 1024;\n const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n \n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n}\n\n// Usage:\nconsole.log(formatFileSize(1234)); // Output: \"1.21 KB\"\nconsole.log(formatFileSize(1234567)); // Output: \"1.18 MB\"\n",
+ "extension": "js"
+ },
+ {
+ "title": "Format Number with Commas",
+ "description": "Formats a number with commas for better readability (e.g., 1000 -> 1,000).",
+ "author": "axorax",
+ "tags": [
+ "number",
+ "format"
+ ],
+ "contributors": [],
+ "code": "const formatNumberWithCommas = (num) => {\n return num.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n};\n\n// Usage:\nformatNumberWithCommas(1000); // Returns: '1,000'\nformatNumberWithCommas(1234567); // Returns: '1,234,567'\nformatNumberWithCommas(987654321); // Returns: '987,654,321'\n",
+ "extension": "js"
+ },
+ {
+ "title": "Number Formatter",
+ "description": "Formats a number with suffixes (K, M, B, etc.).",
+ "author": "realvishalrana",
+ "tags": [
+ "number",
+ "format"
+ ],
+ "contributors": [],
+ "code": "const nFormatter = (num) => {\n if (!num) return;\n num = parseFloat(num.toString().replace(/[^0-9.]/g, ''));\n const suffixes = ['', 'K', 'M', 'B', 'T', 'P', 'E'];\n let index = 0;\n while (num >= 1000 && index < suffixes.length - 1) {\n num /= 1000;\n index++;\n }\n return num.toFixed(2).replace(/\\.0+$|(\\.[0-9]*[1-9])0+$/, '$1') + suffixes[index];\n};\n\n// Usage:\nnFormatter(1234567); // Returns: '1.23M'\n",
+ "extension": "js"
+ },
+ {
+ "title": "Number to Words Converter",
+ "description": "Converts a number to its word representation in English.",
+ "author": "axorax",
+ "tags": [
+ "number",
+ "words"
+ ],
+ "contributors": [],
+ "code": "const numberToWords = (num) => {\n const below20 = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'];\n const tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];\n const above1000 = ['Hundred', 'Thousand', 'Million', 'Billion'];\n if (num < 20) return below20[num];\n let words = '';\n for (let i = 0; num > 0; i++) {\n if (i > 0 && num % 1000 !== 0) words = above1000[i] + ' ' + words;\n if (num % 100 >= 20) {\n words = tens[Math.floor(num / 10)] + ' ' + words;\n num %= 10;\n }\n if (num < 20) words = below20[num] + ' ' + words;\n num = Math.floor(num / 100);\n }\n return words.trim();\n};\n\n// Usage:\nnumberToWords(123); // Returns: 'One Hundred Twenty Three'\nnumberToWords(2045); // Returns: 'Two Thousand Forty Five'\n",
+ "extension": "js"
+ }
+ ]
+ },
+ {
+ "name": "Object Manipulation",
+ "snippets": [
+ {
+ "title": "Check if Object is Empty",
+ "description": "Checks whether an object has no own enumerable properties.",
+ "author": "axorax",
+ "tags": [
+ "object",
+ "check",
+ "empty"
+ ],
+ "contributors": [],
+ "code": "function isEmptyObject(obj) {\n return Object.keys(obj).length === 0;\n}\n\n// Usage:\nisEmptyObject({}); // Returns: true\nisEmptyObject({ a: 1 }); // Returns: false\n",
+ "extension": "js"
+ },
+ {
+ "title": "Compare Two Objects Shallowly",
+ "description": "Compares two objects shallowly and returns whether they are equal.",
+ "author": "axorax",
+ "tags": [
+ "object",
+ "compare",
+ "shallow"
+ ],
+ "contributors": [],
+ "code": "function shallowEqual(obj1, obj2) {\n const keys1 = Object.keys(obj1);\n const keys2 = Object.keys(obj2);\n if (keys1.length !== keys2.length) return false;\n return keys1.every(key => obj1[key] === obj2[key]);\n}\n\n// Usage:\nconst obj1 = { a: 1, b: 2 };\nconst obj2 = { a: 1, b: 2 };\nconst obj3 = { a: 1, b: 3 };\nshallowEqual(obj1, obj2); // Returns: true\nshallowEqual(obj1, obj3); // Returns: false\n",
+ "extension": "js"
+ },
+ {
+ "title": "Convert Object to Query String",
+ "description": "Converts an object to a query string for use in URLs.",
+ "author": "axorax",
+ "tags": [
+ "object",
+ "query string",
+ "url"
+ ],
+ "contributors": [],
+ "code": "function toQueryString(obj) {\n return Object.entries(obj)\n .map(([key, value]) => encodeURIComponent(key) + '=' + encodeURIComponent(value))\n .join('&');\n}\n\n// Usage:\nconst params = { search: 'test', page: 1 };\ntoQueryString(params); // Returns: 'search=test&page=1'\n",
+ "extension": "js"
+ },
+ {
+ "title": "Count Properties in Object",
+ "description": "Counts the number of own properties in an object.",
+ "author": "axorax",
+ "tags": [
+ "object",
+ "count",
+ "properties"
+ ],
+ "contributors": [],
+ "code": "function countProperties(obj) {\n return Object.keys(obj).length;\n}\n\n// Usage:\nconst obj = { a: 1, b: 2, c: 3 };\ncountProperties(obj); // Returns: 3\n",
+ "extension": "js"
+ },
+ {
+ "title": "Deep Clone Object",
+ "description": "Creates a deep copy of an object or array without reference.",
+ "author": "jjcantu",
+ "tags": [
+ "object",
+ "clone"
+ ],
+ "contributors": [],
+ "code": "function deepClone(obj) {\n if (obj === null || typeof obj !== 'object') return obj;\n \n const clone = Array.isArray(obj) ? [] : {};\n \n for (let key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clone[key] = deepClone(obj[key]);\n }\n }\n \n return clone;\n}\n\n// Usage:\nconst original = { a: 1, b: { c: 2 }, d: [1, 2, 3] };\nconst cloned = deepClone(original);\nconsole.log(cloned); // Output: 'original' but cloned\n",
+ "extension": "js"
+ },
+ {
+ "title": "Filter Object",
+ "description": "Filter out entries in an object where the value is falsy, including empty strings, empty objects, null, and undefined.",
+ "author": "realvishalrana",
+ "tags": [
+ "object",
+ "filter"
+ ],
+ "contributors": [],
+ "code": "export const filterObject = (object = {}) =>\n Object.fromEntries(\n Object.entries(object)\n .filter(([key, value]) => value !== null && value !== undefined && value !== '' && (typeof value !== 'object' || Object.keys(value).length > 0))\n );\n\n// Usage:\nconst obj1 = { a: 1, b: null, c: undefined, d: 4, e: '', f: {} };\nfilterObject(obj1); // Returns: { a: 1, d: 4 }\n\nconst obj2 = { x: 0, y: false, z: 'Hello', w: [] };\nfilterObject(obj2); // Returns: { z: 'Hello' }\n\nconst obj3 = { name: 'John', age: null, address: { city: 'New York' }, phone: '' };\nfilterObject(obj3); // Returns: { name: 'John', address: { city: 'New York' } }\n\nconst obj4 = { a: 0, b: '', c: false, d: {}, e: 'Valid' };\nfilterObject(obj4); // Returns: { e: 'Valid' }\n",
+ "extension": "js"
+ },
+ {
+ "title": "Flatten Nested Object",
+ "description": "Flattens a nested object into a single-level object with dot notation for keys.",
+ "author": "axorax",
+ "tags": [
+ "object",
+ "flatten"
+ ],
+ "contributors": [],
+ "code": "function flattenObject(obj, prefix = '') {\n return Object.keys(obj).reduce((acc, key) => {\n const fullPath = prefix ? `${prefix}.${key}` : key;\n if (typeof obj[key] === 'object' && obj[key] !== null) {\n Object.assign(acc, flattenObject(obj[key], fullPath));\n } else {\n acc[fullPath] = obj[key];\n }\n return acc;\n }, {});\n}\n\n// Usage:\nconst nestedObj = { a: { b: { c: 1 }, d: 2 }, e: 3 };\nflattenObject(nestedObj); // Returns: { 'a.b.c': 1, 'a.d': 2, e: 3 }\n",
+ "extension": "js"
+ },
+ {
+ "title": "Freeze Object",
+ "description": "Freezes an object to make it immutable.",
+ "author": "axorax",
+ "tags": [
+ "object",
+ "freeze",
+ "immutable"
+ ],
+ "contributors": [],
+ "code": "function freezeObject(obj) {\n return Object.freeze(obj);\n}\n\n// Usage:\nconst obj = { a: 1, b: 2 };\nconst frozenObj = freezeObject(obj);\nfrozenObj.a = 42; // This will fail silently in strict mode.\nfrozenObj.a; // Returns: 1\n",
+ "extension": "js"
+ },
+ {
+ "title": "Get Nested Value",
+ "description": "Retrieves the value at a given path in a nested object.",
+ "author": "realvishalrana",
+ "tags": [
+ "object",
+ "nested"
+ ],
+ "contributors": [],
+ "code": "const getNestedValue = (obj, path) => {\n const keys = path.split('.');\n return keys.reduce((currentObject, key) => {\n return currentObject && typeof currentObject === 'object' ? currentObject[key] : undefined;\n }, obj);\n};\n\n// Usage:\nconst obj = { a: { b: { c: 42 } } };\ngetNestedValue(obj, 'a.b.c'); // Returns: 42\n",
+ "extension": "js"
+ },
+ {
+ "title": "Invert Object Keys and Values",
+ "description": "Creates a new object by swapping keys and values of the given object.",
+ "author": "axorax",
+ "tags": [
+ "object",
+ "invert"
+ ],
+ "contributors": [],
+ "code": "function invertObject(obj) {\n return Object.fromEntries(\n Object.entries(obj).map(([key, value]) => [value, key])\n );\n}\n\n// Usage:\nconst obj = { a: 1, b: 2, c: 3 };\ninvertObject(obj); // Returns: { '1': 'a', '2': 'b', '3': 'c' }\n",
+ "extension": "js"
+ },
+ {
+ "title": "Merge Objects Deeply",
+ "description": "Deeply merges two or more objects, including nested properties.",
+ "author": "axorax",
+ "tags": [
+ "object",
+ "merge",
+ "deep"
+ ],
+ "contributors": [],
+ "code": "function deepMerge(...objects) {\n return objects.reduce((acc, obj) => {\n Object.keys(obj).forEach(key => {\n if (typeof obj[key] === 'object' && obj[key] !== null) {\n acc[key] = deepMerge(acc[key] || {}, obj[key]);\n } else {\n acc[key] = obj[key];\n }\n });\n return acc;\n }, {});\n}\n\n// Usage:\nconst obj1 = { a: 1, b: { c: 2 } };\nconst obj2 = { b: { d: 3 }, e: 4 };\ndeepMerge(obj1, obj2); // Returns: { a: 1, b: { c: 2, d: 3 }, e: 4 }\n",
+ "extension": "js"
+ },
+ {
+ "title": "Omit Keys from Object",
+ "description": "Creates a new object with specific keys omitted.",
+ "author": "axorax",
+ "tags": [
+ "object",
+ "omit"
+ ],
+ "contributors": [],
+ "code": "function omitKeys(obj, keys) {\n return Object.fromEntries(\n Object.entries(obj).filter(([key]) => !keys.includes(key))\n );\n}\n\n// Usage:\nconst obj = { a: 1, b: 2, c: 3 };\nomitKeys(obj, ['b', 'c']); // Returns: { a: 1 }\n",
+ "extension": "js"
+ },
+ {
+ "title": "Pick Keys from Object",
+ "description": "Creates a new object with only the specified keys.",
+ "author": "axorax",
+ "tags": [
+ "object",
+ "pick"
+ ],
+ "contributors": [],
+ "code": "function pickKeys(obj, keys) {\n return Object.fromEntries(\n Object.entries(obj).filter(([key]) => keys.includes(key))\n );\n}\n\n// Usage:\nconst obj = { a: 1, b: 2, c: 3 };\npickKeys(obj, ['a', 'c']); // Returns: { a: 1, c: 3 }\n",
+ "extension": "js"
+ },
+ {
+ "title": "Unique By Key",
+ "description": "Filters an array of objects to only include unique objects by a specified key.",
+ "author": "realvishalrana",
+ "tags": [
+ "array",
+ "unique"
+ ],
+ "contributors": [],
+ "code": "const uniqueByKey = (key, arr) =>\n arr.filter((obj, index, self) => index === self.findIndex((t) => t?.[key] === obj?.[key]));\n\n// Usage:\nconst arr = [\n { id: 1, name: 'John' },\n { id: 2, name: 'Jane' },\n { id: 1, name: 'John' }\n];\nuniqueByKey('id', arr); // Returns: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]\n",
+ "extension": "js"
+ }
+ ]
+ },
+ {
+ "name": "String Manipulation",
+ "snippets": [
+ {
+ "title": "Capitalize String",
+ "description": "Capitalizes the first letter of a string.",
+ "author": "technoph1le",
+ "tags": [
+ "string",
+ "capitalize"
+ ],
+ "contributors": [],
+ "code": "function capitalize(str) {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n// Usage:\ncapitalize('hello'); // Returns: 'Hello'\n",
+ "extension": "js"
+ },
+ {
+ "title": "Check if String is a Palindrome",
+ "description": "Checks whether a given string is a palindrome.",
+ "author": "axorax",
+ "tags": [
+ "check",
+ "palindrome",
+ "string"
+ ],
+ "contributors": [],
+ "code": "function isPalindrome(str) {\n const cleanStr = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();\n return cleanStr === cleanStr.split('').reverse().join('');\n}\n\n// Example usage:\nisPalindrome('A man, a plan, a canal, Panama'); // Returns: true\n",
+ "extension": "js"
+ },
+ {
+ "title": "Convert String to Camel Case",
+ "description": "Converts a given string into camelCase.",
+ "author": "aumirza",
+ "tags": [
+ "string",
+ "case",
+ "camelCase"
+ ],
+ "contributors": [],
+ "code": "function toCamelCase(str) {\n return str.replace(/\\W+(.)/g, (match, chr) => chr.toUpperCase());\n}\n\n// Usage:\ntoCamelCase('hello world test'); // Returns: 'helloWorldTest'\n",
+ "extension": "js"
+ },
+ {
+ "title": "Convert String to Param Case",
+ "description": "Converts a given string into param-case.",
+ "author": "aumirza",
+ "tags": [
+ "string",
+ "case",
+ "paramCase"
+ ],
+ "contributors": [],
+ "code": "function toParamCase(str) {\n return str.toLowerCase().replace(/\\s+/g, '-');\n}\n\n// Usage:\ntoParamCase('Hello World Test'); // Returns: 'hello-world-test'\n",
+ "extension": "js"
+ },
+ {
+ "title": "Convert String to Pascal Case",
+ "description": "Converts a given string into Pascal Case.",
+ "author": "aumirza",
+ "tags": [
+ "string",
+ "case",
+ "pascalCase"
+ ],
+ "contributors": [],
+ "code": "function toPascalCase(str) {\n return str.replace(/\\b\\w/g, (s) => s.toUpperCase()).replace(/\\W+(.)/g, (match, chr) => chr.toUpperCase());\n}\n\n// Usage:\ntoPascalCase('hello world test'); // Returns: 'HelloWorldTest'\n",
+ "extension": "js"
+ },
+ {
+ "title": "Convert String to Snake Case",
+ "description": "Converts a given string into snake_case.",
+ "author": "axorax",
+ "tags": [
+ "string",
+ "case",
+ "snake_case"
+ ],
+ "contributors": [],
+ "code": "function toSnakeCase(str) {\n return str.replace(/([a-z])([A-Z])/g, '$1_$2')\n .replace(/\\s+/g, '_')\n .toLowerCase();\n}\n\n// Usage:\ntoSnakeCase('Hello World Test'); // Returns: 'hello_world_test'\n",
+ "extension": "js"
+ },
+ {
+ "title": "Convert String to Title Case",
+ "description": "Converts a given string into Title Case.",
+ "author": "aumirza",
+ "tags": [
+ "string",
+ "case",
+ "titleCase"
+ ],
+ "contributors": [],
+ "code": "function toTitleCase(str) {\n return str.toLowerCase().replace(/\\b\\w/g, (s) => s.toUpperCase());\n}\n\n// Usage:\ntoTitleCase('hello world test'); // Returns: 'Hello World Test'\n",
+ "extension": "js"
+ },
+ {
+ "title": "Convert Tabs to Spaces",
+ "description": "Converts all tab characters in a string to spaces.",
+ "author": "axorax",
+ "tags": [
+ "string",
+ "tabs",
+ "spaces"
+ ],
+ "contributors": [],
+ "code": "function tabsToSpaces(str, spacesPerTab = 4) {\n return str.replace(/\\t/g, ' '.repeat(spacesPerTab));\n}\n\n// Usage:\ntabsToSpaces('Hello\\tWorld', 2); // Returns: 'Hello World'\n",
+ "extension": "js"
+ },
+ {
+ "title": "Count Words in a String",
+ "description": "Counts the number of words in a string.",
+ "author": "axorax",
+ "tags": [
+ "string",
+ "manipulation",
+ "word count",
+ "count"
+ ],
+ "contributors": [],
+ "code": "function countWords(str) {\n return str.trim().split(/\\s+/).length;\n}\n\n// Usage:\ncountWords('Hello world! This is a test.'); // Returns: 6\n",
+ "extension": "js"
+ },
+ {
+ "title": "Data with Prefix",
+ "description": "Adds a prefix and postfix to data, with a fallback value.",
+ "author": "realvishalrana",
+ "tags": [
+ "data",
+ "prefix",
+ "postfix",
+ "format"
+ ],
+ "contributors": [],
+ "code": "const dataWithPrefix = (data, fallback = '-', prefix = '', postfix = '') => {\n return data ? `${prefix}${data}${postfix}` : fallback;\n};\n\n// Usage:\ndataWithPrefix('123', '-', '(', ')'); // Returns: '(123)'\ndataWithPrefix('', '-', '(', ')'); // Returns: '-'\ndataWithPrefix('Hello', 'N/A', 'Mr. ', ''); // Returns: 'Mr. Hello'\ndataWithPrefix(null, 'N/A', 'Mr. ', ''); // Returns: 'N/A'\n",
+ "extension": "js"
+ },
+ {
+ "title": "Extract Initials from Name",
+ "description": "Extracts and returns the initials from a full name.",
+ "author": "axorax",
+ "tags": [
+ "string",
+ "initials",
+ "name"
+ ],
+ "contributors": [],
+ "code": "function getInitials(name) {\n return name.split(' ').map(part => part.charAt(0).toUpperCase()).join('');\n}\n\n// Usage:\ngetInitials('John Doe'); // Returns: 'JD'\n",
+ "extension": "js"
+ },
+ {
+ "title": "Generate UUID",
+ "description": "Generates a UUID (v4) string.",
+ "author": "jjcantu",
+ "tags": [
+ "uuid",
+ "generate",
+ "string"
+ ],
+ "contributors": [],
+ "code": "function generateUUID() {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n const r = Math.random() * 16 | 0;\n const v = c === 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n}\n\n// Usage:\nconsole.log(generateUUID()); // Output: \"a1b2c3d4-e5f6-4g7h-8i9j-k0l1m2n3o4p5\"\n",
+ "extension": "js"
+ },
+ {
+ "title": "Mask Sensitive Information",
+ "description": "Masks parts of a sensitive string, like a credit card or email address.",
+ "author": "axorax",
+ "tags": [
+ "string",
+ "mask",
+ "sensitive"
+ ],
+ "contributors": [],
+ "code": "function maskSensitiveInfo(str, visibleCount = 4, maskChar = '*') {\n return str.slice(0, visibleCount) + maskChar.repeat(Math.max(0, str.length - visibleCount));\n}\n\n// Usage:\nmaskSensitiveInfo('123456789', 4); // Returns: '1234*****'\nmaskSensitiveInfo('example@mail.com', 2, '#'); // Returns: 'ex#############'\n",
+ "extension": "js"
+ },
+ {
+ "title": "Pad String on Both Sides",
+ "description": "Pads a string on both sides with a specified character until it reaches the desired length.",
+ "author": "axorax",
+ "tags": [
+ "string",
+ "pad",
+ "manipulation"
+ ],
+ "contributors": [],
+ "code": "function padString(str, length, char = ' ') {\n const totalPad = length - str.length;\n const padStart = Math.floor(totalPad / 2);\n const padEnd = totalPad - padStart;\n return char.repeat(padStart) + str + char.repeat(padEnd);\n}\n\n// Usage:\npadString('hello', 10, '*'); // Returns: '**hello***'\n",
+ "extension": "js"
+ },
+ {
+ "title": "Random string",
+ "description": "Generates a random string of characters of a certain length",
+ "author": "kruimol",
+ "tags": [
+ "function",
+ "random"
+ ],
+ "contributors": [],
+ "code": "function makeid(length, characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {\n return Array.from({ length }, () => characters.charAt(Math.floor(Math.random() * characters.length))).join('');\n}\n\nmakeid(3); // Returns: gDs (Random)\nmakeid(5, \"1234\" /* (optional) */); // Returns: \"35453\" (Random)\n",
+ "extension": "js"
+ },
+ {
+ "title": "Remove All Whitespace",
+ "description": "Removes all whitespace from a string.",
+ "author": "axorax",
+ "tags": [
+ "string",
+ "whitespace"
+ ],
+ "contributors": [],
+ "code": "function removeWhitespace(str) {\n return str.replace(/\\s+/g, '');\n}\n\n// Usage:\nremoveWhitespace('Hello world!'); // Returns: 'Helloworld!'\n",
+ "extension": "js"
+ },
+ {
+ "title": "Remove Vowels from a String",
+ "description": "Removes all vowels from a given string.",
+ "author": "axorax",
+ "tags": [
+ "string",
+ "remove",
+ "vowels"
+ ],
+ "contributors": [],
+ "code": "function removeVowels(str) {\n return str.replace(/[aeiouAEIOU]/g, '');\n}\n\n// Usage:\nremoveVowels('Hello World'); // Returns: 'Hll Wrld'\n",
+ "extension": "js"
+ },
+ {
+ "title": "Reverse String",
+ "description": "Reverses the characters in a string.",
+ "author": "technoph1le",
+ "tags": [
+ "string",
+ "reverse"
+ ],
+ "contributors": [],
+ "code": "const reverseString = (str) => str.split('').reverse().join('');\n\n// Usage:\nreverseString('hello'); // Returns: 'olleh'\n",
+ "extension": "js"
+ },
+ {
+ "title": "Slugify String",
+ "description": "Converts a string into a URL-friendly slug format.",
+ "author": "technoph1le",
+ "tags": [
+ "string",
+ "slug"
+ ],
+ "contributors": [],
+ "code": "const slugify = (string, separator = \"-\") => {\n return string\n .toString() // Cast to string (optional)\n .toLowerCase() // Convert the string to lowercase letters\n .trim() // Remove whitespace from both sides of a string (optional)\n .replace(/\\s+/g, separator) // Replace spaces with {separator}\n .replace(/[^\\w\\-]+/g, \"\") // Remove all non-word chars\n .replace(/\\_/g, separator) // Replace _ with {separator}\n .replace(/\\-\\-+/g, separator) // Replace multiple - with single {separator}\n .replace(/\\-$/g, \"\"); // Remove trailing -\n};\n\n// Usage:\nconst title = \"Hello, World! This is a Test.\";\nslugify(title); // Returns: 'hello-world-this-is-a-test'\nslugify(title, \"_\"); // Returns: 'hello_world_this_is_a_test'\n",
+ "extension": "js"
+ },
+ {
+ "title": "Truncate Text",
+ "description": "Truncates the text to a maximum length and appends '...' if the text exceeds the maximum length.",
+ "author": "realvishalrana",
+ "tags": [
+ "string",
+ "truncate",
+ "text"
+ ],
+ "contributors": [],
+ "code": "const truncateText = (text = '', maxLength = 50) => {\n return `${text.slice(0, maxLength)}${text.length >= maxLength ? '...' : ''}`;\n};\n\n// Usage:\nconst title = \"Hello, World! This is a Test.\";\ntruncateText(title); // Returns: 'Hello, World! This is a Test.'\ntruncateText(title, 10); // Returns: 'Hello, Wor...'\n",
+ "extension": "js"
+ }
+ ]
+ }
+]
\ No newline at end of file
diff --git a/backend/data/consolidated/python--fastapi.json b/backend/data/consolidated/python--fastapi.json
index 333e5cf8..2cea01cb 100644
--- a/backend/data/consolidated/python--fastapi.json
+++ b/backend/data/consolidated/python--fastapi.json
@@ -1,16 +1,21 @@
[
- {
- "name": "Basics",
- "snippets": [
- {
- "title": "Hello, World!",
- "description": "Returns Hello, World! when it recives a GET request made to the root endpoint.",
- "author": "ACR1209",
- "tags": ["printing", "hello-world", "web", "api"],
- "contributors": [],
- "code": "from typing import Union\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n\n@app.get(\"/\")\ndef read_root():\n return {\"msg\": \"Hello, World!\"}\n\n# Usage: \n# -> Go to http://127.0.0.1:8000/ and you'll see {\"msg\", \"Hello, World!\"}\n",
- "extension": "py"
- }
- ]
- }
-]
+ {
+ "name": "Basics",
+ "snippets": [
+ {
+ "title": "Hello, World!",
+ "description": "Returns Hello, World! when it recives a GET request made to the root endpoint.",
+ "author": "ACR1209",
+ "tags": [
+ "printing",
+ "hello-world",
+ "web",
+ "api"
+ ],
+ "contributors": [],
+ "code": "from typing import Union\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n\n@app.get(\"/\")\ndef read_root():\n return {\"msg\": \"Hello, World!\"}\n\n# Usage: \n# -> Go to http://127.0.0.1:8000/ and you'll see {\"msg\", \"Hello, World!\"}\n",
+ "extension": "py"
+ }
+ ]
+ }
+]
\ No newline at end of file
diff --git a/backend/data/consolidated/python--tkinter.json b/backend/data/consolidated/python--tkinter.json
index f88ee116..412122ae 100644
--- a/backend/data/consolidated/python--tkinter.json
+++ b/backend/data/consolidated/python--tkinter.json
@@ -1,188 +1,254 @@
[
- {
- "name": "Basics",
- "snippets": [
- {
- "title": "Display a Pillow Image",
- "description": "Use Pillow to show an image in a Tkinter window.",
- "author": "Legopitstop",
- "tags": ["app", "hello-world", "object-oriented"],
- "contributors": [],
- "code": "from tkinter import Tk, Label\nfrom PIL import Image, ImageDraw, ImageTk\n\n\nclass App(Tk):\n def __init__(self):\n Tk.__init__(self)\n self.geometry(\"200x200\")\n\n # PhotoImage must be global or be assigned to a class or it will be garbage collected.\n self.photo = ImageTk.PhotoImage(self.make_image())\n lbl = Label(self, image=self.photo)\n lbl.pack(expand=1)\n\n def make_image(self):\n width, height = 200, 200\n image = Image.new(\"RGB\", (width, height), \"white\")\n\n # Create a drawing context\n draw = ImageDraw.Draw(image)\n\n # Draw a circle\n radius = 80\n center = (width // 2, height // 2)\n draw.ellipse(\n [\n (center[0] - radius, center[1] - radius),\n (center[0] + radius, center[1] + radius),\n ],\n fill=\"red\",\n outline=\"black\",\n width=3,\n )\n return image\n\n\n# Usage:\nroot = App()\nroot.mainloop()\n\n",
- "extension": "py"
- },
- {
- "title": "Hello, World!",
- "description": "Creates a basic Tkinter window with a \"Hello, World!\" label.",
- "author": "Legopitstop",
- "tags": ["app", "hello-world", "object-oriented"],
- "contributors": [],
- "code": "from tkinter import Tk, Label\n\nclass App(Tk):\n def __init__(self):\n Tk.__init__(self)\n self.geometry(\"200x200\")\n\n self.lbl = Label(self, text='Hello, World!')\n self.lbl.pack(expand=1)\n\n# Usage:\nroot = App()\nroot.mainloop()\n",
- "extension": "py"
- }
- ]
- },
- {
- "name": "Entry Validation",
- "snippets": [
- {
- "title": "Allow Alphanumeric",
- "description": "A validation function to allow alphanumeric characters.",
- "author": "Legopitstop",
- "tags": ["validation", "alphanumeric"],
- "contributors": [],
- "code": "from tkinter import Tk, Entry\n\n\ndef allow_alphanumeric(value):\n return value.isalnum() or value == \"\"\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_alphanumeric)\nEntry(root, validate=\"key\", validatecommand=(reg, \"%P\")).pack()\n\nroot.mainloop()\n",
- "extension": "py"
- },
- {
- "title": "Allow Decimal",
- "description": "A validation function to allow only decimal numbers.",
- "author": "Legopitstop",
- "tags": ["validation", "decimals"],
- "contributors": [],
- "code": "from tkinter import Tk, Entry\n\n\ndef allow_decimal(action, value):\n if action == \"1\":\n if value == \"\":\n return True\n try:\n float(value)\n return True\n except ValueError:\n return False\n return True\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_decimal)\nEntry(root, validate=\"key\", validatecommand=(reg, \"%d\", \"%P\")).pack()\n\nroot.mainloop()\n",
- "extension": "py"
- },
- {
- "title": "Allow Digits with A Max Length",
- "description": "A validation function to allow only digits with a specified maximum length.",
- "author": "Legopitstop",
- "tags": ["validation", "max", "length"],
- "contributors": [],
- "code": "from tkinter import Tk, Entry\n\n\ndef allow_digits_with_max_length(action, value, max_length):\n if action == \"1\":\n return value == \"\" or (value.isdigit() and len(value) <= int(max_length))\n return True\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_digits_with_max_length)\n# 4 is the max length\nEntry(root, validate=\"key\", validatecommand=(reg, \"%d\", \"%P\", 4)).pack()\n\nroot.mainloop()\n",
- "extension": "py"
- },
- {
- "title": "Allow Lowercase",
- "description": "A validation function to allow only lowercase alphabetic characters.",
- "author": "Legopitstop",
- "tags": ["validation", "lowercase"],
- "contributors": [],
- "code": "from tkinter import Tk, Entry\n\n\ndef allow_lowercase(value):\n return value.islower() or value == \"\"\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_lowercase)\nEntry(root, validate=\"key\", validatecommand=(reg, \"%P\")).pack()\n\nroot.mainloop()\n",
- "extension": "py"
- },
- {
- "title": "Allow Negative Integers",
- "description": "A validation function to allow only negative integers.",
- "author": "Legopitstop",
- "tags": ["validation", "negative", "integers"],
- "contributors": [],
- "code": "from tkinter import Tk, Entry\n\n\ndef allow_negative_integers(value):\n return (\n value in (\"\", \"-\") or value.startswith(\"-\") and value[1:].isdigit()\n if value\n else True\n )\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_negative_integers)\nEntry(root, validate=\"key\", validatecommand=(reg, \"%P\")).pack()\n\nroot.mainloop()\n",
- "extension": "py"
- },
- {
- "title": "Allow Numbers in Range",
- "description": "A validation function to allow only numbers within a specified range.",
- "author": "Legopitstop",
- "tags": ["validation", "number", "range"],
- "contributors": [],
- "code": "from tkinter import Tk, Entry\n\n\ndef allow_numbers_in_range(action, value, min_value, max_value):\n if action == \"1\": \n try:\n num = float(value)\n return float(min_value) <= num <= float(max_value)\n except ValueError:\n return False\n return True\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_numbers_in_range)\n# 0 is the minimum value\n# 10 is the maximum value\nEntry(root, validate=\"key\", validatecommand=(reg, \"%d\", \"%P\", 0, 10)).pack()\n\nroot.mainloop()\n",
- "extension": "py"
- },
- {
- "title": "Allow Only Alphabets",
- "description": "A validation function to allow only alphabetic characters.",
- "author": "Legopitstop",
- "tags": ["validation", "alphabets"],
- "contributors": [],
- "code": "from tkinter import Tk, Entry\n\n\ndef allow_only_alphabets(value):\n return value.isalpha() or value == \"\"\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_only_alphabets)\nEntry(root, validate=\"key\", validatecommand=(reg, \"%P\")).pack()\n\nroot.mainloop()\n",
- "extension": "py"
- },
- {
- "title": "Allow Only Digits",
- "description": "A validation function to allow only digits.",
- "author": "Legopitstop",
- "tags": ["validation", "digits"],
- "contributors": [],
- "code": "from tkinter import Tk, Entry\n\n\ndef allow_only_digits(value):\n return value.isdigit() or value == \"\"\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_only_digits)\nEntry(root, validate=\"key\", validatecommand=(reg, \"%P\")).pack()\n\nroot.mainloop()\n",
- "extension": "py"
- },
- {
- "title": "Allow Positive Integers",
- "description": "A validation function to allow only positive integers.",
- "author": "Legopitstop",
- "tags": ["validation", "positive", "integers"],
- "contributors": [],
- "code": "from tkinter import Tk, Entry\n\n\ndef allow_positive_integers(value):\n return value.isdigit() and (value == \"\" or int(value) > 0)\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_positive_integers)\nEntry(root, validate=\"key\", validatecommand=(reg, \"%P\")).pack()\n\nroot.mainloop()\n",
- "extension": "py"
- },
- {
- "title": "Allow signed Decimals",
- "description": "A validation function to allow only signed decimal numbers.",
- "author": "Legopitstop",
- "tags": ["validation", "signed", "decimals"],
- "contributors": [],
- "code": "from tkinter import Tk, Entry\n\n\ndef allow_signed_decimals(action, value):\n if action == \"1\":\n try:\n if value in (\"\", \"-\"):\n return True\n float(value)\n return True\n except ValueError:\n return False\n return True\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_signed_decimals)\nEntry(root, validate=\"key\", validatecommand=(reg, \"%d\", \"%P\")).pack()\n\nroot.mainloop()\n",
- "extension": "py"
- },
- {
- "title": "Allow Signed Integers",
- "description": "A validation function to allow only signed integers.",
- "author": "Legopitstop",
- "tags": ["validation", "signed", "integers"],
- "contributors": [],
- "code": "from tkinter import Tk, Entry\n\n\ndef allow_signed_integers(action, value):\n if action == \"1\":\n return (\n value in (\"\", \"-\")\n or value.isdigit()\n or (value.startswith(\"-\") and value[1:].isdigit())\n )\n return True\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_signed_integers)\nEntry(root, validate=\"key\", validatecommand=(reg, \"%d\", \"%P\")).pack()\n\nroot.mainloop()\n",
- "extension": "py"
- },
- {
- "title": "Allow Specific Characters",
- "description": "A validation function to allow specific characters.",
- "author": "Legopitstop",
- "tags": ["validation", "regex"],
- "contributors": [],
- "code": "from tkinter import Tk, Entry\n\n\ndef allow_specific_characters(value, allowed_chars):\n return all(char in allowed_chars for char in value)\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_specific_characters)\nallowed_chars = \"0123456789ABCDEFabcdef\" # Hexadecimal characters\nEntry(root, validate=\"key\", validatecommand=(reg, \"%P\", allowed_chars)).pack()\n\nroot.mainloop()\n",
- "extension": "py"
- },
- {
- "title": "Allow Uppercase",
- "description": "A validation function to allow uppercase letters.",
- "author": "Legopitstop",
- "tags": ["validation", "uppercase"],
- "contributors": [],
- "code": "from tkinter import Tk, Entry\n\n\ndef allow_uppercase(value):\n return value.isupper() or value == \"\"\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_uppercase)\nEntry(root, validate=\"key\", validatecommand=(reg, \"%P\")).pack()\n\nroot.mainloop()\n",
- "extension": "py"
- },
- {
- "title": "Custom Regular Expression",
- "description": "A validation function to match a regular expression pattern.",
- "author": "Legopitstop",
- "tags": ["validation", "regex", "pattern"],
- "contributors": [],
- "code": "from tkinter import Tk, Entry\nimport re\n\n\ndef custom_regular_expression(action, value, pattern):\n if action == \"1\":\n return re.fullmatch(pattern, value) is not None\n return True\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(custom_regular_expression)\npattern = r\"^\\d{0,4}$\" # Allow up to 4 digits\nEntry(root, validate=\"key\", validatecommand=(reg, \"%d\", \"%P\", pattern)).pack()\n\nroot.mainloop()\n",
- "extension": "py"
- },
- {
- "title": "Restrict Length",
- "description": "A validation function to limit the length.",
- "author": "Legopitstop",
- "tags": ["validation", "length"],
- "contributors": [],
- "code": "from tkinter import Tk, Entry\n\n\ndef restrict_length(value, max_length):\n return len(value) <= int(max_length)\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(restrict_length)\n# 10 is the maximum length allowed\nEntry(root, validate=\"key\", validatecommand=(reg, \"%P\", 10)).pack()\n\nroot.mainloop()\n",
- "extension": "py"
- },
- {
- "title": "Validate File Path",
- "description": "A validation function to ensure the file path exists.",
- "author": "Legopitstop",
- "tags": ["validation", "filepath", "fp"],
- "contributors": [],
- "code": "from tkinter import Tk, Entry\nimport os\n\n\ndef validate_file_path(action, value):\n if action == \"1\":\n return value == \"\" or os.path.exists(os.path.expandvars(value))\n return True\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(validate_file_path)\nEntry(root, validate=\"key\", validatecommand=(reg, \"%d\", \"%P\")).pack()\n\nroot.mainloop()\n",
- "extension": "py"
- }
- ]
- },
- {
- "name": "Menus",
- "snippets": [
- {
- "title": "Context Menu",
- "description": "Opens a menu when you right click a widget.",
- "author": "Legopitstop",
- "tags": ["menu"],
- "contributors": [],
- "code": "from tkinter import Tk, Label, Menu\n\n\nclass App(Tk):\n def __init__(self):\n Tk.__init__(self)\n self.geometry(\"200x200\")\n\n lbl = Label(self, text=\"Right-click me!\")\n lbl.bind(\"\", self.do_popup)\n lbl.pack(expand=1, ipadx=10, ipady=10)\n\n def do_popup(self, event):\n menu = Menu(self, tearoff=0)\n menu.add_command(label=\"Option 1\", command=lambda: print(\"Option 1\"))\n menu.add_command(label=\"Option 2\", command=lambda: print(\"Option 2\"))\n menu.post(event.x_root, event.y_root)\n\n\n# Usage:\nroot = App()\nroot.mainloop()\n",
- "extension": "py"
- }
- ]
- }
-]
+ {
+ "name": "Basics",
+ "snippets": [
+ {
+ "title": "Display a Pillow Image",
+ "description": "Use Pillow to show an image in a Tkinter window.",
+ "author": "Legopitstop",
+ "tags": [
+ "app",
+ "hello-world",
+ "object-oriented"
+ ],
+ "contributors": [],
+ "code": "from tkinter import Tk, Label\nfrom PIL import Image, ImageDraw, ImageTk\n\n\nclass App(Tk):\n def __init__(self):\n Tk.__init__(self)\n self.geometry(\"200x200\")\n\n # PhotoImage must be global or be assigned to a class or it will be garbage collected.\n self.photo = ImageTk.PhotoImage(self.make_image())\n lbl = Label(self, image=self.photo)\n lbl.pack(expand=1)\n\n def make_image(self):\n width, height = 200, 200\n image = Image.new(\"RGB\", (width, height), \"white\")\n\n # Create a drawing context\n draw = ImageDraw.Draw(image)\n\n # Draw a circle\n radius = 80\n center = (width // 2, height // 2)\n draw.ellipse(\n [\n (center[0] - radius, center[1] - radius),\n (center[0] + radius, center[1] + radius),\n ],\n fill=\"red\",\n outline=\"black\",\n width=3,\n )\n return image\n\n\n# Usage:\nroot = App()\nroot.mainloop()\n\n",
+ "extension": "py"
+ },
+ {
+ "title": "Hello, World!",
+ "description": "Creates a basic Tkinter window with a \"Hello, World!\" label.",
+ "author": "Legopitstop",
+ "tags": [
+ "app",
+ "hello-world",
+ "object-oriented"
+ ],
+ "contributors": [],
+ "code": "from tkinter import Tk, Label\n\nclass App(Tk):\n def __init__(self):\n Tk.__init__(self)\n self.geometry(\"200x200\")\n\n self.lbl = Label(self, text='Hello, World!')\n self.lbl.pack(expand=1)\n\n# Usage:\nroot = App()\nroot.mainloop()\n",
+ "extension": "py"
+ }
+ ]
+ },
+ {
+ "name": "Entry Validation",
+ "snippets": [
+ {
+ "title": "Allow Alphanumeric",
+ "description": "A validation function to allow alphanumeric characters.",
+ "author": "Legopitstop",
+ "tags": [
+ "validation",
+ "alphanumeric"
+ ],
+ "contributors": [],
+ "code": "from tkinter import Tk, Entry\n\n\ndef allow_alphanumeric(value):\n return value.isalnum() or value == \"\"\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_alphanumeric)\nEntry(root, validate=\"key\", validatecommand=(reg, \"%P\")).pack()\n\nroot.mainloop()\n",
+ "extension": "py"
+ },
+ {
+ "title": "Allow Decimal",
+ "description": "A validation function to allow only decimal numbers.",
+ "author": "Legopitstop",
+ "tags": [
+ "validation",
+ "decimals"
+ ],
+ "contributors": [],
+ "code": "from tkinter import Tk, Entry\n\n\ndef allow_decimal(action, value):\n if action == \"1\":\n if value == \"\":\n return True\n try:\n float(value)\n return True\n except ValueError:\n return False\n return True\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_decimal)\nEntry(root, validate=\"key\", validatecommand=(reg, \"%d\", \"%P\")).pack()\n\nroot.mainloop()\n",
+ "extension": "py"
+ },
+ {
+ "title": "Allow Digits with A Max Length",
+ "description": "A validation function to allow only digits with a specified maximum length.",
+ "author": "Legopitstop",
+ "tags": [
+ "validation",
+ "max",
+ "length"
+ ],
+ "contributors": [],
+ "code": "from tkinter import Tk, Entry\n\n\ndef allow_digits_with_max_length(action, value, max_length):\n if action == \"1\":\n return value == \"\" or (value.isdigit() and len(value) <= int(max_length))\n return True\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_digits_with_max_length)\n# 4 is the max length\nEntry(root, validate=\"key\", validatecommand=(reg, \"%d\", \"%P\", 4)).pack()\n\nroot.mainloop()\n",
+ "extension": "py"
+ },
+ {
+ "title": "Allow Lowercase",
+ "description": "A validation function to allow only lowercase alphabetic characters.",
+ "author": "Legopitstop",
+ "tags": [
+ "validation",
+ "lowercase"
+ ],
+ "contributors": [],
+ "code": "from tkinter import Tk, Entry\n\n\ndef allow_lowercase(value):\n return value.islower() or value == \"\"\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_lowercase)\nEntry(root, validate=\"key\", validatecommand=(reg, \"%P\")).pack()\n\nroot.mainloop()\n",
+ "extension": "py"
+ },
+ {
+ "title": "Allow Negative Integers",
+ "description": "A validation function to allow only negative integers.",
+ "author": "Legopitstop",
+ "tags": [
+ "validation",
+ "negative",
+ "integers"
+ ],
+ "contributors": [],
+ "code": "from tkinter import Tk, Entry\n\n\ndef allow_negative_integers(value):\n return (\n value in (\"\", \"-\") or value.startswith(\"-\") and value[1:].isdigit()\n if value\n else True\n )\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_negative_integers)\nEntry(root, validate=\"key\", validatecommand=(reg, \"%P\")).pack()\n\nroot.mainloop()\n",
+ "extension": "py"
+ },
+ {
+ "title": "Allow Numbers in Range",
+ "description": "A validation function to allow only numbers within a specified range.",
+ "author": "Legopitstop",
+ "tags": [
+ "validation",
+ "number",
+ "range"
+ ],
+ "contributors": [],
+ "code": "from tkinter import Tk, Entry\n\n\ndef allow_numbers_in_range(action, value, min_value, max_value):\n if action == \"1\": \n try:\n num = float(value)\n return float(min_value) <= num <= float(max_value)\n except ValueError:\n return False\n return True\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_numbers_in_range)\n# 0 is the minimum value\n# 10 is the maximum value\nEntry(root, validate=\"key\", validatecommand=(reg, \"%d\", \"%P\", 0, 10)).pack()\n\nroot.mainloop()\n",
+ "extension": "py"
+ },
+ {
+ "title": "Allow Only Alphabets",
+ "description": "A validation function to allow only alphabetic characters.",
+ "author": "Legopitstop",
+ "tags": [
+ "validation",
+ "alphabets"
+ ],
+ "contributors": [],
+ "code": "from tkinter import Tk, Entry\n\n\ndef allow_only_alphabets(value):\n return value.isalpha() or value == \"\"\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_only_alphabets)\nEntry(root, validate=\"key\", validatecommand=(reg, \"%P\")).pack()\n\nroot.mainloop()\n",
+ "extension": "py"
+ },
+ {
+ "title": "Allow Only Digits",
+ "description": "A validation function to allow only digits.",
+ "author": "Legopitstop",
+ "tags": [
+ "validation",
+ "digits"
+ ],
+ "contributors": [],
+ "code": "from tkinter import Tk, Entry\n\n\ndef allow_only_digits(value):\n return value.isdigit() or value == \"\"\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_only_digits)\nEntry(root, validate=\"key\", validatecommand=(reg, \"%P\")).pack()\n\nroot.mainloop()\n",
+ "extension": "py"
+ },
+ {
+ "title": "Allow Positive Integers",
+ "description": "A validation function to allow only positive integers.",
+ "author": "Legopitstop",
+ "tags": [
+ "validation",
+ "positive",
+ "integers"
+ ],
+ "contributors": [],
+ "code": "from tkinter import Tk, Entry\n\n\ndef allow_positive_integers(value):\n return value.isdigit() and (value == \"\" or int(value) > 0)\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_positive_integers)\nEntry(root, validate=\"key\", validatecommand=(reg, \"%P\")).pack()\n\nroot.mainloop()\n",
+ "extension": "py"
+ },
+ {
+ "title": "Allow signed Decimals",
+ "description": "A validation function to allow only signed decimal numbers.",
+ "author": "Legopitstop",
+ "tags": [
+ "validation",
+ "signed",
+ "decimals"
+ ],
+ "contributors": [],
+ "code": "from tkinter import Tk, Entry\n\n\ndef allow_signed_decimals(action, value):\n if action == \"1\":\n try:\n if value in (\"\", \"-\"):\n return True\n float(value)\n return True\n except ValueError:\n return False\n return True\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_signed_decimals)\nEntry(root, validate=\"key\", validatecommand=(reg, \"%d\", \"%P\")).pack()\n\nroot.mainloop()\n",
+ "extension": "py"
+ },
+ {
+ "title": "Allow Signed Integers",
+ "description": "A validation function to allow only signed integers.",
+ "author": "Legopitstop",
+ "tags": [
+ "validation",
+ "signed",
+ "integers"
+ ],
+ "contributors": [],
+ "code": "from tkinter import Tk, Entry\n\n\ndef allow_signed_integers(action, value):\n if action == \"1\":\n return (\n value in (\"\", \"-\")\n or value.isdigit()\n or (value.startswith(\"-\") and value[1:].isdigit())\n )\n return True\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_signed_integers)\nEntry(root, validate=\"key\", validatecommand=(reg, \"%d\", \"%P\")).pack()\n\nroot.mainloop()\n",
+ "extension": "py"
+ },
+ {
+ "title": "Allow Specific Characters",
+ "description": "A validation function to allow specific characters.",
+ "author": "Legopitstop",
+ "tags": [
+ "validation",
+ "regex"
+ ],
+ "contributors": [],
+ "code": "from tkinter import Tk, Entry\n\n\ndef allow_specific_characters(value, allowed_chars):\n return all(char in allowed_chars for char in value)\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_specific_characters)\nallowed_chars = \"0123456789ABCDEFabcdef\" # Hexadecimal characters\nEntry(root, validate=\"key\", validatecommand=(reg, \"%P\", allowed_chars)).pack()\n\nroot.mainloop()\n",
+ "extension": "py"
+ },
+ {
+ "title": "Allow Uppercase",
+ "description": "A validation function to allow uppercase letters.",
+ "author": "Legopitstop",
+ "tags": [
+ "validation",
+ "uppercase"
+ ],
+ "contributors": [],
+ "code": "from tkinter import Tk, Entry\n\n\ndef allow_uppercase(value):\n return value.isupper() or value == \"\"\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(allow_uppercase)\nEntry(root, validate=\"key\", validatecommand=(reg, \"%P\")).pack()\n\nroot.mainloop()\n",
+ "extension": "py"
+ },
+ {
+ "title": "Custom Regular Expression",
+ "description": "A validation function to match a regular expression pattern.",
+ "author": "Legopitstop",
+ "tags": [
+ "validation",
+ "regex",
+ "pattern"
+ ],
+ "contributors": [],
+ "code": "from tkinter import Tk, Entry\nimport re\n\n\ndef custom_regular_expression(action, value, pattern):\n if action == \"1\":\n return re.fullmatch(pattern, value) is not None\n return True\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(custom_regular_expression)\npattern = r\"^\\d{0,4}$\" # Allow up to 4 digits\nEntry(root, validate=\"key\", validatecommand=(reg, \"%d\", \"%P\", pattern)).pack()\n\nroot.mainloop()\n",
+ "extension": "py"
+ },
+ {
+ "title": "Restrict Length",
+ "description": "A validation function to limit the length.",
+ "author": "Legopitstop",
+ "tags": [
+ "validation",
+ "length"
+ ],
+ "contributors": [],
+ "code": "from tkinter import Tk, Entry\n\n\ndef restrict_length(value, max_length):\n return len(value) <= int(max_length)\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(restrict_length)\n# 10 is the maximum length allowed\nEntry(root, validate=\"key\", validatecommand=(reg, \"%P\", 10)).pack()\n\nroot.mainloop()\n",
+ "extension": "py"
+ },
+ {
+ "title": "Validate File Path",
+ "description": "A validation function to ensure the file path exists.",
+ "author": "Legopitstop",
+ "tags": [
+ "validation",
+ "filepath",
+ "fp"
+ ],
+ "contributors": [],
+ "code": "from tkinter import Tk, Entry\nimport os\n\n\ndef validate_file_path(action, value):\n if action == \"1\":\n return value == \"\" or os.path.exists(os.path.expandvars(value))\n return True\n\n\n# Usage:\nroot = Tk()\nroot.geometry(\"200x200\")\n\nreg = root.register(validate_file_path)\nEntry(root, validate=\"key\", validatecommand=(reg, \"%d\", \"%P\")).pack()\n\nroot.mainloop()\n",
+ "extension": "py"
+ }
+ ]
+ },
+ {
+ "name": "Menus",
+ "snippets": [
+ {
+ "title": "Context Menu",
+ "description": "Opens a menu when you right click a widget.",
+ "author": "Legopitstop",
+ "tags": [
+ "menu"
+ ],
+ "contributors": [],
+ "code": "from tkinter import Tk, Label, Menu\n\n\nclass App(Tk):\n def __init__(self):\n Tk.__init__(self)\n self.geometry(\"200x200\")\n\n lbl = Label(self, text=\"Right-click me!\")\n lbl.bind(\"\", self.do_popup)\n lbl.pack(expand=1, ipadx=10, ipady=10)\n\n def do_popup(self, event):\n menu = Menu(self, tearoff=0)\n menu.add_command(label=\"Option 1\", command=lambda: print(\"Option 1\"))\n menu.add_command(label=\"Option 2\", command=lambda: print(\"Option 2\"))\n menu.post(event.x_root, event.y_root)\n\n\n# Usage:\nroot = App()\nroot.mainloop()\n",
+ "extension": "py"
+ }
+ ]
+ }
+]
\ No newline at end of file
diff --git a/backend/data/consolidated/python.json b/backend/data/consolidated/python.json
index 7c85adce..6e22272d 100644
--- a/backend/data/consolidated/python.json
+++ b/backend/data/consolidated/python.json
@@ -1,569 +1,785 @@
[
- {
- "name": "Basics",
- "snippets": [
- {
- "title": "Hello, World!",
- "description": "Prints Hello, World! to the terminal.",
- "author": "James-Beans",
- "tags": ["printing", "hello-world"],
- "contributors": [],
- "code": "print(\"Hello, World!\") # Prints Hello, World! to the terminal.\n",
- "extension": "py"
- }
- ]
- },
- {
- "name": "Datetime Utilities",
- "snippets": [
- {
- "title": "Calculate Date Difference in Milliseconds",
- "description": "Calculates the difference between two dates in milliseconds.",
- "author": "e3nviction",
- "tags": ["datetime", "difference"],
- "contributors": [],
- "code": "from datetime import datetime\n\ndef date_difference_in_millis(date1, date2):\n delta = date2 - date1\n return delta.total_seconds() * 1000\n\n# Usage:\nd1 = datetime(2023, 1, 1, 12, 0, 0)\nd2 = datetime(2023, 1, 1, 12, 1, 0)\ndate_difference_in_millis(d1, d2) # Returns: 60000\n",
- "extension": "py"
- },
- {
- "title": "Check if Date is a Weekend",
- "description": "Checks whether a given date falls on a weekend.",
- "author": "axorax",
- "tags": ["datetime", "weekend"],
- "contributors": [],
- "code": "from datetime import datetime\n\ndef is_weekend(date):\n try:\n return date.weekday() >= 5 # Saturday = 5, Sunday = 6\n except AttributeError:\n raise TypeError(\"Input must be a datetime object\")\n\n# Usage:\ndate = datetime(2023, 1, 1)\nis_weekend(date) # Returns: True (Sunday)\n",
- "extension": "py"
- },
- {
- "title": "Day of the Week String",
- "description": "Gets the string of the day of the week for a given date.",
- "author": "axorax",
- "tags": ["datetime", "weekday"],
- "contributors": [],
- "code": "from datetime import datetime\n\ndef get_day_of_week(date):\n days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\n try:\n return days[date.weekday()]\n except IndexError:\n raise ValueError(\"Invalid date\")\n\n# Usage:\ndate = datetime(2023, 1, 1)\nget_day_of_week(date) # Returns: 'Sunday'\n",
- "extension": "py"
- },
- {
- "title": "Generate Date Range List",
- "description": "Generates a list of dates between two given dates.",
- "author": "axorax",
- "tags": ["datetime", "range"],
- "contributors": [],
- "code": "from datetime import datetime, timedelta\n\ndef generate_date_range(start_date, end_date):\n if start_date > end_date:\n raise ValueError(\"start_date must be before end_date\")\n\n current_date = start_date\n date_list = []\n while current_date <= end_date:\n date_list.append(current_date)\n current_date += timedelta(days=1)\n\n return date_list\n\n# Usage:\nstart = datetime(2023, 1, 1)\nend = datetime(2023, 1, 5)\ndates = generate_date_range(start, end)\nfor d in dates:\n print(d.strftime('%Y-%m-%d'))\n# Outputs: '2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05'\n",
- "extension": "py"
- },
- {
- "title": "Get Current Date and Time as String",
- "description": "Fetches the current date and time as a formatted string.",
- "author": "e3nviction",
- "tags": ["datetime", "current", "string"],
- "contributors": [],
- "code": "from datetime import datetime\n\ndef get_current_datetime_string():\n return datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n\n# Usage:\nget_current_datetime_string() # Returns: '2023-01-01 12:00:00'\n",
- "extension": "py"
- },
- {
- "title": "Get Number of Days in a Month",
- "description": "Determines the number of days in a specific month and year.",
- "author": "axorax",
- "tags": ["datetime", "calendar"],
- "contributors": [],
- "code": "from calendar import monthrange\nfrom datetime import datetime\n\ndef get_days_in_month(year, month):\n try:\n return monthrange(year, month)[1]\n except ValueError as e:\n raise ValueError(f\"Invalid month or year: {e}\")\n\n# Usage:\nget_days_in_month(2023, 2) # Returns: 28 (for non-leap year February)\n",
- "extension": "py"
- },
- {
- "title": "Measure Execution Time",
- "description": "Measures the execution time of a code block.",
- "author": "technoph1le",
- "tags": ["time", "execution"],
- "contributors": [],
- "code": "import time\n\ndef measure_time(func, *args):\n start = time.time()\n result = func(*args)\n end = time.time()\n print(f'Execution time: {end - start:.6f} seconds')\n return result\n\n# Usage:\ndef slow_function():\n time.sleep(2)\n\nmeasure_time(slow_function) # Outputs an execution time of ~2s\n",
- "extension": "py"
- }
- ]
- },
- {
- "name": "Error Handling",
- "snippets": [
- {
- "title": "Create Custom Exception Type",
- "description": "Create a Custom Exception Type that can be called with raise.",
- "author": "mrcool7387",
- "tags": ["python", "error-creation", "organisation", "utility"],
- "contributors": [],
- "code": "class ExceptionName(BaseException):\n def __init__(message: str):\n super().__init__(message)\n\n# Usage\na: int = 1\n\nif a > 0:\n raise ExceptionName('Error Message')\n",
- "extension": "py"
- },
- {
- "title": "Retry Function Execution on Exception",
- "description": "Retries a function execution a specified number of times if it raises an exception.",
- "author": "axorax",
- "tags": ["error-handling", "retry"],
- "contributors": [],
- "code": "import time\n\ndef retry(func, retries=3, delay=1):\n for attempt in range(retries):\n try:\n return func()\n except Exception as e:\n print(f\"Attempt {attempt + 1} failed: {e}\")\n time.sleep(delay)\n raise Exception(\"All retry attempts failed\")\n\n# Usage:\ndef unstable_function():\n raise ValueError(\"Simulated failure\")\n\n# Retry 3 times with 2 seconds delay:\ntry:\n retry(unstable_function, retries=3, delay=2)\nexcept Exception as e:\n print(e) # Output: All retry attempts failed\n",
- "extension": "py"
- }
- ]
- },
- {
- "name": "File Handling",
- "snippets": [
- {
- "title": "Find Files",
- "description": "Finds all files of the specified type within a given directory.",
- "author": "Jackeastern",
- "tags": ["os", "filesystem", "file_search"],
- "contributors": [],
- "code": "import os\n\ndef find_files(directory, file_type):\n file_type = file_type.lower() # Convert file_type to lowercase\n found_files = []\n\n for root, _, files in os.walk(directory):\n for file in files:\n file_ext = os.path.splitext(file)[1].lower()\n if file_ext == file_type:\n full_path = os.path.join(root, file)\n found_files.append(full_path)\n\n return found_files\n\n# Example Usage:\nfind_files('/path/to/your/directory', '.pdf') # Returns all .pdf in directory\n",
- "extension": "py"
- },
- {
- "title": "Get File Extension",
- "description": "Gets the extension of a file.",
- "author": "axorax",
- "tags": ["file", "extension"],
- "contributors": [],
- "code": "import os\n\ndef get_file_extension(filepath):\n return os.path.splitext(filepath)[1]\n\n# Usage:\nget_file_extension('example.txt') # Returns: '.txt'\n",
- "extension": "py"
- },
- {
- "title": "List Files in Directory",
- "description": "Lists all files in a specified directory.",
- "author": "axorax",
- "tags": ["file", "list", "directory"],
- "contributors": [],
- "code": "import os\n\ndef list_files(directory):\n return [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]\n\n# Usage:\nlist_files('/path/to/directory') # Returns: List of file in the directory\n",
- "extension": "py"
- },
- {
- "title": "Read File in Chunks",
- "description": "Reads a file in chunks of a specified size.",
- "author": "axorax",
- "tags": ["file", "read", "chunks"],
- "contributors": [],
- "code": "def read_file_in_chunks(filepath, chunk_size):\n with open(filepath, 'r') as file:\n while chunk := file.read(chunk_size):\n yield chunk\n\n# Usage:\nfor chunk in read_file_in_chunks('example.txt', 1024):\n print(chunk) # Outputs: Chucks of 1024 bytes\n",
- "extension": "py"
- }
- ]
- },
- {
- "name": "Json Manipulation",
- "snippets": [
- {
- "title": "Filter JSON Data",
- "description": "Filters a JSON object based on a condition and returns the filtered data.",
- "author": "axorax",
- "tags": ["json", "filter", "data"],
- "contributors": [],
- "code": "import json\n\ndef filter_json_data(filepath, condition):\n with open(filepath, 'r') as file:\n data = json.load(file)\n\n # Filter data based on the provided condition\n filtered_data = [item for item in data if condition(item)]\n\n return filtered_data\n\n# Usage:\ncondition = lambda x: x['age'] > 25\nfilter_json_data('data.json', condition) # Returns: `data.json` filtered with `condition`\n",
- "extension": "py"
- },
- {
- "title": "Flatten Nested JSON",
- "description": "Flattens a nested JSON object into a flat dictionary.",
- "author": "axorax",
- "tags": ["json", "flatten", "nested"],
- "contributors": [],
- "code": "def flatten_json(nested_json, prefix=''):\n flat_dict = {}\n for key, value in nested_json.items():\n if isinstance(value, dict):\n flat_dict.update(flatten_json(value, prefix + key + '.'))\n else:\n flat_dict[prefix + key] = value\n return flat_dict\n\n# Usage:\nnested_json = {'name': 'John', 'address': {'city': 'New York', 'zip': '10001'}}\nflatten_json(nested_json) # Returns: {'name': 'John', 'address.city': 'New York', 'address.zip': '10001'}\n",
- "extension": "py"
- },
- {
- "title": "Merge Multiple JSON Files",
- "description": "Merges multiple JSON files into one and writes the merged data into a new file.",
- "author": "axorax",
- "tags": ["json", "merge", "file"],
- "contributors": [],
- "code": "import json\n\ndef merge_json_files(filepaths, output_filepath):\n merged_data = []\n\n # Read each JSON file and merge their data\n for filepath in filepaths:\n with open(filepath, 'r') as file:\n data = json.load(file)\n merged_data.extend(data)\n\n # Write the merged data into a new file\n with open(output_filepath, 'w') as file:\n json.dump(merged_data, file, indent=4)\n\n# Usage:\nfiles_to_merge = ['file1.json', 'file2.json']\nmerge_json_files(files_to_merge, 'merged.json')\n",
- "extension": "py"
- },
- {
- "title": "Read JSON File",
- "description": "Reads a JSON file and parses its content.",
- "author": "e3nviction",
- "tags": ["json", "file", "read"],
- "contributors": [],
- "code": "import json\n\ndef read_json(filepath):\n with open(filepath, 'r') as file:\n return json.load(file)\n\n# Usage:\nread_json('data.json') # Returns: Content of file as dict\n",
- "extension": "py"
- },
- {
- "title": "Update JSON File",
- "description": "Updates an existing JSON file with new data or modifies the existing values.",
- "author": "axorax",
- "tags": ["json", "update", "file"],
- "contributors": [],
- "code": "import json\n\ndef update_json(filepath, new_data):\n # Read the existing JSON data\n with open(filepath, 'r') as file:\n data = json.load(file)\n\n # Update the data with the new content\n data.update(new_data)\n\n # Write the updated data back to the JSON file\n with open(filepath, 'w') as file:\n json.dump(data, file, indent=4)\n\n# Usage:\nnew_data = {'age': 31}\nupdate_json('data.json', new_data) # Updates `age` in `data.json` without modifying other keys\n",
- "extension": "py"
- },
- {
- "title": "Write JSON File",
- "description": "Writes a dictionary to a JSON file.",
- "author": "e3nviction",
- "tags": ["json", "file", "write"],
- "contributors": [],
- "code": "import json\n\ndef write_json(filepath, data):\n with open(filepath, 'w') as file:\n json.dump(data, file, indent=4)\n\n# Usage:\ndata = {'name': 'John', 'age': 30}\nwrite_json('data.json', data)\n",
- "extension": "py"
- }
- ]
- },
- {
- "name": "List Manipulation",
- "snippets": [
- {
- "title": "Find Duplicates in a List",
- "description": "Identifies duplicate elements in a list.",
- "author": "axorax",
- "tags": ["list", "duplicates"],
- "contributors": [],
- "code": "def find_duplicates(lst):\n seen = set()\n duplicates = set()\n for item in lst:\n if item in seen:\n duplicates.add(item)\n else:\n seen.add(item)\n return list(duplicates)\n\n# Usage:\ndata = [1, 2, 3, 2, 4, 5, 1]\nfind_duplicates(data) # Returns: [1, 2]\n",
- "extension": "py"
- },
- {
- "title": "Find Intersection of Two Lists",
- "description": "Finds the common elements between two lists.",
- "author": "axorax",
- "tags": ["list", "intersection"],
- "contributors": [],
- "code": "def list_intersection(lst1, lst2):\n return [item for item in lst1 if item in lst2]\n\n# Usage:\nlist_a = [1, 2, 3, 4]\nlist_b = [3, 4, 5, 6]\nlist_intersection(list_a, list_b) # Returns: [3, 4]\n",
- "extension": "py"
- },
- {
- "title": "Find Maximum Difference in List",
- "description": "Finds the maximum difference between any two elements in a list.",
- "author": "axorax",
- "tags": ["list", "difference"],
- "contributors": [],
- "code": "def max_difference(lst):\n if not lst or len(lst) < 2:\n return 0\n return max(lst) - min(lst)\n\n# Usage:\ndata = [10, 3, 5, 20, 7]\nmax_difference(data) # Returns: 17\n",
- "extension": "py"
- },
- {
- "title": "Flatten Nested List",
- "description": "Flattens a multi-dimensional list into a single list.",
- "author": "technoph1le",
- "tags": ["list", "flatten"],
- "contributors": [],
- "code": "def flatten_list(lst):\n return [item for sublist in lst for item in sublist]\n\n# Usage:\nnested_list = [[1, 2], [3, 4], [5]]\nflatten_list(nested_list) # Returns: [1, 2, 3, 4, 5]\n",
- "extension": "py"
- },
- {
- "title": "Flatten Unevenly Nested Lists",
- "description": "Converts unevenly nested lists of any depth into a single flat list.",
- "author": "agilarasu",
- "tags": ["list", "flattening", "nested-lists", "depth"],
- "contributors": [],
- "code": "def flatten(nested_list):\n for item in nested_list:\n if isinstance(item, list):\n yield from flatten(item)\n else:\n yield item\n\n# Usage:\nnested_list = [1, [2, [3, 4]], 5]\nlist(flatten(nested_list)) # Returns: [1, 2, 3, 4, 5]\n",
- "extension": "py"
- },
- {
- "title": "Partition List",
- "description": "Partitions a list into sublists of a given size.",
- "author": "axorax",
- "tags": ["list", "partition"],
- "contributors": [],
- "code": "def partition_list(lst, size):\n for i in range(0, len(lst), size):\n yield lst[i:i + size]\n\n# Usage:\ndata = [1, 2, 3, 4, 5, 6, 7]\nlist(partition_list(data, 3)) # Returns: [[1, 2, 3], [4, 5, 6], [7]]\n",
- "extension": "py"
- },
- {
- "title": "Remove Duplicates",
- "description": "Removes duplicate elements from a list while maintaining order.",
- "author": "technoph1le",
- "tags": ["list", "duplicates", "filter"],
- "contributors": [],
- "code": "def remove_duplicates(lst):\n return list(dict.fromkeys(lst))\n\n# Usage:\nremove_duplicates([1, 2, 2, 3, 4, 4, 5]) # Returns: [1, 2, 3, 4, 5]\n",
- "extension": "py"
- }
- ]
- },
- {
- "name": "Math And Numbers",
- "snippets": [
- {
- "title": "Calculate Compound Interest",
- "description": "Calculates compound interest for a given principal amount, rate, and time period.",
- "author": "axorax",
- "tags": ["math", "compound interest", "finance"],
- "contributors": [],
- "code": "def compound_interest(principal, rate, time, n=1):\n return principal * (1 + rate / n) ** (n * time)\n\n# Usage:\ncompound_interest(1000, 0.05, 5) # Returns: 1276.2815625000003\ncompound_interest(1000, 0.05, 5, 12) # Returns: 1283.68\n",
- "extension": "py"
- },
- {
- "title": "Check Perfect Square",
- "description": "Checks if a number is a perfect square.",
- "author": "axorax",
- "tags": ["math", "perfect square", "check"],
- "contributors": [],
- "code": "def is_perfect_square(n):\n if n < 0:\n return False\n root = int(n**0.5)\n return root * root == n\n\n# Usage:\nis_perfect_square(16) # Returns: True\nis_perfect_square(20) # Returns: False\n",
- "extension": "py"
- },
- {
- "title": "Check Prime Number",
- "description": "Checks if a number is a prime number.",
- "author": "technoph1le",
- "tags": ["math", "prime", "check"],
- "contributors": [],
- "code": "def is_prime(n):\n if n <= 1:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return False\n return True\n\n# Usage:\nis_prime(17) # Returns: True\n",
- "extension": "py"
- },
- {
- "title": "Convert Binary to Decimal",
- "description": "Converts a binary string to its decimal equivalent.",
- "author": "axorax",
- "tags": ["math", "binary", "decimal", "conversion"],
- "contributors": [],
- "code": "def binary_to_decimal(binary_str):\n return int(binary_str, 2)\n\n# Usage:\nbinary_to_decimal('1010') # Returns: 10\nbinary_to_decimal('1101') # Returns: 13\n",
- "extension": "py"
- },
- {
- "title": "Convert Bytes to Human-Readable Format",
- "description": "Converts a size in bytes to a human-readable format.",
- "author": "axorax",
- "tags": ["bytes", "format"],
- "contributors": [],
- "code": "def bytes_to_human_readable(num):\n for unit in ['B', 'KB', 'MB', 'GB', 'TB', 'PB']:\n if num < 1024:\n return f\"{num:.2f} {unit}\"\n num /= 1024\n\n# Usage:\nbytes_to_human_readable(123456789) # Returns: '117.74 MB'\n",
- "extension": "py"
- },
- {
- "title": "Find LCM (Least Common Multiple)",
- "description": "Calculates the least common multiple (LCM) of two numbers.",
- "author": "axorax",
- "tags": ["python", "math", "lcm", "gcd", "utility"],
- "contributors": [],
- "code": "def lcm(a, b):\n return abs(a * b) // gcd(a, b)\n\n# Usage:\nlcm(12, 15) # Returns: 60\nlcm(7, 5) # Returns: 35\n",
- "extension": "py"
- },
- {
- "title": "Linear Mapping",
- "description": "remaps a value from one range to another",
- "author": "JasimAlrawie",
- "tags": ["math", "number-theory", "algebra"],
- "contributors": [],
- "code": "def linear_mapping(value, min_in, max_in, min_out, max_out):\n return (value - min_in) * (max_out - min_out) / (max_in - min_in) + min_out\n\n#Usage:\nlinear_mapping(value, 0, 1, 0, 255) # remaps the value from (0,1) to (0,255)\nlinear_mapping(value, 0, PI*2, 0, 360) # remaps the value from rad to deg\nlinear_mapping(value, -1, 1, 1, 8) # remaps the value from (-1,1) to (1,8)\n",
- "extension": "py"
- },
- {
- "title": "Solve Quadratic Equation",
- "description": "Solves a quadratic equation ax^2 + bx + c = 0 and returns the roots.",
- "author": "axorax",
- "tags": ["math", "quadratic", "equation", "solver"],
- "contributors": [],
- "code": "import cmath\n\ndef solve_quadratic(a, b, c):\n discriminant = cmath.sqrt(b**2 - 4 * a * c)\n root1 = (-b + discriminant) / (2 * a)\n root2 = (-b - discriminant) / (2 * a)\n return root1, root2\n\n# Usage:\nsolve_quadratic(1, -3, 2) # Returns: ((2+0j), (1+0j))\nsolve_quadratic(1, 2, 5) # Returns: ((-1+2j), (-1-2j))\n",
- "extension": "py"
- }
- ]
- },
- {
- "name": "Sqlite Database",
- "snippets": [
- {
- "title": "Create SQLite Database Table",
- "description": "Creates a table in an SQLite database with a dynamic schema.",
- "author": "e3nviction",
- "tags": ["sqlite", "database", "table"],
- "contributors": [],
- "code": "import sqlite3\n\ndef create_table(db_name, table_name, schema):\n conn = sqlite3.connect(db_name)\n cursor = conn.cursor()\n schema_string = ', '.join([f'{col} {dtype}' for col, dtype in schema.items()])\n cursor.execute(f'''\n CREATE TABLE IF NOT EXISTS {table_name} (\n {schema_string}\n )''')\n conn.commit()\n conn.close()\n\n# Usage:\ndb_name = 'example.db'\ntable_name = 'users'\nschema = {\n 'id': 'INTEGER PRIMARY KEY',\n 'name': 'TEXT',\n 'age': 'INTEGER',\n 'email': 'TEXT'\n}\ncreate_table(db_name, table_name, schema)\n",
- "extension": "py"
- },
- {
- "title": "Insert Data into Sqlite Table",
- "description": "Inserts a row into a specified SQLite table using a dictionary of fields and values.",
- "author": "e3nviction",
- "tags": ["sqlite", "database"],
- "contributors": [],
- "code": "import sqlite3\n\ndef insert_into_table(db_path, table_name, data):\n with sqlite3.connect(db_path) as conn:\n columns = ', '.join(data.keys())\n placeholders = ', '.join(['?'] * len(data))\n sql = f\"INSERT INTO {table_name} ({columns}) VALUES ({placeholders})\"\n conn.execute(sql, tuple(data.values()))\n conn.commit()\n\n# Usage:\ndb_path = 'example.db'\ntable_name = 'users'\ndata = {\n 'name': 'John Doe',\n 'email': 'john@example.com',\n 'age': 30\n}\ninsert_into_table(db_path, table_name, data)\n",
- "extension": "py"
- },
- {
- "title": "Query Data from Sqlite Table",
- "description": "Fetches data from a specified SQLite table, with options for selecting specific columns and applying a WHERE clause.",
- "author": "pl44t",
- "tags": ["sqlite", "database"],
- "contributors": [],
- "code": "import sqlite3\n\ndef query_table(db_path, table_name, columns='*', where_clause=None):\n with sqlite3.connect(db_path) as conn:\n cursor = conn.cursor()\n sql = f\"SELECT {columns} FROM {table_name}\"\n if where_clause:\n sql += f\" WHERE {where_clause}\"\n cursor.execute(sql)\n return cursor.fetchall()\n\n# Usage:\ndb_path = 'example.db'\ntable_name = 'users'\ncolumns = 'id, name, email'\nwhere_clause = 'age > 25'\nresult = query_table(db_path, table_name, columns, where_clause)\nfor row in result:\n print(row)\n\n",
- "extension": "py"
- },
- {
- "title": "Update Records in Sqlite Table",
- "description": "Updates records in a specified SQLite table, allowing dynamic column updates and an optional WHERE clause.",
- "author": "pl44t",
- "tags": ["sqlite", "database"],
- "contributors": [],
- "code": "import sqlite3\n\ndef update_table(db_path, table_name, updates, where_clause=None):\n with sqlite3.connect(db_path) as conn:\n set_clause = ', '.join([f\"{col} = ?\" for col in updates.keys()])\n sql = f\"UPDATE {table_name} SET {set_clause}\"\n if where_clause:\n sql += f\" WHERE {where_clause}\"\n conn.execute(sql, tuple(updates.values()))\n conn.commit()\n\n# Usage:\ndb_path = 'example.db'\ntable_name = 'users'\nupdates = {'name': 'Jane Doe', 'age': 28}\nwhere_clause = \"id = 1\"\nupdate_table(db_path, table_name, updates, where_clause)\n\n",
- "extension": "py"
- }
- ]
- },
- {
- "name": "String Manipulation",
- "snippets": [
- {
- "title": "Capitalize Words",
- "description": "Capitalizes the first letter of each word in a string.",
- "author": "axorax",
- "tags": ["string", "capitalize"],
- "contributors": [],
- "code": "def capitalize_words(s):\n return ' '.join(word.capitalize() for word in s.split())\n\n# Usage:\ncapitalize_words('hello world') # Returns: 'Hello World'\n",
- "extension": "py"
- },
- {
- "title": "Check Anagram",
- "description": "Checks if two strings are anagrams of each other.",
- "author": "SteliosGee",
- "tags": ["string", "anagram", "check"],
- "contributors": [],
- "code": "def is_anagram(s1, s2):\n return sorted(s1) == sorted(s2)\n\n# Usage:\nis_anagram('listen', 'silent') # Returns: True\n",
- "extension": "py"
- },
- {
- "title": "Check Palindrome",
- "description": "Checks if a string is a palindrome.",
- "author": "technoph1le",
- "tags": ["string", "palindrome"],
- "contributors": [],
- "code": "def is_palindrome(s):\n s = s.lower().replace(' ', '')\n return s == s[::-1]\n\n# Usage:\nis_palindrome('A man a plan a canal Panama') # Returns: True\n",
- "extension": "py"
- },
- {
- "title": "Convert Snake Case to Camel Case",
- "description": "Converts a snake_case string to camelCase.",
- "author": "axorax",
- "tags": ["string", "snake-case", "camel-case", "convert"],
- "contributors": [],
- "code": "def snake_to_camel(s):\n parts = s.split('_')\n return parts[0] + ''.join(word.capitalize() for word in parts[1:])\n\n# Usage:\nsnake_to_camel('hello_world') # Returns: 'helloWorld'\n",
- "extension": "py"
- },
- {
- "title": "Convert String to Unicode",
- "description": "Converts a string into its Unicode representation.",
- "author": "axorax",
- "tags": ["string", "ascii", "unicode", "convert"],
- "contributors": [],
- "code": "def string_to_unicode(s):\n return [ord(char) for char in s]\n\n# Usage:\nstring_to_unicode('hello') # Returns: [104, 101, 108, 108, 111]\n",
- "extension": "py"
- },
- {
- "title": "Count Character Frequency",
- "description": "Counts the frequency of each character in a string.",
- "author": "axorax",
- "tags": ["string", "character-frequency"],
- "contributors": [],
- "code": "from collections import Counter\n\ndef char_frequency(s):\n return dict(Counter(s))\n\n# Usage:\nchar_frequency('hello') # Returns: {'h': 1, 'e': 1, 'l': 2, 'o': 1}\n",
- "extension": "py"
- },
- {
- "title": "Count Vowels",
- "description": "Counts the number of vowels in a string.",
- "author": "SteliosGee",
- "tags": ["string", "vowels", "count"],
- "contributors": [],
- "code": "def count_vowels(s):\n vowels = 'aeiou'\n return len([char for char in s.lower() if char in vowels])\n\n# Usage:\ncount_vowels('hello') # Returns: 2\n",
- "extension": "py"
- },
- {
- "title": "Count Words",
- "description": "Counts the number of words in a string.",
- "author": "axorax",
- "tags": ["string", "word-count"],
- "contributors": [],
- "code": "def count_words(s):\n return len(s.split())\n\n# Usage:\ncount_words('The quick brown fox') # Returns: 4\n",
- "extension": "py"
- },
- {
- "title": "Find All Substrings",
- "description": "Finds all substrings of a given string.",
- "author": "axorax",
- "tags": ["string", "substring", "find"],
- "contributors": [],
- "code": "def find_substrings(s):\n substrings = []\n for i in range(len(s)):\n for j in range(i + 1, len(s) + 1):\n substrings.append(s[i:j])\n return substrings\n\n# Usage:\nfind_substrings('abc') # Returns: ['a', 'ab', 'abc', 'b', 'bc', 'c']\n",
- "extension": "py"
- },
- {
- "title": "Find Longest Word",
- "description": "Finds the longest word in a string.",
- "author": "axorax",
- "tags": ["string", "longest-word"],
- "contributors": [],
- "code": "def find_longest_word(s):\n words = s.split()\n return max(words, key=len) if words else ''\n\n# Usage:\nfind_longest_word('The quick brown fox') # Returns: 'quick'\n",
- "extension": "py"
- },
- {
- "title": "Find Unique Characters",
- "description": "Finds all unique characters in a string.",
- "author": "axorax",
- "tags": ["string", "unique", "characters"],
- "contributors": [],
- "code": "def find_unique_chars(s):\n return ''.join(sorted(set(s)))\n\n# Usage:\nfind_unique_chars('banana') # Results: 'abn'\n",
- "extension": "py"
- },
- {
- "title": "Generate Random String",
- "description": "Generates a random alphanumeric string.",
- "author": "technoph1le",
- "tags": ["random", "string"],
- "contributors": [],
- "code": "import random\nimport string\n\ndef random_string(length):\n letters_and_digits = string.ascii_letters + string.digits\n return ''.join(random.choice(letters_and_digits) for _ in range(length))\n\n# Usage:\nrandom_string(10) # Results: Random 10-character string\n",
- "extension": "py"
- },
- {
- "title": "Remove Characters",
- "description": "Removes specific characters from a string.",
- "author": "axorax",
- "tags": ["string", "remove", "characters"],
- "contributors": [],
- "code": "def remove_chars(s, chars):\n return ''.join(c for c in s if c not in chars)\n\n# Usage:\nremove_chars('hello world', 'eo') # Returns: 'hll wrld'\n",
- "extension": "py"
- },
- {
- "title": "Remove Duplicate Characters",
- "description": "Removes duplicate characters from a string while maintaining the order.",
- "author": "axorax",
- "tags": ["string", "duplicates", "remove"],
- "contributors": [],
- "code": "def remove_duplicate_chars(s):\n seen = set()\n return ''.join(char for char in s if not (char in seen or seen.add(char)))\n\n# Usage:\nremove_duplicate_chars('programming') # Returns: 'progamin'\n",
- "extension": "py"
- },
- {
- "title": "Remove Punctuation",
- "description": "Removes punctuation from a string.",
- "author": "SteliosGee",
- "tags": ["string", "punctuation", "remove"],
- "contributors": [],
- "code": "import string\n\ndef remove_punctuation(s):\n return s.translate(str.maketrans('', '', string.punctuation))\n\n# Usage:\nremove_punctuation('Hello, World!') # Returns: 'Hello World'\n",
- "extension": "py"
- },
- {
- "title": "Remove Whitespace",
- "description": "Removes all whitespace from a string.",
- "author": "axorax",
- "tags": ["string", "whitespace", "remove"],
- "contributors": [],
- "code": "def remove_whitespace(s):\n return ''.join(s.split())\n\n# Usage:\nremove_whitespace('hello world') # Returns: 'helloworld'\n",
- "extension": "py"
- },
- {
- "title": "Reverse String",
- "description": "Reverses the characters in a string.",
- "author": "technoph1le",
- "tags": ["string", "reverse"],
- "contributors": [],
- "code": "def reverse_string(s:str) -> str:\n return s[::-1]\n\n# Usage:\nreverse_string('hello') # Returns: 'olleh'\n",
- "extension": "py"
- },
- {
- "title": "Split Camel Case",
- "description": "Splits a camel case string into separate words.",
- "author": "axorax",
- "tags": ["string", "camel-case", "split"],
- "contributors": [],
- "code": "import re\n\ndef split_camel_case(s):\n return ' '.join(re.findall(r'[A-Z][a-z]*|[a-z]+', s))\n\n# Usage:\nsplit_camel_case('camelCaseString') # Returns: 'camel Case String'\n",
- "extension": "py"
- },
- {
- "title": "Truncate",
- "description": "Truncates a string to a specified length and a toggleable truncation notation.",
- "author": "axorax",
- "tags": ["string", "truncate"],
- "contributors": ["MinerMinerMods"],
- "code": "def truncate(s:str, length:int, suffix:bool = True) -> str :\n return (s[:length] + (\"...\" if suffix else \"\")) if len(s) > length else s\n\n# Usage:\ntruncate('This is a long string', 10) # Returns: 'This is a ...'\ntruncate('This is a long string', 10, False) # Returns: 'This is a '\n",
- "extension": "py"
- }
- ]
- }
-]
+ {
+ "name": "Basics",
+ "snippets": [
+ {
+ "title": "Hello, World!",
+ "description": "Prints Hello, World! to the terminal.",
+ "author": "James-Beans",
+ "tags": [
+ "printing",
+ "hello-world"
+ ],
+ "contributors": [],
+ "code": "print(\"Hello, World!\") # Prints Hello, World! to the terminal.\n",
+ "extension": "py"
+ }
+ ]
+ },
+ {
+ "name": "Datetime Utilities",
+ "snippets": [
+ {
+ "title": "Calculate Date Difference in Milliseconds",
+ "description": "Calculates the difference between two dates in milliseconds.",
+ "author": "e3nviction",
+ "tags": [
+ "datetime",
+ "difference"
+ ],
+ "contributors": [],
+ "code": "from datetime import datetime\n\ndef date_difference_in_millis(date1, date2):\n delta = date2 - date1\n return delta.total_seconds() * 1000\n\n# Usage:\nd1 = datetime(2023, 1, 1, 12, 0, 0)\nd2 = datetime(2023, 1, 1, 12, 1, 0)\ndate_difference_in_millis(d1, d2) # Returns: 60000\n",
+ "extension": "py"
+ },
+ {
+ "title": "Check if Date is a Weekend",
+ "description": "Checks whether a given date falls on a weekend.",
+ "author": "axorax",
+ "tags": [
+ "datetime",
+ "weekend"
+ ],
+ "contributors": [],
+ "code": "from datetime import datetime\n\ndef is_weekend(date):\n try:\n return date.weekday() >= 5 # Saturday = 5, Sunday = 6\n except AttributeError:\n raise TypeError(\"Input must be a datetime object\")\n\n# Usage:\ndate = datetime(2023, 1, 1)\nis_weekend(date) # Returns: True (Sunday)\n",
+ "extension": "py"
+ },
+ {
+ "title": "Day of the Week String",
+ "description": "Gets the string of the day of the week for a given date.",
+ "author": "axorax",
+ "tags": [
+ "datetime",
+ "weekday"
+ ],
+ "contributors": [],
+ "code": "from datetime import datetime\n\ndef get_day_of_week(date):\n days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\n try:\n return days[date.weekday()]\n except IndexError:\n raise ValueError(\"Invalid date\")\n\n# Usage:\ndate = datetime(2023, 1, 1)\nget_day_of_week(date) # Returns: 'Sunday'\n",
+ "extension": "py"
+ },
+ {
+ "title": "Generate Date Range List",
+ "description": "Generates a list of dates between two given dates.",
+ "author": "axorax",
+ "tags": [
+ "datetime",
+ "range"
+ ],
+ "contributors": [],
+ "code": "from datetime import datetime, timedelta\n\ndef generate_date_range(start_date, end_date):\n if start_date > end_date:\n raise ValueError(\"start_date must be before end_date\")\n\n current_date = start_date\n date_list = []\n while current_date <= end_date:\n date_list.append(current_date)\n current_date += timedelta(days=1)\n\n return date_list\n\n# Usage:\nstart = datetime(2023, 1, 1)\nend = datetime(2023, 1, 5)\ndates = generate_date_range(start, end)\nfor d in dates:\n print(d.strftime('%Y-%m-%d'))\n# Outputs: '2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05'\n",
+ "extension": "py"
+ },
+ {
+ "title": "Get Current Date and Time as String",
+ "description": "Fetches the current date and time as a formatted string.",
+ "author": "e3nviction",
+ "tags": [
+ "datetime",
+ "current",
+ "string"
+ ],
+ "contributors": [],
+ "code": "from datetime import datetime\n\ndef get_current_datetime_string():\n return datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n\n# Usage:\nget_current_datetime_string() # Returns: '2023-01-01 12:00:00'\n",
+ "extension": "py"
+ },
+ {
+ "title": "Get Number of Days in a Month",
+ "description": "Determines the number of days in a specific month and year.",
+ "author": "axorax",
+ "tags": [
+ "datetime",
+ "calendar"
+ ],
+ "contributors": [],
+ "code": "from calendar import monthrange\nfrom datetime import datetime\n\ndef get_days_in_month(year, month):\n try:\n return monthrange(year, month)[1]\n except ValueError as e:\n raise ValueError(f\"Invalid month or year: {e}\")\n\n# Usage:\nget_days_in_month(2023, 2) # Returns: 28 (for non-leap year February)\n",
+ "extension": "py"
+ },
+ {
+ "title": "Measure Execution Time",
+ "description": "Measures the execution time of a code block.",
+ "author": "technoph1le",
+ "tags": [
+ "time",
+ "execution"
+ ],
+ "contributors": [],
+ "code": "import time\n\ndef measure_time(func, *args):\n start = time.time()\n result = func(*args)\n end = time.time()\n print(f'Execution time: {end - start:.6f} seconds')\n return result\n\n# Usage:\ndef slow_function():\n time.sleep(2)\n\nmeasure_time(slow_function) # Outputs an execution time of ~2s\n",
+ "extension": "py"
+ }
+ ]
+ },
+ {
+ "name": "Error Handling",
+ "snippets": [
+ {
+ "title": "Create Custom Exception Type",
+ "description": "Create a Custom Exception Type that can be called with raise.",
+ "author": "mrcool7387",
+ "tags": [
+ "python",
+ "error-creation",
+ "organisation",
+ "utility"
+ ],
+ "contributors": [],
+ "code": "class ExceptionName(BaseException):\n def __init__(message: str):\n super().__init__(message)\n\n# Usage\na: int = 1\n\nif a > 0:\n raise ExceptionName('Error Message')\n",
+ "extension": "py"
+ },
+ {
+ "title": "Retry Function Execution on Exception",
+ "description": "Retries a function execution a specified number of times if it raises an exception.",
+ "author": "axorax",
+ "tags": [
+ "error-handling",
+ "retry"
+ ],
+ "contributors": [],
+ "code": "import time\n\ndef retry(func, retries=3, delay=1):\n for attempt in range(retries):\n try:\n return func()\n except Exception as e:\n print(f\"Attempt {attempt + 1} failed: {e}\")\n time.sleep(delay)\n raise Exception(\"All retry attempts failed\")\n\n# Usage:\ndef unstable_function():\n raise ValueError(\"Simulated failure\")\n\n# Retry 3 times with 2 seconds delay:\ntry:\n retry(unstable_function, retries=3, delay=2)\nexcept Exception as e:\n print(e) # Output: All retry attempts failed\n",
+ "extension": "py"
+ }
+ ]
+ },
+ {
+ "name": "File Handling",
+ "snippets": [
+ {
+ "title": "Find Files",
+ "description": "Finds all files of the specified type within a given directory.",
+ "author": "Jackeastern",
+ "tags": [
+ "os",
+ "filesystem",
+ "file_search"
+ ],
+ "contributors": [],
+ "code": "import os\n\ndef find_files(directory, file_type):\n file_type = file_type.lower() # Convert file_type to lowercase\n found_files = []\n\n for root, _, files in os.walk(directory):\n for file in files:\n file_ext = os.path.splitext(file)[1].lower()\n if file_ext == file_type:\n full_path = os.path.join(root, file)\n found_files.append(full_path)\n\n return found_files\n\n# Example Usage:\nfind_files('/path/to/your/directory', '.pdf') # Returns all .pdf in directory\n",
+ "extension": "py"
+ },
+ {
+ "title": "Get File Extension",
+ "description": "Gets the extension of a file.",
+ "author": "axorax",
+ "tags": [
+ "file",
+ "extension"
+ ],
+ "contributors": [],
+ "code": "import os\n\ndef get_file_extension(filepath):\n return os.path.splitext(filepath)[1]\n\n# Usage:\nget_file_extension('example.txt') # Returns: '.txt'\n",
+ "extension": "py"
+ },
+ {
+ "title": "List Files in Directory",
+ "description": "Lists all files in a specified directory.",
+ "author": "axorax",
+ "tags": [
+ "file",
+ "list",
+ "directory"
+ ],
+ "contributors": [],
+ "code": "import os\n\ndef list_files(directory):\n return [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]\n\n# Usage:\nlist_files('/path/to/directory') # Returns: List of file in the directory\n",
+ "extension": "py"
+ },
+ {
+ "title": "Read File in Chunks",
+ "description": "Reads a file in chunks of a specified size.",
+ "author": "axorax",
+ "tags": [
+ "file",
+ "read",
+ "chunks"
+ ],
+ "contributors": [],
+ "code": "def read_file_in_chunks(filepath, chunk_size):\n with open(filepath, 'r') as file:\n while chunk := file.read(chunk_size):\n yield chunk\n\n# Usage:\nfor chunk in read_file_in_chunks('example.txt', 1024):\n print(chunk) # Outputs: Chucks of 1024 bytes\n",
+ "extension": "py"
+ }
+ ]
+ },
+ {
+ "name": "Json Manipulation",
+ "snippets": [
+ {
+ "title": "Filter JSON Data",
+ "description": "Filters a JSON object based on a condition and returns the filtered data.",
+ "author": "axorax",
+ "tags": [
+ "json",
+ "filter",
+ "data"
+ ],
+ "contributors": [],
+ "code": "import json\n\ndef filter_json_data(filepath, condition):\n with open(filepath, 'r') as file:\n data = json.load(file)\n\n # Filter data based on the provided condition\n filtered_data = [item for item in data if condition(item)]\n\n return filtered_data\n\n# Usage:\ncondition = lambda x: x['age'] > 25\nfilter_json_data('data.json', condition) # Returns: `data.json` filtered with `condition`\n",
+ "extension": "py"
+ },
+ {
+ "title": "Flatten Nested JSON",
+ "description": "Flattens a nested JSON object into a flat dictionary.",
+ "author": "axorax",
+ "tags": [
+ "json",
+ "flatten",
+ "nested"
+ ],
+ "contributors": [],
+ "code": "def flatten_json(nested_json, prefix=''):\n flat_dict = {}\n for key, value in nested_json.items():\n if isinstance(value, dict):\n flat_dict.update(flatten_json(value, prefix + key + '.'))\n else:\n flat_dict[prefix + key] = value\n return flat_dict\n\n# Usage:\nnested_json = {'name': 'John', 'address': {'city': 'New York', 'zip': '10001'}}\nflatten_json(nested_json) # Returns: {'name': 'John', 'address.city': 'New York', 'address.zip': '10001'}\n",
+ "extension": "py"
+ },
+ {
+ "title": "Merge Multiple JSON Files",
+ "description": "Merges multiple JSON files into one and writes the merged data into a new file.",
+ "author": "axorax",
+ "tags": [
+ "json",
+ "merge",
+ "file"
+ ],
+ "contributors": [],
+ "code": "import json\n\ndef merge_json_files(filepaths, output_filepath):\n merged_data = []\n\n # Read each JSON file and merge their data\n for filepath in filepaths:\n with open(filepath, 'r') as file:\n data = json.load(file)\n merged_data.extend(data)\n\n # Write the merged data into a new file\n with open(output_filepath, 'w') as file:\n json.dump(merged_data, file, indent=4)\n\n# Usage:\nfiles_to_merge = ['file1.json', 'file2.json']\nmerge_json_files(files_to_merge, 'merged.json')\n",
+ "extension": "py"
+ },
+ {
+ "title": "Read JSON File",
+ "description": "Reads a JSON file and parses its content.",
+ "author": "e3nviction",
+ "tags": [
+ "json",
+ "file",
+ "read"
+ ],
+ "contributors": [],
+ "code": "import json\n\ndef read_json(filepath):\n with open(filepath, 'r') as file:\n return json.load(file)\n\n# Usage:\nread_json('data.json') # Returns: Content of file as dict\n",
+ "extension": "py"
+ },
+ {
+ "title": "Update JSON File",
+ "description": "Updates an existing JSON file with new data or modifies the existing values.",
+ "author": "axorax",
+ "tags": [
+ "json",
+ "update",
+ "file"
+ ],
+ "contributors": [],
+ "code": "import json\n\ndef update_json(filepath, new_data):\n # Read the existing JSON data\n with open(filepath, 'r') as file:\n data = json.load(file)\n\n # Update the data with the new content\n data.update(new_data)\n\n # Write the updated data back to the JSON file\n with open(filepath, 'w') as file:\n json.dump(data, file, indent=4)\n\n# Usage:\nnew_data = {'age': 31}\nupdate_json('data.json', new_data) # Updates `age` in `data.json` without modifying other keys\n",
+ "extension": "py"
+ },
+ {
+ "title": "Write JSON File",
+ "description": "Writes a dictionary to a JSON file.",
+ "author": "e3nviction",
+ "tags": [
+ "json",
+ "file",
+ "write"
+ ],
+ "contributors": [],
+ "code": "import json\n\ndef write_json(filepath, data):\n with open(filepath, 'w') as file:\n json.dump(data, file, indent=4)\n\n# Usage:\ndata = {'name': 'John', 'age': 30}\nwrite_json('data.json', data)\n",
+ "extension": "py"
+ }
+ ]
+ },
+ {
+ "name": "List Manipulation",
+ "snippets": [
+ {
+ "title": "Find Duplicates in a List",
+ "description": "Identifies duplicate elements in a list.",
+ "author": "axorax",
+ "tags": [
+ "list",
+ "duplicates"
+ ],
+ "contributors": [],
+ "code": "def find_duplicates(lst):\n seen = set()\n duplicates = set()\n for item in lst:\n if item in seen:\n duplicates.add(item)\n else:\n seen.add(item)\n return list(duplicates)\n\n# Usage:\ndata = [1, 2, 3, 2, 4, 5, 1]\nfind_duplicates(data) # Returns: [1, 2]\n",
+ "extension": "py"
+ },
+ {
+ "title": "Find Intersection of Two Lists",
+ "description": "Finds the common elements between two lists.",
+ "author": "axorax",
+ "tags": [
+ "list",
+ "intersection"
+ ],
+ "contributors": [],
+ "code": "def list_intersection(lst1, lst2):\n return [item for item in lst1 if item in lst2]\n\n# Usage:\nlist_a = [1, 2, 3, 4]\nlist_b = [3, 4, 5, 6]\nlist_intersection(list_a, list_b) # Returns: [3, 4]\n",
+ "extension": "py"
+ },
+ {
+ "title": "Find Maximum Difference in List",
+ "description": "Finds the maximum difference between any two elements in a list.",
+ "author": "axorax",
+ "tags": [
+ "list",
+ "difference"
+ ],
+ "contributors": [],
+ "code": "def max_difference(lst):\n if not lst or len(lst) < 2:\n return 0\n return max(lst) - min(lst)\n\n# Usage:\ndata = [10, 3, 5, 20, 7]\nmax_difference(data) # Returns: 17\n",
+ "extension": "py"
+ },
+ {
+ "title": "Flatten Nested List",
+ "description": "Flattens a multi-dimensional list into a single list.",
+ "author": "technoph1le",
+ "tags": [
+ "list",
+ "flatten"
+ ],
+ "contributors": [],
+ "code": "def flatten_list(lst):\n return [item for sublist in lst for item in sublist]\n\n# Usage:\nnested_list = [[1, 2], [3, 4], [5]]\nflatten_list(nested_list) # Returns: [1, 2, 3, 4, 5]\n",
+ "extension": "py"
+ },
+ {
+ "title": "Flatten Unevenly Nested Lists",
+ "description": "Converts unevenly nested lists of any depth into a single flat list.",
+ "author": "agilarasu",
+ "tags": [
+ "list",
+ "flattening",
+ "nested-lists",
+ "depth"
+ ],
+ "contributors": [],
+ "code": "def flatten(nested_list):\n for item in nested_list:\n if isinstance(item, list):\n yield from flatten(item)\n else:\n yield item\n\n# Usage:\nnested_list = [1, [2, [3, 4]], 5]\nlist(flatten(nested_list)) # Returns: [1, 2, 3, 4, 5]\n",
+ "extension": "py"
+ },
+ {
+ "title": "Partition List",
+ "description": "Partitions a list into sublists of a given size.",
+ "author": "axorax",
+ "tags": [
+ "list",
+ "partition"
+ ],
+ "contributors": [],
+ "code": "def partition_list(lst, size):\n for i in range(0, len(lst), size):\n yield lst[i:i + size]\n\n# Usage:\ndata = [1, 2, 3, 4, 5, 6, 7]\nlist(partition_list(data, 3)) # Returns: [[1, 2, 3], [4, 5, 6], [7]]\n",
+ "extension": "py"
+ },
+ {
+ "title": "Remove Duplicates",
+ "description": "Removes duplicate elements from a list while maintaining order.",
+ "author": "technoph1le",
+ "tags": [
+ "list",
+ "duplicates",
+ "filter"
+ ],
+ "contributors": [],
+ "code": "def remove_duplicates(lst):\n return list(dict.fromkeys(lst))\n\n# Usage:\nremove_duplicates([1, 2, 2, 3, 4, 4, 5]) # Returns: [1, 2, 3, 4, 5]\n",
+ "extension": "py"
+ }
+ ]
+ },
+ {
+ "name": "Math And Numbers",
+ "snippets": [
+ {
+ "title": "Calculate Compound Interest",
+ "description": "Calculates compound interest for a given principal amount, rate, and time period.",
+ "author": "axorax",
+ "tags": [
+ "math",
+ "compound interest",
+ "finance"
+ ],
+ "contributors": [],
+ "code": "def compound_interest(principal, rate, time, n=1):\n return principal * (1 + rate / n) ** (n * time)\n\n# Usage:\ncompound_interest(1000, 0.05, 5) # Returns: 1276.2815625000003\ncompound_interest(1000, 0.05, 5, 12) # Returns: 1283.68\n",
+ "extension": "py"
+ },
+ {
+ "title": "Check Perfect Square",
+ "description": "Checks if a number is a perfect square.",
+ "author": "axorax",
+ "tags": [
+ "math",
+ "perfect square",
+ "check"
+ ],
+ "contributors": [],
+ "code": "def is_perfect_square(n):\n if n < 0:\n return False\n root = int(n**0.5)\n return root * root == n\n\n# Usage:\nis_perfect_square(16) # Returns: True\nis_perfect_square(20) # Returns: False\n",
+ "extension": "py"
+ },
+ {
+ "title": "Check Prime Number",
+ "description": "Checks if a number is a prime number.",
+ "author": "technoph1le",
+ "tags": [
+ "math",
+ "prime",
+ "check"
+ ],
+ "contributors": [],
+ "code": "def is_prime(n):\n if n <= 1:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return False\n return True\n\n# Usage:\nis_prime(17) # Returns: True\n",
+ "extension": "py"
+ },
+ {
+ "title": "Convert Binary to Decimal",
+ "description": "Converts a binary string to its decimal equivalent.",
+ "author": "axorax",
+ "tags": [
+ "math",
+ "binary",
+ "decimal",
+ "conversion"
+ ],
+ "contributors": [],
+ "code": "def binary_to_decimal(binary_str):\n return int(binary_str, 2)\n\n# Usage:\nbinary_to_decimal('1010') # Returns: 10\nbinary_to_decimal('1101') # Returns: 13\n",
+ "extension": "py"
+ },
+ {
+ "title": "Convert Bytes to Human-Readable Format",
+ "description": "Converts a size in bytes to a human-readable format.",
+ "author": "axorax",
+ "tags": [
+ "bytes",
+ "format"
+ ],
+ "contributors": [],
+ "code": "def bytes_to_human_readable(num):\n for unit in ['B', 'KB', 'MB', 'GB', 'TB', 'PB']:\n if num < 1024:\n return f\"{num:.2f} {unit}\"\n num /= 1024\n\n# Usage:\nbytes_to_human_readable(123456789) # Returns: '117.74 MB'\n",
+ "extension": "py"
+ },
+ {
+ "title": "Find LCM (Least Common Multiple)",
+ "description": "Calculates the least common multiple (LCM) of two numbers.",
+ "author": "axorax",
+ "tags": [
+ "python",
+ "math",
+ "lcm",
+ "gcd",
+ "utility"
+ ],
+ "contributors": [],
+ "code": "def lcm(a, b):\n return abs(a * b) // gcd(a, b)\n\n# Usage:\nlcm(12, 15) # Returns: 60\nlcm(7, 5) # Returns: 35\n",
+ "extension": "py"
+ },
+ {
+ "title": "Linear Mapping",
+ "description": "remaps a value from one range to another",
+ "author": "JasimAlrawie",
+ "tags": [
+ "math",
+ "number-theory",
+ "algebra"
+ ],
+ "contributors": [],
+ "code": "def linear_mapping(value, min_in, max_in, min_out, max_out):\n return (value - min_in) * (max_out - min_out) / (max_in - min_in) + min_out\n\n#Usage:\nlinear_mapping(value, 0, 1, 0, 255) # remaps the value from (0,1) to (0,255)\nlinear_mapping(value, 0, PI*2, 0, 360) # remaps the value from rad to deg\nlinear_mapping(value, -1, 1, 1, 8) # remaps the value from (-1,1) to (1,8)\n",
+ "extension": "py"
+ },
+ {
+ "title": "Solve Quadratic Equation",
+ "description": "Solves a quadratic equation ax^2 + bx + c = 0 and returns the roots.",
+ "author": "axorax",
+ "tags": [
+ "math",
+ "quadratic",
+ "equation",
+ "solver"
+ ],
+ "contributors": [],
+ "code": "import cmath\n\ndef solve_quadratic(a, b, c):\n discriminant = cmath.sqrt(b**2 - 4 * a * c)\n root1 = (-b + discriminant) / (2 * a)\n root2 = (-b - discriminant) / (2 * a)\n return root1, root2\n\n# Usage:\nsolve_quadratic(1, -3, 2) # Returns: ((2+0j), (1+0j))\nsolve_quadratic(1, 2, 5) # Returns: ((-1+2j), (-1-2j))\n",
+ "extension": "py"
+ }
+ ]
+ },
+ {
+ "name": "Sqlite Database",
+ "snippets": [
+ {
+ "title": "Create SQLite Database Table",
+ "description": "Creates a table in an SQLite database with a dynamic schema.",
+ "author": "e3nviction",
+ "tags": [
+ "sqlite",
+ "database",
+ "table"
+ ],
+ "contributors": [],
+ "code": "import sqlite3\n\ndef create_table(db_name, table_name, schema):\n conn = sqlite3.connect(db_name)\n cursor = conn.cursor()\n schema_string = ', '.join([f'{col} {dtype}' for col, dtype in schema.items()])\n cursor.execute(f'''\n CREATE TABLE IF NOT EXISTS {table_name} (\n {schema_string}\n )''')\n conn.commit()\n conn.close()\n\n# Usage:\ndb_name = 'example.db'\ntable_name = 'users'\nschema = {\n 'id': 'INTEGER PRIMARY KEY',\n 'name': 'TEXT',\n 'age': 'INTEGER',\n 'email': 'TEXT'\n}\ncreate_table(db_name, table_name, schema)\n",
+ "extension": "py"
+ },
+ {
+ "title": "Insert Data into Sqlite Table",
+ "description": "Inserts a row into a specified SQLite table using a dictionary of fields and values.",
+ "author": "e3nviction",
+ "tags": [
+ "sqlite",
+ "database"
+ ],
+ "contributors": [],
+ "code": "import sqlite3\n\ndef insert_into_table(db_path, table_name, data):\n with sqlite3.connect(db_path) as conn:\n columns = ', '.join(data.keys())\n placeholders = ', '.join(['?'] * len(data))\n sql = f\"INSERT INTO {table_name} ({columns}) VALUES ({placeholders})\"\n conn.execute(sql, tuple(data.values()))\n conn.commit()\n\n# Usage:\ndb_path = 'example.db'\ntable_name = 'users'\ndata = {\n 'name': 'John Doe',\n 'email': 'john@example.com',\n 'age': 30\n}\ninsert_into_table(db_path, table_name, data)\n",
+ "extension": "py"
+ },
+ {
+ "title": "Query Data from Sqlite Table",
+ "description": "Fetches data from a specified SQLite table, with options for selecting specific columns and applying a WHERE clause.",
+ "author": "pl44t",
+ "tags": [
+ "sqlite",
+ "database"
+ ],
+ "contributors": [],
+ "code": "import sqlite3\n\ndef query_table(db_path, table_name, columns='*', where_clause=None):\n with sqlite3.connect(db_path) as conn:\n cursor = conn.cursor()\n sql = f\"SELECT {columns} FROM {table_name}\"\n if where_clause:\n sql += f\" WHERE {where_clause}\"\n cursor.execute(sql)\n return cursor.fetchall()\n\n# Usage:\ndb_path = 'example.db'\ntable_name = 'users'\ncolumns = 'id, name, email'\nwhere_clause = 'age > 25'\nresult = query_table(db_path, table_name, columns, where_clause)\nfor row in result:\n print(row)\n\n",
+ "extension": "py"
+ },
+ {
+ "title": "Update Records in Sqlite Table",
+ "description": "Updates records in a specified SQLite table, allowing dynamic column updates and an optional WHERE clause.",
+ "author": "pl44t",
+ "tags": [
+ "sqlite",
+ "database"
+ ],
+ "contributors": [],
+ "code": "import sqlite3\n\ndef update_table(db_path, table_name, updates, where_clause=None):\n with sqlite3.connect(db_path) as conn:\n set_clause = ', '.join([f\"{col} = ?\" for col in updates.keys()])\n sql = f\"UPDATE {table_name} SET {set_clause}\"\n if where_clause:\n sql += f\" WHERE {where_clause}\"\n conn.execute(sql, tuple(updates.values()))\n conn.commit()\n\n# Usage:\ndb_path = 'example.db'\ntable_name = 'users'\nupdates = {'name': 'Jane Doe', 'age': 28}\nwhere_clause = \"id = 1\"\nupdate_table(db_path, table_name, updates, where_clause)\n\n",
+ "extension": "py"
+ }
+ ]
+ },
+ {
+ "name": "String Manipulation",
+ "snippets": [
+ {
+ "title": "Capitalize Words",
+ "description": "Capitalizes the first letter of each word in a string.",
+ "author": "axorax",
+ "tags": [
+ "string",
+ "capitalize"
+ ],
+ "contributors": [],
+ "code": "def capitalize_words(s):\n return ' '.join(word.capitalize() for word in s.split())\n\n# Usage:\ncapitalize_words('hello world') # Returns: 'Hello World'\n",
+ "extension": "py"
+ },
+ {
+ "title": "Check Anagram",
+ "description": "Checks if two strings are anagrams of each other.",
+ "author": "SteliosGee",
+ "tags": [
+ "string",
+ "anagram",
+ "check"
+ ],
+ "contributors": [],
+ "code": "def is_anagram(s1, s2):\n return sorted(s1) == sorted(s2)\n\n# Usage:\nis_anagram('listen', 'silent') # Returns: True\n",
+ "extension": "py"
+ },
+ {
+ "title": "Check Palindrome",
+ "description": "Checks if a string is a palindrome.",
+ "author": "technoph1le",
+ "tags": [
+ "string",
+ "palindrome"
+ ],
+ "contributors": [],
+ "code": "def is_palindrome(s):\n s = s.lower().replace(' ', '')\n return s == s[::-1]\n\n# Usage:\nis_palindrome('A man a plan a canal Panama') # Returns: True\n",
+ "extension": "py"
+ },
+ {
+ "title": "Convert Snake Case to Camel Case",
+ "description": "Converts a snake_case string to camelCase.",
+ "author": "axorax",
+ "tags": [
+ "string",
+ "snake-case",
+ "camel-case",
+ "convert"
+ ],
+ "contributors": [],
+ "code": "def snake_to_camel(s):\n parts = s.split('_')\n return parts[0] + ''.join(word.capitalize() for word in parts[1:])\n\n# Usage:\nsnake_to_camel('hello_world') # Returns: 'helloWorld'\n",
+ "extension": "py"
+ },
+ {
+ "title": "Convert String to Unicode",
+ "description": "Converts a string into its Unicode representation.",
+ "author": "axorax",
+ "tags": [
+ "string",
+ "ascii",
+ "unicode",
+ "convert"
+ ],
+ "contributors": [],
+ "code": "def string_to_unicode(s):\n return [ord(char) for char in s]\n\n# Usage:\nstring_to_unicode('hello') # Returns: [104, 101, 108, 108, 111]\n",
+ "extension": "py"
+ },
+ {
+ "title": "Count Character Frequency",
+ "description": "Counts the frequency of each character in a string.",
+ "author": "axorax",
+ "tags": [
+ "string",
+ "character-frequency"
+ ],
+ "contributors": [],
+ "code": "from collections import Counter\n\ndef char_frequency(s):\n return dict(Counter(s))\n\n# Usage:\nchar_frequency('hello') # Returns: {'h': 1, 'e': 1, 'l': 2, 'o': 1}\n",
+ "extension": "py"
+ },
+ {
+ "title": "Count Vowels",
+ "description": "Counts the number of vowels in a string.",
+ "author": "SteliosGee",
+ "tags": [
+ "string",
+ "vowels",
+ "count"
+ ],
+ "contributors": [],
+ "code": "def count_vowels(s):\n vowels = 'aeiou'\n return len([char for char in s.lower() if char in vowels])\n\n# Usage:\ncount_vowels('hello') # Returns: 2\n",
+ "extension": "py"
+ },
+ {
+ "title": "Count Words",
+ "description": "Counts the number of words in a string.",
+ "author": "axorax",
+ "tags": [
+ "string",
+ "word-count"
+ ],
+ "contributors": [],
+ "code": "def count_words(s):\n return len(s.split())\n\n# Usage:\ncount_words('The quick brown fox') # Returns: 4\n",
+ "extension": "py"
+ },
+ {
+ "title": "Find All Substrings",
+ "description": "Finds all substrings of a given string.",
+ "author": "axorax",
+ "tags": [
+ "string",
+ "substring",
+ "find"
+ ],
+ "contributors": [],
+ "code": "def find_substrings(s):\n substrings = []\n for i in range(len(s)):\n for j in range(i + 1, len(s) + 1):\n substrings.append(s[i:j])\n return substrings\n\n# Usage:\nfind_substrings('abc') # Returns: ['a', 'ab', 'abc', 'b', 'bc', 'c']\n",
+ "extension": "py"
+ },
+ {
+ "title": "Find Longest Word",
+ "description": "Finds the longest word in a string.",
+ "author": "axorax",
+ "tags": [
+ "string",
+ "longest-word"
+ ],
+ "contributors": [],
+ "code": "def find_longest_word(s):\n words = s.split()\n return max(words, key=len) if words else ''\n\n# Usage:\nfind_longest_word('The quick brown fox') # Returns: 'quick'\n",
+ "extension": "py"
+ },
+ {
+ "title": "Find Unique Characters",
+ "description": "Finds all unique characters in a string.",
+ "author": "axorax",
+ "tags": [
+ "string",
+ "unique",
+ "characters"
+ ],
+ "contributors": [],
+ "code": "def find_unique_chars(s):\n return ''.join(sorted(set(s)))\n\n# Usage:\nfind_unique_chars('banana') # Results: 'abn'\n",
+ "extension": "py"
+ },
+ {
+ "title": "Generate Random String",
+ "description": "Generates a random alphanumeric string.",
+ "author": "technoph1le",
+ "tags": [
+ "random",
+ "string"
+ ],
+ "contributors": [],
+ "code": "import random\nimport string\n\ndef random_string(length):\n letters_and_digits = string.ascii_letters + string.digits\n return ''.join(random.choice(letters_and_digits) for _ in range(length))\n\n# Usage:\nrandom_string(10) # Results: Random 10-character string\n",
+ "extension": "py"
+ },
+ {
+ "title": "Remove Characters",
+ "description": "Removes specific characters from a string.",
+ "author": "axorax",
+ "tags": [
+ "string",
+ "remove",
+ "characters"
+ ],
+ "contributors": [],
+ "code": "def remove_chars(s, chars):\n return ''.join(c for c in s if c not in chars)\n\n# Usage:\nremove_chars('hello world', 'eo') # Returns: 'hll wrld'\n",
+ "extension": "py"
+ },
+ {
+ "title": "Remove Duplicate Characters",
+ "description": "Removes duplicate characters from a string while maintaining the order.",
+ "author": "axorax",
+ "tags": [
+ "string",
+ "duplicates",
+ "remove"
+ ],
+ "contributors": [],
+ "code": "def remove_duplicate_chars(s):\n seen = set()\n return ''.join(char for char in s if not (char in seen or seen.add(char)))\n\n# Usage:\nremove_duplicate_chars('programming') # Returns: 'progamin'\n",
+ "extension": "py"
+ },
+ {
+ "title": "Remove Punctuation",
+ "description": "Removes punctuation from a string.",
+ "author": "SteliosGee",
+ "tags": [
+ "string",
+ "punctuation",
+ "remove"
+ ],
+ "contributors": [],
+ "code": "import string\n\ndef remove_punctuation(s):\n return s.translate(str.maketrans('', '', string.punctuation))\n\n# Usage:\nremove_punctuation('Hello, World!') # Returns: 'Hello World'\n",
+ "extension": "py"
+ },
+ {
+ "title": "Remove Whitespace",
+ "description": "Removes all whitespace from a string.",
+ "author": "axorax",
+ "tags": [
+ "string",
+ "whitespace",
+ "remove"
+ ],
+ "contributors": [],
+ "code": "def remove_whitespace(s):\n return ''.join(s.split())\n\n# Usage:\nremove_whitespace('hello world') # Returns: 'helloworld'\n",
+ "extension": "py"
+ },
+ {
+ "title": "Reverse String",
+ "description": "Reverses the characters in a string.",
+ "author": "technoph1le",
+ "tags": [
+ "string",
+ "reverse"
+ ],
+ "contributors": [],
+ "code": "def reverse_string(s:str) -> str:\n return s[::-1]\n\n# Usage:\nreverse_string('hello') # Returns: 'olleh'\n",
+ "extension": "py"
+ },
+ {
+ "title": "Split Camel Case",
+ "description": "Splits a camel case string into separate words.",
+ "author": "axorax",
+ "tags": [
+ "string",
+ "camel-case",
+ "split"
+ ],
+ "contributors": [],
+ "code": "import re\n\ndef split_camel_case(s):\n return ' '.join(re.findall(r'[A-Z][a-z]*|[a-z]+', s))\n\n# Usage:\nsplit_camel_case('camelCaseString') # Returns: 'camel Case String'\n",
+ "extension": "py"
+ },
+ {
+ "title": "Truncate",
+ "description": "Truncates a string to a specified length and a toggleable truncation notation.",
+ "author": "axorax",
+ "tags": [
+ "string",
+ "truncate"
+ ],
+ "contributors": [
+ "MinerMinerMods"
+ ],
+ "code": "def truncate(s:str, length:int, suffix:bool = True) -> str :\n return (s[:length] + (\"...\" if suffix else \"\")) if len(s) > length else s\n\n# Usage:\ntruncate('This is a long string', 10) # Returns: 'This is a ...'\ntruncate('This is a long string', 10, False) # Returns: 'This is a '\n",
+ "extension": "py"
+ }
+ ]
+ }
+]
\ No newline at end of file
diff --git a/backend/data/consolidated/regex.json b/backend/data/consolidated/regex.json
index 3f894293..9fc3d786 100644
--- a/backend/data/consolidated/regex.json
+++ b/backend/data/consolidated/regex.json
@@ -1,66 +1,80 @@
[
- {
- "name": "Miscellaneous",
- "snippets": [
- {
- "title": "Hexadecimal Color",
- "description": "Matches hex color codes",
- "author": "majvax",
- "tags": ["color", "hexadecimal"],
- "contributors": [],
- "code": "^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$\n\n\n-> Usage:\n#FFF1 ✗\n#FFF ✓\n#FFF000 ✓\n",
- "extension": "regex"
- },
- {
- "title": "IPv4",
- "description": "Matches IPv4 address",
- "author": "majvax",
- "tags": ["ipv4", "networking"],
- "contributors": [],
- "code": "^((25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})$\n\n\n-> Usage:\n123.300.0.101 ✗\n127.0.0.1 ✓\n192.168.0.1 ✓\n",
- "extension": "regex"
- },
- {
- "title": "Unintentional Duplication",
- "description": "Matches duplicated word in a text.",
- "author": "majvax",
- "tags": ["duplication"],
- "contributors": [],
- "code": "\\b(\\w+)\\s+\\1\\b\n\n\n-> Usage:\nI need to finish this task ✗\nI need to to finish this task ✓\n",
- "extension": "regex"
- },
- {
- "title": "Whitespace Trimmer",
- "description": "Matches leading and/or trailing whitespace.",
- "author": "majvax",
- "tags": ["trim"],
- "contributors": [],
- "code": "^\\s+|\\s+$\n\n\n-> Usage:\n(don't account for the quotation marks, it just to visualize whitespace)\n\"Hello World\" ✗\n\" Hello World\" ✓\n\"Hello World \" ✓\n\" Hello World \" ✓\n",
- "extension": "regex"
- }
- ]
- },
- {
- "name": "Validation pattern",
- "snippets": [
- {
- "title": "Email Address",
- "description": "Match any email address",
- "author": "majvax",
- "tags": ["email"],
- "contributors": [],
- "code": "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$\n\n-> Usage:\nexample.name@domain.com.ru ✓\nname.surname@gmail.com ✓\n",
- "extension": "regex"
- },
- {
- "title": "Strong Password",
- "description": "Match password with at least 12 characters, one uppercased letter, one number, and one special character.",
- "author": "majvax",
- "tags": ["password"],
- "contributors": [],
- "code": "^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{12,}$\n\n-> Usage:\nlongpassword ✗\nlongpassw0rd ✗\nlongp@ssw0rd ✗\nLongp@ssw0rd ✓\n",
- "extension": "regex"
- }
- ]
- }
-]
+ {
+ "name": "Miscellaneous",
+ "snippets": [
+ {
+ "title": "Hexadecimal Color",
+ "description": "Matches hex color codes",
+ "author": "majvax",
+ "tags": [
+ "color",
+ "hexadecimal"
+ ],
+ "contributors": [],
+ "code": "^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$\n\n\n-> Usage:\n#FFF1 ✗\n#FFF ✓\n#FFF000 ✓\n",
+ "extension": "regex"
+ },
+ {
+ "title": "IPv4",
+ "description": "Matches IPv4 address",
+ "author": "majvax",
+ "tags": [
+ "ipv4",
+ "networking"
+ ],
+ "contributors": [],
+ "code": "^((25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})$\n\n\n-> Usage:\n123.300.0.101 ✗\n127.0.0.1 ✓\n192.168.0.1 ✓\n",
+ "extension": "regex"
+ },
+ {
+ "title": "Unintentional Duplication",
+ "description": "Matches duplicated word in a text.",
+ "author": "majvax",
+ "tags": [
+ "duplication"
+ ],
+ "contributors": [],
+ "code": "\\b(\\w+)\\s+\\1\\b\n\n\n-> Usage:\nI need to finish this task ✗\nI need to to finish this task ✓\n",
+ "extension": "regex"
+ },
+ {
+ "title": "Whitespace Trimmer",
+ "description": "Matches leading and/or trailing whitespace.",
+ "author": "majvax",
+ "tags": [
+ "trim"
+ ],
+ "contributors": [],
+ "code": "^\\s+|\\s+$\n\n\n-> Usage:\n(don't account for the quotation marks, it just to visualize whitespace)\n\"Hello World\" ✗\n\" Hello World\" ✓\n\"Hello World \" ✓\n\" Hello World \" ✓\n",
+ "extension": "regex"
+ }
+ ]
+ },
+ {
+ "name": "Validation pattern",
+ "snippets": [
+ {
+ "title": "Email Address",
+ "description": "Match any email address",
+ "author": "majvax",
+ "tags": [
+ "email"
+ ],
+ "contributors": [],
+ "code": "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$\n\n-> Usage:\nexample.name@domain.com.ru ✓\nname.surname@gmail.com ✓\n",
+ "extension": "regex"
+ },
+ {
+ "title": "Strong Password",
+ "description": "Match password with at least 12 characters, one uppercased letter, one number, and one special character.",
+ "author": "majvax",
+ "tags": [
+ "password"
+ ],
+ "contributors": [],
+ "code": "^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{12,}$\n\n-> Usage:\nlongpassword ✗\nlongpassw0rd ✗\nlongp@ssw0rd ✗\nLongp@ssw0rd ✓\n",
+ "extension": "regex"
+ }
+ ]
+ }
+]
\ No newline at end of file
diff --git a/backend/data/consolidated/ruby.json b/backend/data/consolidated/ruby.json
index 45ad5a1d..be6449e3 100644
--- a/backend/data/consolidated/ruby.json
+++ b/backend/data/consolidated/ruby.json
@@ -1,177 +1,238 @@
[
- {
- "name": "Array Manipulation",
- "snippets": [
- {
- "title": "Binary Search",
- "description": "Searches for an element in a sorted array using binary search.",
- "author": "ACR1209",
- "tags": ["array", "binary-search", "search"],
- "contributors": [],
- "code": "def binary_search(array, target)\n low = 0\n high = array.length - 1\n\n while low <= high\n mid = (low + high) / 2\n guess = array[mid]\n\n if guess == target\n return mid\n elsif guess > target\n high = mid - 1\n else\n low = mid + 1\n end\n end\n\n return nil\nend\n\n# Usage:\narray = [1, 3, 5, 7, 9]\ntarget = 5\nresult = binary_search(array, target)\nputs result # Output: 2\n",
- "extension": "rb"
- },
- {
- "title": "Chunk Array",
- "description": "Splits an array into chunks of a specified size.",
- "author": "ACR1209",
- "tags": ["array", "chunk"],
- "contributors": [],
- "code": "def chunk_array(array, size)\n array.each_slice(size).to_a\nend\n\n# Usage:\narr = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nchunked_arr = chunk_array(arr, 2)\nputs chunked_arr.inspect # Output: [[1, 2], [3, 4], [5, 6], [7, 8], [9]]\n",
- "extension": "rb"
- },
- {
- "title": "Matrix Transpose",
- "description": "Transposes a 2D matrix.",
- "author": "ACR1209",
- "tags": ["array", "matrix", "transpose"],
- "contributors": [],
- "code": "def transpose_matrix(matrix)\n return [] if matrix.empty?\n return [] if matrix.first.empty?\n\n matrix.first.zip(*matrix[1..-1])\nend\n\n# Usage:\nmatrix = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n]\nprint transpose_matrix(matrix) # Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]\n",
- "extension": "ruby"
- }
- ]
- },
- {
- "name": "Basics",
- "snippets": [
- {
- "title": "Hello, World!",
- "description": "Prints Hello, World! to the terminal.",
- "author": "ACR1209",
- "tags": ["printing", "hello-world", "utility"],
- "contributors": [],
- "code": "puts 'Hello, World!'\n",
- "extension": "rb"
- }
- ]
- },
- {
- "name": "Error Handling",
- "snippets": [
- {
- "title": "Custom Error Class",
- "description": "Defines and raises a custom error class in Ruby.",
- "author": "ACR1209",
- "tags": ["error handling", "custom error"],
- "contributors": [],
- "code": "class MyCustomError < StandardError; end\n\ndef risky_method(value)\n raise MyCustomError, \"Value must be positive\" if value <= 0\n \"Valid value: #{value}\"\nend\n\n# Usage:\nbegin\n puts risky_method(-1)\nrescue MyCustomError => e\n puts e.message # Output: \"Value must be positive\"\nend\n",
- "extension": "rb"
- }
- ]
- },
- {
- "name": "Math And Numbers",
- "snippets": [
- {
- "title": "Calculate Compound Interest",
- "description": "Calculates compound interest for a given principal amount, rate, and time period.",
- "author": "ACR1209",
- "tags": ["math", "compound interest", "finance"],
- "contributors": ["axorax"],
- "code": "def compound_interest(principal, rate, time, n = 1)\n principal * (1 + rate / n) ** (n * time)\nend\n\n# Usage:\nputs compound_interest(1000, 0.05, 5) # Output: 1276.2815625000003\nputs compound_interest(1000, 0.05, 5, 12) # Output: 1283.3586785035118\n",
- "extension": "rb"
- },
- {
- "title": "Calculate Factorial",
- "description": "Computes the factorial of a given integer.",
- "author": "ACR1209",
- "tags": ["math", "factorial"],
- "contributors": [],
- "code": "def factorial(n)\n return 1 if n <= 1\n (2..n).reduce(1, :*)\nend\n\n# Usage:\nputs factorial(5) # Output: 120\n",
- "extension": "rb"
- },
- {
- "title": "Check Prime Number",
- "description": "Checks if a number is a prime number.",
- "author": "ACR1209",
- "tags": ["math", "prime", "check"],
- "contributors": ["technoph1le"],
- "code": "def is_prime?(n)\n return false if n <= 1\n (2..Math.sqrt(n)).each do |i|\n return false if n % i == 0\n end\n true\nend\n\n# Usage:\nputs is_prime?(29) # Output: true\nputs is_prime?(30) # Output: false\n",
- "extension": "rb"
- },
- {
- "title": "Find all primes up to integer (Sieve of Sundaram)",
- "description": "Finds all the prime numbers up to a specific integer.",
- "author": "ACR1209",
- "tags": ["math", "prime numbers"],
- "contributors": [],
- "code": "def sieve_of_sundaram(limit)\n n = (limit - 1) / 2\n marked = Array.new(n + 1, false)\n\n (1..n).each do |i|\n j = i\n while (i + j + 2 * i * j) <= n\n marked[i + j + 2 * i * j] = true\n j += 1\n end\n end\n\n primes = [2]\n (1..n).each do |i|\n primes << (2 * i + 1) unless marked[i]\n end\n\n primes\nend\n\n# Usage:\nprint sieve_of_sundaram(30) # Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n",
- "extension": "rb"
- }
- ]
- },
- {
- "name": "String Manipulation",
- "snippets": [
- {
- "title": "Capitalize Words",
- "description": "Capitalizes the first letter of each word in a string.",
- "author": "ACR1209",
- "tags": ["string", "capitalize", "words"],
- "contributors": [],
- "code": "def capitalize_words(str)\n str.split.map(&:capitalize).join(' ')\nend\n\n# Usage:\nsentence = \"ruby is awesome\"\nputs capitalize_words(sentence) # Output: \"Ruby Is Awesome\"\n",
- "extension": "rb"
- },
- {
- "title": "Count Word Occurrences in String",
- "description": "Counts the occurrences of each word in a given string.",
- "author": "ACR1209",
- "tags": ["string", "occurrences", "word-count"],
- "contributors": [],
- "code": "def count_word_occurrences(text)\n words = text.downcase.scan(/\\w+/)\n occurrences = Hash.new(0)\n words.each { |word| occurrences[word] += 1 }\n occurrences\nend\n\n# Usage:\ntext = \"ruby is awesome and Ruby is fun\"\nputs count_word_occurrences(text) # Output: {\"ruby\"=>2, \"is\"=>2, \"awesome\"=>1, \"and\"=>1, \"fun\"=>1}\n",
- "extension": "rb"
- },
- {
- "title": "Remove Punctuation",
- "description": "Removes all punctuation from a given string.",
- "author": "ACR1209",
- "tags": ["string", "punctuation", "remove"],
- "contributors": [],
- "code": "def remove_punctuation(str)\n str.gsub(/[[:punct:]]/, '')\nend\n\n# Usage:\ntext = \"Hello, Ruby! How's it going?\"\nputs remove_punctuation(text) # Output: \"Hello Ruby Hows it going\"\n",
- "extension": "rb"
- },
- {
- "title": "Transform Camel Case to Snake Case",
- "description": "Converts a Camel or Pascal Case string to Snake case.",
- "author": "ACR1209",
- "tags": [
- "string",
- "convert",
- "camel-case",
- "snake-case",
- "pascal-case"
- ],
- "contributors": [],
- "code": "def camel_to_snake(str)\n str.gsub(/([A-Z])/, '_\\1').sub(/^_/, '').downcase\nend\n\n# Usage:\ncamel_case = \"camelCaseToSnakeCase\"\npascal_case = \"PascalCaseToSnakeCase\"\nputs camel_to_snake(camel_case) # Output: \"camel_case_to_snake_case\"\nputs camel_to_snake(pascal_case) # Output: \"pascal_case_to_snake_case\"\n",
- "extension": "rb"
- },
- {
- "title": "Transform from Snake Case to Camel Case",
- "description": "Converts a Snake Case string to Camel Case.",
- "author": "ACR1209",
- "tags": ["string", "convert", "snake-case", "camel-case"],
- "contributors": [],
- "code": "def snake_to_camel(str)\n str.split('_').map.with_index { |word, index| \n index == 0 ? word : word.capitalize \n }.join\nend\n\n# Usage:\nsnake_case = \"snake_case_to_camel_case\"\nputs snake_to_camel(snake_case) # Output: \"snakeCaseToCamelCase\"\n",
- "extension": "rb"
- },
- {
- "title": "Transform from Snake Case to Pascal Case",
- "description": "Converts a Snake Case string to Pascal Case.",
- "author": "ACR1209",
- "tags": ["string", "convert", "snake-case", "pascal-case"],
- "contributors": [],
- "code": "def snake_to_pascal(str)\n str.split('_').map.with_index { |word, index| \n word.capitalize \n }.join\nend\n\n# Usage:\nsnake_case = \"snake_case_to_pascal_case\"\nputs snake_to_pascal(snake_case) # Output: \"SnakeCaseToPascalCase\"\n",
- "extension": "rb"
- },
- {
- "title": "Truncate String",
- "description": "Truncates a string to a specified length, optionally adding an ellipsis.",
- "author": "ACR1209",
- "tags": ["string", "truncate"],
- "contributors": [],
- "code": "def truncate_string(str, max_length)\n return str if str.length <= max_length || max_length <= 3\n str[0, max_length - 3] + '...'\nend\n\n# Usage:\nlong_string = \"Ruby is a dynamic, open source programming language.\"\nputs truncate_string(20, long_string) # Output: \"Ruby is a dynamic...\"\nputs truncate_string(54, long_string) # Output: \"Ruby is a dynamic, open source programming language.\"\n",
- "extension": "rb"
- }
- ]
- }
-]
+ {
+ "name": "Array Manipulation",
+ "snippets": [
+ {
+ "title": "Binary Search",
+ "description": "Searches for an element in a sorted array using binary search.",
+ "author": "ACR1209",
+ "tags": [
+ "array",
+ "binary-search",
+ "search"
+ ],
+ "contributors": [],
+ "code": "def binary_search(array, target)\n low = 0\n high = array.length - 1\n\n while low <= high\n mid = (low + high) / 2\n guess = array[mid]\n\n if guess == target\n return mid\n elsif guess > target\n high = mid - 1\n else\n low = mid + 1\n end\n end\n\n return nil\nend\n\n# Usage:\narray = [1, 3, 5, 7, 9]\ntarget = 5\nresult = binary_search(array, target)\nputs result # Output: 2\n",
+ "extension": "rb"
+ },
+ {
+ "title": "Chunk Array",
+ "description": "Splits an array into chunks of a specified size.",
+ "author": "ACR1209",
+ "tags": [
+ "array",
+ "chunk"
+ ],
+ "contributors": [],
+ "code": "def chunk_array(array, size)\n array.each_slice(size).to_a\nend\n\n# Usage:\narr = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nchunked_arr = chunk_array(arr, 2)\nputs chunked_arr.inspect # Output: [[1, 2], [3, 4], [5, 6], [7, 8], [9]]\n",
+ "extension": "rb"
+ },
+ {
+ "title": "Matrix Transpose",
+ "description": "Transposes a 2D matrix.",
+ "author": "ACR1209",
+ "tags": [
+ "array",
+ "matrix",
+ "transpose"
+ ],
+ "contributors": [],
+ "code": "def transpose_matrix(matrix)\n return [] if matrix.empty?\n return [] if matrix.first.empty?\n\n matrix.first.zip(*matrix[1..-1])\nend\n\n# Usage:\nmatrix = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n]\nprint transpose_matrix(matrix) # Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]\n",
+ "extension": "ruby"
+ }
+ ]
+ },
+ {
+ "name": "Basics",
+ "snippets": [
+ {
+ "title": "Hello, World!",
+ "description": "Prints Hello, World! to the terminal.",
+ "author": "ACR1209",
+ "tags": [
+ "printing",
+ "hello-world",
+ "utility"
+ ],
+ "contributors": [],
+ "code": "puts 'Hello, World!'\n",
+ "extension": "rb"
+ }
+ ]
+ },
+ {
+ "name": "Error Handling",
+ "snippets": [
+ {
+ "title": "Custom Error Class",
+ "description": "Defines and raises a custom error class in Ruby.",
+ "author": "ACR1209",
+ "tags": [
+ "error handling",
+ "custom error"
+ ],
+ "contributors": [],
+ "code": "class MyCustomError < StandardError; end\n\ndef risky_method(value)\n raise MyCustomError, \"Value must be positive\" if value <= 0\n \"Valid value: #{value}\"\nend\n\n# Usage:\nbegin\n puts risky_method(-1)\nrescue MyCustomError => e\n puts e.message # Output: \"Value must be positive\"\nend\n",
+ "extension": "rb"
+ }
+ ]
+ },
+ {
+ "name": "Math And Numbers",
+ "snippets": [
+ {
+ "title": "Calculate Compound Interest",
+ "description": "Calculates compound interest for a given principal amount, rate, and time period.",
+ "author": "ACR1209",
+ "tags": [
+ "math",
+ "compound interest",
+ "finance"
+ ],
+ "contributors": [
+ "axorax"
+ ],
+ "code": "def compound_interest(principal, rate, time, n = 1)\n principal * (1 + rate / n) ** (n * time)\nend\n\n# Usage:\nputs compound_interest(1000, 0.05, 5) # Output: 1276.2815625000003\nputs compound_interest(1000, 0.05, 5, 12) # Output: 1283.3586785035118\n",
+ "extension": "rb"
+ },
+ {
+ "title": "Calculate Factorial",
+ "description": "Computes the factorial of a given integer.",
+ "author": "ACR1209",
+ "tags": [
+ "math",
+ "factorial"
+ ],
+ "contributors": [],
+ "code": "def factorial(n)\n return 1 if n <= 1\n (2..n).reduce(1, :*)\nend\n\n# Usage:\nputs factorial(5) # Output: 120\n",
+ "extension": "rb"
+ },
+ {
+ "title": "Check Prime Number",
+ "description": "Checks if a number is a prime number.",
+ "author": "ACR1209",
+ "tags": [
+ "math",
+ "prime",
+ "check"
+ ],
+ "contributors": [
+ "technoph1le"
+ ],
+ "code": "def is_prime?(n)\n return false if n <= 1\n (2..Math.sqrt(n)).each do |i|\n return false if n % i == 0\n end\n true\nend\n\n# Usage:\nputs is_prime?(29) # Output: true\nputs is_prime?(30) # Output: false\n",
+ "extension": "rb"
+ },
+ {
+ "title": "Find all primes up to integer (Sieve of Sundaram)",
+ "description": "Finds all the prime numbers up to a specific integer.",
+ "author": "ACR1209",
+ "tags": [
+ "math",
+ "prime numbers"
+ ],
+ "contributors": [],
+ "code": "def sieve_of_sundaram(limit)\n n = (limit - 1) / 2\n marked = Array.new(n + 1, false)\n\n (1..n).each do |i|\n j = i\n while (i + j + 2 * i * j) <= n\n marked[i + j + 2 * i * j] = true\n j += 1\n end\n end\n\n primes = [2]\n (1..n).each do |i|\n primes << (2 * i + 1) unless marked[i]\n end\n\n primes\nend\n\n# Usage:\nprint sieve_of_sundaram(30) # Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n",
+ "extension": "rb"
+ }
+ ]
+ },
+ {
+ "name": "String Manipulation",
+ "snippets": [
+ {
+ "title": "Capitalize Words",
+ "description": "Capitalizes the first letter of each word in a string.",
+ "author": "ACR1209",
+ "tags": [
+ "string",
+ "capitalize",
+ "words"
+ ],
+ "contributors": [],
+ "code": "def capitalize_words(str)\n str.split.map(&:capitalize).join(' ')\nend\n\n# Usage:\nsentence = \"ruby is awesome\"\nputs capitalize_words(sentence) # Output: \"Ruby Is Awesome\"\n",
+ "extension": "rb"
+ },
+ {
+ "title": "Count Word Occurrences in String",
+ "description": "Counts the occurrences of each word in a given string.",
+ "author": "ACR1209",
+ "tags": [
+ "string",
+ "occurrences",
+ "word-count"
+ ],
+ "contributors": [],
+ "code": "def count_word_occurrences(text)\n words = text.downcase.scan(/\\w+/)\n occurrences = Hash.new(0)\n words.each { |word| occurrences[word] += 1 }\n occurrences\nend\n\n# Usage:\ntext = \"ruby is awesome and Ruby is fun\"\nputs count_word_occurrences(text) # Output: {\"ruby\"=>2, \"is\"=>2, \"awesome\"=>1, \"and\"=>1, \"fun\"=>1}\n",
+ "extension": "rb"
+ },
+ {
+ "title": "Remove Punctuation",
+ "description": "Removes all punctuation from a given string.",
+ "author": "ACR1209",
+ "tags": [
+ "string",
+ "punctuation",
+ "remove"
+ ],
+ "contributors": [],
+ "code": "def remove_punctuation(str)\n str.gsub(/[[:punct:]]/, '')\nend\n\n# Usage:\ntext = \"Hello, Ruby! How's it going?\"\nputs remove_punctuation(text) # Output: \"Hello Ruby Hows it going\"\n",
+ "extension": "rb"
+ },
+ {
+ "title": "Transform Camel Case to Snake Case",
+ "description": "Converts a Camel or Pascal Case string to Snake case.",
+ "author": "ACR1209",
+ "tags": [
+ "string",
+ "convert",
+ "camel-case",
+ "snake-case",
+ "pascal-case"
+ ],
+ "contributors": [],
+ "code": "def camel_to_snake(str)\n str.gsub(/([A-Z])/, '_\\1').sub(/^_/, '').downcase\nend\n\n# Usage:\ncamel_case = \"camelCaseToSnakeCase\"\npascal_case = \"PascalCaseToSnakeCase\"\nputs camel_to_snake(camel_case) # Output: \"camel_case_to_snake_case\"\nputs camel_to_snake(pascal_case) # Output: \"pascal_case_to_snake_case\"\n",
+ "extension": "rb"
+ },
+ {
+ "title": "Transform from Snake Case to Camel Case",
+ "description": "Converts a Snake Case string to Camel Case.",
+ "author": "ACR1209",
+ "tags": [
+ "string",
+ "convert",
+ "snake-case",
+ "camel-case"
+ ],
+ "contributors": [],
+ "code": "def snake_to_camel(str)\n str.split('_').map.with_index { |word, index| \n index == 0 ? word : word.capitalize \n }.join\nend\n\n# Usage:\nsnake_case = \"snake_case_to_camel_case\"\nputs snake_to_camel(snake_case) # Output: \"snakeCaseToCamelCase\"\n",
+ "extension": "rb"
+ },
+ {
+ "title": "Transform from Snake Case to Pascal Case",
+ "description": "Converts a Snake Case string to Pascal Case.",
+ "author": "ACR1209",
+ "tags": [
+ "string",
+ "convert",
+ "snake-case",
+ "pascal-case"
+ ],
+ "contributors": [],
+ "code": "def snake_to_pascal(str)\n str.split('_').map.with_index { |word, index| \n word.capitalize \n }.join\nend\n\n# Usage:\nsnake_case = \"snake_case_to_pascal_case\"\nputs snake_to_pascal(snake_case) # Output: \"SnakeCaseToPascalCase\"\n",
+ "extension": "rb"
+ },
+ {
+ "title": "Truncate String",
+ "description": "Truncates a string to a specified length, optionally adding an ellipsis.",
+ "author": "ACR1209",
+ "tags": [
+ "string",
+ "truncate"
+ ],
+ "contributors": [],
+ "code": "def truncate_string(str, max_length)\n return str if str.length <= max_length || max_length <= 3\n str[0, max_length - 3] + '...'\nend\n\n# Usage:\nlong_string = \"Ruby is a dynamic, open source programming language.\"\nputs truncate_string(20, long_string) # Output: \"Ruby is a dynamic...\"\nputs truncate_string(54, long_string) # Output: \"Ruby is a dynamic, open source programming language.\"\n",
+ "extension": "rb"
+ }
+ ]
+ }
+]
\ No newline at end of file
diff --git a/backend/data/consolidated/rust.json b/backend/data/consolidated/rust.json
index 530a3c02..7fd16cd1 100644
--- a/backend/data/consolidated/rust.json
+++ b/backend/data/consolidated/rust.json
@@ -1,67 +1,82 @@
[
- {
- "name": "Basics",
- "snippets": [
- {
- "title": "Hello, World!",
- "description": "Prints Hello, World! to the terminal.",
- "author": "James-Beans",
- "tags": ["printing", "hello-world"],
- "contributors": [],
- "code": "fn main() { // Defines the main running function\n println!(\"Hello, World!\"); // Prints Hello, World! to the terminal.\n}\n",
- "extension": "rust"
- }
- ]
- },
- {
- "name": "File Handling",
- "snippets": [
- {
- "title": "Find Files",
- "description": "Finds all files of the specified extension within a given directory.",
- "author": "Mathys-Gasnier",
- "tags": ["file", "search"],
- "contributors": [],
- "code": "fn find_files(directory: &str, file_type: &str) -> std::io::Result> {\n let mut result = vec![];\n\n for entry in std::fs::read_dir(directory)? {\n let dir = entry?;\n let path = dir.path();\n if dir.file_type().is_ok_and(|t| !t.is_file()) &&\n path.extension().is_some_and(|ext| ext != file_type) {\n continue;\n }\n result.push(path)\n }\n\n Ok(result)\n}\n\n// Usage:\nfind_files(\"/path/to/your/directory\", \".pdf\"); // Returns: if Ok(), a vector of path to `.pdf` files in the directory\n",
- "extension": "rust"
- },
- {
- "title": "Read File Lines",
- "description": "Reads all lines from a file and returns them as a vector of strings.",
- "author": "Mathys-Gasnier",
- "tags": ["file", "read"],
- "contributors": [],
- "code": "fn read_lines(file_name: &str) -> std::io::Result>\n Ok(\n std::fs::read_to_string(file_name)?\n .lines()\n .map(String::from)\n .collect()\n )\n}\n\n// Usage:\nread_lines(\"path/to/file.txt\"); // Returns: If Ok(), a Vec of the lines of the file\n",
- "extension": "rust"
- }
- ]
- },
- {
- "name": "Linux",
- "snippets": [
- {
- "title": "Get Desktop Enviroment",
- "description": "Get the Desktop Enviroment that the user is currently using.",
- "author": "sponkurtus2 ",
- "tags": ["linux", "file"],
- "contributors": [],
- "code": "fn get_desktop_env() -> String {\n // Return empty string if no X display is available\n if env::var(\"DISPLAY\").is_err() {\n return String::new();\n }\n\n // Check common desktop environment variables.\n for env_var in &[\n \"XDG_SESSION_DESKTOP\",\n \"XDG_CURRENT_DESKTOP\",\n \"DESKTOP_SESSION\",\n ] {\n if let Ok(de) = env::var(env_var) {\n return de;\n }\n }\n\n // As fallback, try to get desktop name from last word of last line in .xinitrc\n let path = format!(\"{}/.xinitrc\", env::var(\"HOME\").unwrap_or_default());\n if let Ok(mut file) = File::open(&path) {\n let mut buf = String::new();\n if file.read_to_string(&mut buf).is_ok() {\n if let Some(last_line) = buf.lines().last() {\n let last_word = last_line.split(' ').last().unwrap_or(\"\");\n return last_word.to_string();\n }\n }\n }\n\n // Return \"N/A\" if no desktop environment could be detected\n String::from(\"N/A\")\n}\n\n// Usage:\nget_desktop_env(); // Returns: the desktop enviroment that the user actually has e.g. i3.\n",
- "extension": "rust"
- }
- ]
- },
- {
- "name": "String Manipulation",
- "snippets": [
- {
- "title": "Capitalize String",
- "description": "Makes the first letter of a string uppercase.",
- "author": "Mathys-Gasnier",
- "tags": ["string", "capitalize"],
- "contributors": [],
- "code": "fn capitalized(str: &str) -> String {\n let mut chars = str.chars();\n match chars.next() {\n None => String::new(),\n Some(f) => f.to_uppercase().chain(chars).collect(),\n }\n}\n\n// Usage:\ncapitalized(\"lower_case\"); // Returns: Lower_case\n",
- "extension": "rust"
- }
- ]
- }
-]
+ {
+ "name": "Basics",
+ "snippets": [
+ {
+ "title": "Hello, World!",
+ "description": "Prints Hello, World! to the terminal.",
+ "author": "James-Beans",
+ "tags": [
+ "printing",
+ "hello-world"
+ ],
+ "contributors": [],
+ "code": "fn main() { // Defines the main running function\n println!(\"Hello, World!\"); // Prints Hello, World! to the terminal.\n}\n",
+ "extension": "rust"
+ }
+ ]
+ },
+ {
+ "name": "File Handling",
+ "snippets": [
+ {
+ "title": "Find Files",
+ "description": "Finds all files of the specified extension within a given directory.",
+ "author": "Mathys-Gasnier",
+ "tags": [
+ "file",
+ "search"
+ ],
+ "contributors": [],
+ "code": "fn find_files(directory: &str, file_type: &str) -> std::io::Result