diff --git a/public/consolidated/c.json b/public/consolidated/c.json index aa8d1803..a9a23234 100644 --- a/public/consolidated/c.json +++ b/public/consolidated/c.json @@ -6,12 +6,12 @@ "title": "Hello, World!", "description": "Prints Hello, World! to the terminal.", "author": "0xHouss", - "code": "#include // Includes the input/output library\n\nint main() { // Defines the main function\n printf(\"Hello, World!\\n\") // Outputs Hello, World! and a newline\n\n return 0; // indicate the program executed successfully\n}\n", "tags": [ "printing", "hello-world" ], - "contributors": [] + "contributors": [], + "code": "#include // Includes the input/output library\n\nint main() { // Defines the main function\n printf(\"Hello, World!\\n\") // Outputs Hello, World! and a newline\n\n return 0; // indicate the program executed successfully\n}\n" } ] }, @@ -22,12 +22,12 @@ "title": "Factorial Function", "description": "Calculates the factorial of a number.", "author": "0xHouss", - "code": "int factorial(int x) {\n int y = 1;\n\n for (int i = 2; i <= x; i++)\n y *= i;\n\n return y;\n}\n\n// Usage:\nfactorial(4); // Returns: 24\n", "tags": [ "math", "factorial" ], - "contributors": [] + "contributors": [], + "code": "int factorial(int x) {\n int y = 1;\n\n for (int i = 2; i <= x; i++)\n y *= i;\n\n return y;\n}\n\n// Usage:\nfactorial(4); // Returns: 24\n" } ] } diff --git a/public/consolidated/cpp.json b/public/consolidated/cpp.json index 7a0b9e36..e560e82d 100644 --- a/public/consolidated/cpp.json +++ b/public/consolidated/cpp.json @@ -6,12 +6,12 @@ "title": "Hello, World!", "description": "Prints Hello, World! to the terminal.", "author": "James-Beans", - "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", "tags": [ "printing", "hello-world" ], - "contributors": [] + "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" } ] }, @@ -22,13 +22,13 @@ "title": "Vector to Queue", "description": "Convert vector into queue quickly", "author": "mrityunjay2003", - "code": "#include\n#include\n#include\n\nstd::queue vectorToQueue(const std::vector& v) {\n return std::queue(std::deque(v.begin(), v.end()));\n}\n\nstd::vector vec = { 1, 2, 3, 4, 5 };\nvectorToQueue(&vec); // Returns: std::queue { 1, 2, 3, 4, 5 }\n", "tags": [ "data structures", "queue", "vector" ], - "contributors": [] + "contributors": [], + "code": "#include\n#include\n#include\n\nstd::queue vectorToQueue(const std::vector& v) {\n return std::queue(std::deque(v.begin(), v.end()));\n}\n\nstd::vector vec = { 1, 2, 3, 4, 5 };\nvectorToQueue(&vec); // Returns: std::queue { 1, 2, 3, 4, 5 }\n" } ] }, @@ -39,12 +39,12 @@ "title": "Check Prime Number", "description": "Check if an integer is a prime number", "author": "MihneaMoso", - "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", "tags": [ "number", "prime" ], - "contributors": [] + "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" } ] }, @@ -55,23 +55,23 @@ "title": "Reverse String", "description": "Reverses the characters in a string.", "author": "Vaibhav-kesarwani", - "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", "tags": [ "array", "reverse" ], - "contributors": [] + "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" }, { "title": "Split String", "description": "Splits a string by a delimiter", "author": "saminjay", - "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", "tags": [ "string", "split" ], - "contributors": [] + "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" } ] } diff --git a/public/consolidated/csharp.json b/public/consolidated/csharp.json index 5fe902e4..63ff0ec1 100644 --- a/public/consolidated/csharp.json +++ b/public/consolidated/csharp.json @@ -6,12 +6,12 @@ "title": "Hello, World!", "description": "Prints Hello, World! to the terminal.", "author": "chaitanya-jvnm", - "code": "public class Program {\n public static void Main(string[] args) {\n System.Console.WriteLine(\"Hello, World!\");\n }\n}\n", "tags": [ "printing", "hello-world" ], - "contributors": [] + "contributors": [], + "code": "public class Program {\n public static void Main(string[] args) {\n System.Console.WriteLine(\"Hello, World!\");\n }\n}\n" } ] }, @@ -22,23 +22,23 @@ "title": "Generate GUID", "description": "Generates a new GUID", "author": "chaitanya-jvnm", - "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", "tags": [ "guid", "generate" ], - "contributors": [] + "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" }, { "title": "Validate GUID", "description": "Checks if a string is a valid GUID.", "author": "chaitanya-jvnm", - "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", "tags": [ "guid", "validate" ], - "contributors": [] + "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" } ] }, @@ -49,23 +49,23 @@ "title": "Decode JWT", "description": "Decodes a JWT.", "author": "chaitanya-jvnm", - "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", "tags": [ "jwt", "decode" ], - "contributors": [] + "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" }, { "title": "Validate JWT", "description": "Validates a JWT.", "author": "chaitanya-jvnm", - "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", "tags": [ "jwt", "validate" ], - "contributors": [] + "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" } ] }, @@ -76,12 +76,12 @@ "title": "Swap items at index", "description": "Swaps two items at determined indexes", "author": "omegaleo", - "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", "tags": [ "list", "swapping" ], - "contributors": [] + "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" } ] }, @@ -92,23 +92,23 @@ "title": "Capitalize first letter", "description": "Makes the first letter of a string uppercase.", "author": "chaitanya-jvnm", - "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", "tags": [ "string", "capitalize" ], - "contributors": [] + "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" }, { "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", - "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", "tags": [ "string", "truncate" ], - "contributors": [] + "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" } ] } diff --git a/public/consolidated/css.json b/public/consolidated/css.json index f6acdac0..b759c611 100644 --- a/public/consolidated/css.json +++ b/public/consolidated/css.json @@ -6,38 +6,38 @@ "title": "3D Button Effect", "description": "Adds a 3D effect to a button when clicked.", "author": "dostonnabotov", - "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", "tags": [ "button", "3D", "effect" ], - "contributors": [] + "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" }, { "title": "Button Hover Effect", "description": "Creates a hover effect with a color transition.", "author": "dostonnabotov", - "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", "tags": [ "button", "hover", "transition" ], - "contributors": [] + "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" }, { "title": "MacOS Button", "description": "A macOS-like button style, with hover and shading effects.", "author": "e3nviction", - "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", "tags": [ "button", "macos", "hover", "transition" ], - "contributors": [] + "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" } ] }, @@ -48,37 +48,37 @@ "title": "Blur Background", "description": "Applies a blur effect to the background of an element.", "author": "dostonnabotov", - "code": ".blur-background {\n backdrop-filter: blur(10px);\n background: rgba(255, 255, 255, 0.5);\n}\n", "tags": [ "blur", "background", "effects" ], - "contributors": [] + "contributors": [], + "code": ".blur-background {\n backdrop-filter: blur(10px);\n background: rgba(255, 255, 255, 0.5);\n}\n" }, { "title": "Hover Glow Effect", "description": "Adds a glowing effect on hover.", "author": "dostonnabotov", - "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", "tags": [ "hover", "glow", "effects" ], - "contributors": [] + "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" }, { "title": "Hover to Reveal Color", "description": "A card with an image that transitions from grayscale to full color on hover.", "author": "Haider-Mukhtar", - "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", "tags": [ "hover", "image", "effects" ], - "contributors": [] + "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" } ] }, @@ -89,59 +89,59 @@ "title": "CSS Reset", "description": "Resets some default browser styles, ensuring consistency across browsers.", "author": "AmeerMoustafa", - "code": "* {\n margin: 0;\n padding: 0;\n box-sizing: border-box\n}\n", "tags": [ "reset", "browser", "layout" ], - "contributors": [] + "contributors": [], + "code": "* {\n margin: 0;\n padding: 0;\n box-sizing: border-box\n}\n" }, { "title": "Equal-Width Columns", "description": "Creates columns with equal widths using flexbox.", "author": "dostonnabotov", - "code": ".columns {\n display: flex;\n justify-content: space-between;\n}\n\n.column {\n flex: 1;\n margin: 0 10px;\n}\n", "tags": [ "flexbox", "columns", "layout" ], - "contributors": [] + "contributors": [], + "code": ".columns {\n display: flex;\n justify-content: space-between;\n}\n\n.column {\n flex: 1;\n margin: 0 10px;\n}\n" }, { "title": "Grid layout", "description": "Equal sized items in a responsive grid", "author": "xshubhamg", - "code": ".grid-container {\n display: grid\n grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));\n/* Explanation:\n- `auto-fit`: Automatically fits as many columns as possible within the container.\n- `minmax(250px, 1fr)`: Defines a minimum column size of 250px and a maximum size of 1fr (fraction of available space).\n*/\n}\n", "tags": [ "layout", "grid" ], - "contributors": [] + "contributors": [], + "code": ".grid-container {\n display: grid\n grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));\n/* Explanation:\n- `auto-fit`: Automatically fits as many columns as possible within the container.\n- `minmax(250px, 1fr)`: Defines a minimum column size of 250px and a maximum size of 1fr (fraction of available space).\n*/\n}\n" }, { "title": "Responsive Design", "description": "The different responsive breakpoints.", "author": "kruimol", - "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", "tags": [ "responsive", "media queries" ], - "contributors": [] + "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" }, { "title": "Sticky Footer", "description": "Ensures the footer always stays at the bottom of the page.", "author": "dostonnabotov", - "code": "body {\n display: flex;\n flex-direction: column;\n min-height: 100vh;\n}\n\nfooter {\n margin-top: auto;\n}\n", "tags": [ "layout", "footer", "sticky" ], - "contributors": [] + "contributors": [], + "code": "body {\n display: flex;\n flex-direction: column;\n min-height: 100vh;\n}\n\nfooter {\n margin-top: auto;\n}\n" } ] }, @@ -152,24 +152,24 @@ "title": "Letter Spacing", "description": "Adds space between letters for better readability.", "author": "dostonnabotov", - "code": "p {\n letter-spacing: 0.05em;\n}\n", "tags": [ "typography", "spacing" ], - "contributors": [] + "contributors": [], + "code": "p {\n letter-spacing: 0.05em;\n}\n" }, { "title": "Responsive Font Sizing", "description": "Adjusts font size based on viewport width.", "author": "dostonnabotov", - "code": "h1 {\n font-size: calc(1.5rem + 2vw);\n}\n", "tags": [ "font", "responsive", "typography" ], - "contributors": [] + "contributors": [], + "code": "h1 {\n font-size: calc(1.5rem + 2vw);\n}\n" } ] } diff --git a/public/consolidated/haskell.json b/public/consolidated/haskell.json index 35f79386..b4a97f3c 100644 --- a/public/consolidated/haskell.json +++ b/public/consolidated/haskell.json @@ -6,37 +6,37 @@ "title": "Binary Search", "description": "Searches for an element in a sorted array using binary search.", "author": "ACR1209", - "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", "tags": [ "array", "binary-search", "search" ], - "contributors": [] + "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" }, { "title": "Chunk Array", "description": "Splits an array into chunks of a specified size.", "author": "ACR1209", - "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", "tags": [ "array", "chunk", "utility" ], - "contributors": [] + "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" }, { "title": "Matrix Transpose", "description": "Transposes a 2D matrix.", "author": "ACR1209", - "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", "tags": [ "array", "matrix", "transpose" ], - "contributors": [] + "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" } ] }, @@ -47,13 +47,13 @@ "title": "Hello, World!", "description": "Prints Hello, World! to the terminal.", "author": "ACR1209", - "code": "putStrLn \"Hello, World!\"\n", "tags": [ "printing", "hello-world", "utility" ], - "contributors": [] + "contributors": [], + "code": "putStrLn \"Hello, World!\"\n" } ] }, @@ -64,27 +64,27 @@ "title": "Find Files in Directory by Type", "description": "Finds all files in a directory with a specific extension.", "author": "ACR1209", - "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", "tags": [ "file", "search", "extension", "filesystem" ], - "contributors": [] + "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" }, { "title": "Read File in Chunks", "description": "Reads a file in chunks grouped by lines.", "author": "ACR1209", - "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", "tags": [ "file", "read", "chunks", "utility" ], - "contributors": [] + "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" } ] }, @@ -95,48 +95,48 @@ "title": "Either Monad for Error Handling", "description": "Using the Either monad to handle errors in a computation.", "author": "ACR1209", - "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", "tags": [ "monads", "either", "error handling" ], - "contributors": [] + "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" }, { "title": "Maybe Monad", "description": "Using the Maybe monad to handle computations that might fail.", "author": "ACR1209", - "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", "tags": [ "monads", "maybe" ], - "contributors": [] + "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" }, { "title": "State Monad", "description": "Managing mutable state using the State monad.", "author": "ACR1209", - "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", "tags": [ "monads", "state", "state-management" ], - "contributors": [] + "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" }, { "title": "Writer Monad", "description": "Using the Writer monad to accumulate logs or other outputs alongside a computation.", "author": "ACR1209", - "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", "tags": [ "monads", "writer", "logs" ], - "contributors": [] + "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" } ] }, @@ -147,7 +147,6 @@ "title": "CamelCase to snake_case", "description": "Converts a Camel Case string to Snake case.", "author": "ACR1209", - "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", "tags": [ "string", "convert", @@ -155,49 +154,49 @@ "snake-case", "utility" ], - "contributors": [] + "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" }, { "title": "Capitalize Words", "description": "Capitalizes the first letter of each word in a string.", "author": "ACR1209", - "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", "tags": [ "string", "capitalize", "words" ], - "contributors": [] + "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" }, { "title": "Count Word Occurrences in String", "description": "Counts the occurrences of each word in a given string.", "author": "ACR1209", - "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", "tags": [ "string", "occurrences", "word-count" ], - "contributors": [] + "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" }, { "title": "Remove Punctuation", "description": "Removes all punctuation from a given string.", "author": "ACR1209", - "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", "tags": [ "string", "punctuation", "remove" ], - "contributors": [] + "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" }, { "title": "Snake_Case to CamelCase", "description": "Converts a Snake Case string to Camel Case.", "author": "ACR1209", - "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", "tags": [ "string", "convert", @@ -205,19 +204,20 @@ "camel-case", "utilty" ], - "contributors": [] + "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" }, { "title": "Truncate String", "description": "Truncates a string to a specified length, optionally adding an ellipsis.", "author": "ACR1209", - "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", "tags": [ "string", "truncate", "utility" ], - "contributors": [] + "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" } ] } diff --git a/public/consolidated/html.json b/public/consolidated/html.json index ba1201e2..f7635148 100644 --- a/public/consolidated/html.json +++ b/public/consolidated/html.json @@ -6,7 +6,6 @@ "title": "Grid Layout with Navigation", "description": "Full-height grid layout with header navigation using nesting syntax.", "author": "GreenMan36", - "code": "\n\n \n \n \n \n
\n Header\n \n
\n
Main Content
\n
Footer
\n \n\n", "tags": [ "css", "layout", @@ -14,13 +13,13 @@ "grid", "full-height" ], - "contributors": [] + "contributors": [], + "code": "\n\n \n \n \n \n
\n Header\n \n
\n
Main Content
\n
Footer
\n \n\n" }, { "title": "Sticky Header-Footer Layout", "description": "Full-height layout with sticky header and footer, using modern viewport units and flexbox.", "author": "GreenMan36", - "code": "\n\n \n \n \n \n
header
\n
body/content
\n
footer
\n \n\n", "tags": [ "css", "layout", @@ -28,7 +27,8 @@ "flexbox", "viewport" ], - "contributors": [] + "contributors": [], + "code": "\n\n \n \n \n \n
header
\n
body/content
\n
footer
\n \n\n" } ] } diff --git a/public/consolidated/java.json b/public/consolidated/java.json index 06aadb7d..f00ab589 100644 --- a/public/consolidated/java.json +++ b/public/consolidated/java.json @@ -6,13 +6,13 @@ "title": "Hello-World", "description": "Prints Hello world in the console", "author": "SarvariHarshitha", - "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", "tags": [ "java", "console", "printing" ], - "contributors": [] + "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" } ] } diff --git a/public/consolidated/javascript.json b/public/consolidated/javascript.json index 38244992..c7b78ff8 100644 --- a/public/consolidated/javascript.json +++ b/public/consolidated/javascript.json @@ -6,58 +6,58 @@ "title": "Partition Array", "description": "Splits an array into two arrays based on a callback function.", "author": "Swaraj-Singh-30", - "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", "tags": [ "array", "partition", "reduce" ], - "contributors": [] + "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" }, { "title": "Remove Duplicates", "description": "Removes duplicate values from an array.", "author": "dostonnabotov", - "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", "tags": [ "array", "deduplicate" ], - "contributors": [] + "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" }, { "title": "Remove Falsy Values", "description": "Removes falsy values from an array.", "author": "mubasshir", - "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", "tags": [ "array", "falsy", "filter" ], - "contributors": [] + "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" }, { "title": "Shuffle Array", "description": "Shuffles an Array.", "author": "loxt-nixo", - "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", "tags": [ "array", "shuffle" ], - "contributors": [] + "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" }, { "title": "Zip Arrays", "description": "Combines two arrays by pairing corresponding elements from each array.", "author": "Swaraj-Singh-30", - "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", "tags": [ "array", "map" ], - "contributors": [] + "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" } ] }, @@ -68,12 +68,12 @@ "title": "Hello, World!", "description": "Prints Hello, World! to the terminal.", "author": "James-Beans", - "code": "console.log(\"Hello, World!\"); // Prints Hello, World! to the console\n", "tags": [ "printing", "hello-world" ], - "contributors": [] + "contributors": [], + "code": "console.log(\"Hello, World!\"); // Prints Hello, World! to the console\n" } ] }, @@ -85,10 +85,8 @@ "description": "Converts RGB color values to hexadecimal color code.", "author": "jjcantu", "tags": [ - "javascript", "color", - "conversion", - "utility" + "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" @@ -102,74 +100,73 @@ "title": "Check Leap Year", "description": "Determines if a given year is a leap year.", "author": "axorax", - "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", "tags": [ "date", "leap-year" ], - "contributors": [] + "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" }, { "title": "Convert to Unix Timestamp", "description": "Converts a date to a Unix timestamp in seconds.", "author": "Yugveer06", - "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", "tags": [ "date", "unix", "timestamp" ], - "contributors": [] + "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" }, { "title": "Format Date", "description": "Formats a date in 'YYYY-MM-DD' format.", "author": "dostonnabotov", - "code": "const formatDate = (date) => date.toISOString().split('T')[0];\n\n// Usage:\nformatDate(new Date(2024, 11, 10)); // Returns: '2024-12-10'\n", "tags": [ "date", "format" ], - "contributors": [] + "contributors": [], + "code": "const formatDate = (date) => date.toISOString().split('T')[0];\n\n// Usage:\nformatDate(new Date(2024, 11, 10)); // Returns: '2024-12-10'\n" }, { "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", - "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", "tags": [ "date", "day-of-year" ], - "contributors": [] + "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" }, { "title": "Get Days in Month", "description": "Calculates the number of days in a specific month of a given year.", "author": "axorax", - "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", "tags": [ "date", "days-in-month" ], - "contributors": [] + "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" }, { "title": "Get Time Difference", "description": "Calculates the time difference in days between two dates.", "author": "dostonnabotov", - "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", "tags": [ "date", "time-difference" ], - "contributors": [] + "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" }, { "title": "Relative Time Formatter", "description": "Displays how long ago a date occurred or how far in the future a date is.", "author": "Yugveer06", - "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", "tags": [ "date", "time", @@ -177,18 +174,19 @@ "future", "past" ], - "contributors": [] + "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" }, { "title": "Start of the Day", "description": "Returns the start of the day (midnight) for a given date.", "author": "axorax", - "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", "tags": [ "date", "start-of-day" ], - "contributors": [] + "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" } ] }, @@ -199,23 +197,23 @@ "title": "Change Element Style", "description": "Changes the inline style of an element.", "author": "axorax", - "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", "tags": [ "dom", "style" ], - "contributors": [] + "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" }, { "title": "Remove Element", "description": "Removes a specified element from the DOM.", "author": "axorax", - "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", "tags": [ "dom", "remove" ], - "contributors": [] + "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" } ] }, @@ -226,97 +224,96 @@ "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", - "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", "tags": [ "function", "compose" ], - "contributors": [] + "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" }, { "title": "Curry Function", "description": "Transforms a function into its curried form.", "author": "axorax", - "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", "tags": [ "curry", "function" ], - "contributors": [] + "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" }, { "title": "Debounce Function", "description": "Delays a function execution until after a specified time.", "author": "dostonnabotov", - "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", "tags": [ "debounce", "performance" ], - "contributors": [] + "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" }, { "title": "Get Contrast Color", "description": "Returns either black or white text color based on the brightness of the provided hex color.", "author": "yaya12085", - "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", "tags": [ "color", "hex", "contrast", "brightness" ], - "contributors": [] + "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" }, { "title": "Memoize Function", "description": "Caches the result of a function based on its arguments to improve performance.", "author": "axorax", - "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", "tags": [ "memoization", "optimization" ], - "contributors": [] + "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" }, { "title": "Once Function", "description": "Ensures a function is only called once.", "author": "axorax", - "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", "tags": [ "function", "once" ], - "contributors": [] + "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" }, { "title": "Rate Limit Function", "description": "Limits how often a function can be executed within a given time window.", "author": "axorax", - "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", "tags": [ "function", "rate-limiting" ], - "contributors": [] + "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" }, { "title": "Repeat Function Invocation", "description": "Invokes a function a specified number of times.", "author": "dostonnabotov", - "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", "tags": [ "function", "repeat" ], - "contributors": [] + "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" }, { "title": "Sleep Function", "description": "Waits for a specified amount of milliseconds before resolving.", "author": "0xHouss", - "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", "tags": [ "javascript", "sleep", @@ -324,7 +321,8 @@ "utility", "promises" ], - "contributors": [] + "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" } ] }, @@ -335,34 +333,34 @@ "title": "Add Item to localStorage", "description": "Stores a value in localStorage under the given key.", "author": "dostonnabotov", - "code": "const addToLocalStorage = (key, value) => {\n localStorage.setItem(key, JSON.stringify(value));\n};\n\n// Usage:\naddToLocalStorage('user', { name: 'John', age: 30 });\n", "tags": [ "localStorage", "storage" ], - "contributors": [] + "contributors": [], + "code": "const addToLocalStorage = (key, value) => {\n localStorage.setItem(key, JSON.stringify(value));\n};\n\n// Usage:\naddToLocalStorage('user', { name: 'John', age: 30 });\n" }, { "title": "Check if Item Exists in localStorage", "description": "Checks if a specific item exists in localStorage.", "author": "axorax", - "code": "const isItemInLocalStorage = (key) => {\n return localStorage.getItem(key) !== null;\n};\n\n// Usage:\nconsole.log(isItemInLocalStorage('user')); // Output: true or false\n", "tags": [ "localStorage", "storage" ], - "contributors": [] + "contributors": [], + "code": "const isItemInLocalStorage = (key) => {\n return localStorage.getItem(key) !== null;\n};\n\n// Usage:\nconsole.log(isItemInLocalStorage('user')); // Output: true or false\n" }, { "title": "Retrieve Item from localStorage", "description": "Retrieves a value from localStorage by key and parses it.", "author": "dostonnabotov", - "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", "tags": [ "localStorage", "storage" ], - "contributors": [] + "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" } ] }, @@ -373,44 +371,42 @@ "title": "Convert Number to Currency", "description": "Converts a number to a currency format with a specific locale.", "author": "axorax", - "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", "tags": [ "number", "currency" ], - "contributors": [] + "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" }, { "title": "Convert Number to Roman Numerals", "description": "Converts a number to Roman numeral representation.", "author": "axorax", - "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", "tags": [ "number", "roman" ], - "contributors": [] + "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" }, { "title": "Convert to Scientific Notation", "description": "Converts a number to scientific notation.", "author": "axorax", - "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", "tags": [ "number", "scientific" ], - "contributors": [] + "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" }, { "title": "Format File Size", "description": "Converts bytes into human-readable file size format.", "author": "jjcantu", "tags": [ - "javascript", "format", - "size", - "utility" + "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" @@ -419,34 +415,34 @@ "title": "Format Number with Commas", "description": "Formats a number with commas for better readability (e.g., 1000 -> 1,000).", "author": "axorax", - "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", "tags": [ "number", "format" ], - "contributors": [] + "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" }, { "title": "Number Formatter", "description": "Formats a number with suffixes (K, M, B, etc.).", "author": "realvishalrana", - "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", "tags": [ "number", "format" ], - "contributors": [] + "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" }, { "title": "Number to Words Converter", "description": "Converts a number to its word representation in English.", "author": "axorax", - "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", "tags": [ "number", "words" ], - "contributors": [] + "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" } ] }, @@ -457,163 +453,161 @@ "title": "Check if Object is Empty", "description": "Checks whether an object has no own enumerable properties.", "author": "axorax", - "code": "function isEmptyObject(obj) {\n return Object.keys(obj).length === 0;\n}\n\n// Usage:\nisEmptyObject({}); // Returns: true\nisEmptyObject({ a: 1 }); // Returns: false\n", "tags": [ "object", "check", "empty" ], - "contributors": [] + "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" }, { "title": "Compare Two Objects Shallowly", "description": "Compares two objects shallowly and returns whether they are equal.", "author": "axorax", - "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", "tags": [ "object", "compare", "shallow" ], - "contributors": [] + "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" }, { "title": "Convert Object to Query String", "description": "Converts an object to a query string for use in URLs.", "author": "axorax", - "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", "tags": [ "object", "query string", "url" ], - "contributors": [] + "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" }, { "title": "Count Properties in Object", "description": "Counts the number of own properties in an object.", "author": "axorax", - "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", "tags": [ "object", "count", "properties" ], - "contributors": [] + "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" }, { "title": "Deep Clone Object", "description": "Creates a deep copy of an object or array without reference.", "author": "jjcantu", "tags": [ - "javascript", "object", - "clone", - "utility" + "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: { a: 1, b: { c: 2 }, d: [1, 2, 3] }\n" + "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" }, { "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", - "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", "tags": [ "object", "filter" ], - "contributors": [] + "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" }, { "title": "Flatten Nested Object", "description": "Flattens a nested object into a single-level object with dot notation for keys.", "author": "axorax", - "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", "tags": [ "object", "flatten" ], - "contributors": [] + "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" }, { "title": "Freeze Object", "description": "Freezes an object to make it immutable.", "author": "axorax", - "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", "tags": [ "object", "freeze", "immutable" ], - "contributors": [] + "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" }, { "title": "Get Nested Value", "description": "Retrieves the value at a given path in a nested object.", "author": "realvishalrana", - "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", "tags": [ "object", "nested" ], - "contributors": [] + "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" }, { "title": "Invert Object Keys and Values", "description": "Creates a new object by swapping keys and values of the given object.", "author": "axorax", - "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", "tags": [ "object", "invert" ], - "contributors": [] + "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" }, { "title": "Merge Objects Deeply", "description": "Deeply merges two or more objects, including nested properties.", "author": "axorax", - "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", "tags": [ "object", "merge", "deep" ], - "contributors": [] + "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" }, { "title": "Omit Keys from Object", "description": "Creates a new object with specific keys omitted.", "author": "axorax", - "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", "tags": [ "object", "omit" ], - "contributors": [] + "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" }, { "title": "Pick Keys from Object", "description": "Creates a new object with only the specified keys.", "author": "axorax", - "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", "tags": [ "object", "pick" ], - "contributors": [] + "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" }, { "title": "Unique By Key", "description": "Filters an array of objects to only include unique objects by a specified key.", "author": "realvishalrana", - "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", "tags": [ "array", "unique" ], - "contributors": [] + "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" } ] }, @@ -624,143 +618,143 @@ "title": "Capitalize String", "description": "Capitalizes the first letter of a string.", "author": "dostonnabotov", - "code": "function capitalize(str) {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n// Usage:\ncapitalize('hello'); // Returns: 'Hello'\n", "tags": [ "string", "capitalize" ], - "contributors": [] + "contributors": [], + "code": "function capitalize(str) {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n// Usage:\ncapitalize('hello'); // Returns: 'Hello'\n" }, { "title": "Check if String is a Palindrome", "description": "Checks whether a given string is a palindrome.", "author": "axorax", - "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", "tags": [ "check", "palindrome", "string" ], - "contributors": [] + "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" }, { "title": "Convert String to Camel Case", "description": "Converts a given string into camelCase.", "author": "aumirza", - "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", "tags": [ "string", "case", "camelCase" ], - "contributors": [] + "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" }, { "title": "Convert String to Param Case", "description": "Converts a given string into param-case.", "author": "aumirza", - "code": "function toParamCase(str) {\n return str.toLowerCase().replace(/\\s+/g, '-');\n}\n\n// Usage:\ntoParamCase('Hello World Test'); // Returns: 'hello-world-test'\n", "tags": [ "string", "case", "paramCase" ], - "contributors": [] + "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" }, { "title": "Convert String to Pascal Case", "description": "Converts a given string into Pascal Case.", "author": "aumirza", - "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", "tags": [ "string", "case", "pascalCase" ], - "contributors": [] + "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" }, { "title": "Convert String to Snake Case", "description": "Converts a given string into snake_case.", "author": "axorax", - "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", "tags": [ "string", "case", "snake_case" ], - "contributors": [] + "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" }, { "title": "Convert String to Title Case", "description": "Converts a given string into Title Case.", "author": "aumirza", - "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", "tags": [ "string", "case", "titleCase" ], - "contributors": [] + "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" }, { "title": "Convert Tabs to Spaces", "description": "Converts all tab characters in a string to spaces.", "author": "axorax", - "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", "tags": [ "string", "tabs", "spaces" ], - "contributors": [] + "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" }, { "title": "Count Words in a String", "description": "Counts the number of words in a string.", "author": "axorax", - "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", "tags": [ "string", "manipulation", "word count", "count" ], - "contributors": [] + "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" }, { "title": "Data with Prefix", "description": "Adds a prefix and postfix to data, with a fallback value.", "author": "realvishalrana", - "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", "tags": [ "data", "prefix", "postfix", "format" ], - "contributors": [] + "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" }, { "title": "Extract Initials from Name", "description": "Extracts and returns the initials from a full name.", "author": "axorax", - "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", "tags": [ "string", "initials", "name" ], - "contributors": [] + "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" }, { "title": "Generate UUID", "description": "Generates a UUID (v4) string.", "author": "jjcantu", "tags": [ - "javascript", "uuid", - "utility" + "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" @@ -769,93 +763,93 @@ "title": "Mask Sensitive Information", "description": "Masks parts of a sensitive string, like a credit card or email address.", "author": "axorax", - "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", "tags": [ "string", "mask", "sensitive" ], - "contributors": [] + "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" }, { "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", - "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", "tags": [ "string", "pad", "manipulation" ], - "contributors": [] + "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" }, { "title": "Random string", "description": "Generates a random string of characters of a certain length", "author": "kruimol", - "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", "tags": [ "function", "random" ], - "contributors": [] + "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" }, { "title": "Remove All Whitespace", "description": "Removes all whitespace from a string.", "author": "axorax", - "code": "function removeWhitespace(str) {\n return str.replace(/\\s+/g, '');\n}\n\n// Usage:\nremoveWhitespace('Hello world!'); // Returns: 'Helloworld!'\n", "tags": [ "string", "whitespace" ], - "contributors": [] + "contributors": [], + "code": "function removeWhitespace(str) {\n return str.replace(/\\s+/g, '');\n}\n\n// Usage:\nremoveWhitespace('Hello world!'); // Returns: 'Helloworld!'\n" }, { "title": "Remove Vowels from a String", "description": "Removes all vowels from a given string.", "author": "axorax", - "code": "function removeVowels(str) {\n return str.replace(/[aeiouAEIOU]/g, '');\n}\n\n// Usage:\nremoveVowels('Hello World'); // Returns: 'Hll Wrld'\n", "tags": [ "string", "remove", "vowels" ], - "contributors": [] + "contributors": [], + "code": "function removeVowels(str) {\n return str.replace(/[aeiouAEIOU]/g, '');\n}\n\n// Usage:\nremoveVowels('Hello World'); // Returns: 'Hll Wrld'\n" }, { "title": "Reverse String", "description": "Reverses the characters in a string.", "author": "dostonnabotov", - "code": "const reverseString = (str) => str.split('').reverse().join('');\n\n// Usage:\nreverseString('hello'); // Returns: 'olleh'\n", "tags": [ "string", "reverse" ], - "contributors": [] + "contributors": [], + "code": "const reverseString = (str) => str.split('').reverse().join('');\n\n// Usage:\nreverseString('hello'); // Returns: 'olleh'\n" }, { "title": "Slugify String", "description": "Converts a string into a URL-friendly slug format.", "author": "dostonnabotov", - "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", "tags": [ "string", "slug" ], - "contributors": [] + "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" }, { "title": "Truncate Text", "description": "Truncates the text to a maximum length and appends '...' if the text exceeds the maximum length.", "author": "realvishalrana", - "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", "tags": [ "string", "truncate", "text" ], - "contributors": [] + "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" } ] } diff --git a/public/consolidated/python.json b/public/consolidated/python.json index 86b32ceb..953272b8 100644 --- a/public/consolidated/python.json +++ b/public/consolidated/python.json @@ -6,12 +6,12 @@ "title": "Hello, World!", "description": "Prints Hello, World! to the terminal.", "author": "James-Beans", - "code": "print(\"Hello, World!\") # Prints Hello, World! to the terminal.\n", "tags": [ "printing", "hello-world" ], - "contributors": [] + "contributors": [], + "code": "print(\"Hello, World!\") # Prints Hello, World! to the terminal.\n" } ] }, @@ -22,79 +22,79 @@ "title": "Calculate Date Difference in Milliseconds", "description": "Calculates the difference between two dates in milliseconds.", "author": "e3nviction", - "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", "tags": [ "datetime", "difference" ], - "contributors": [] + "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" }, { "title": "Check if Date is a Weekend", "description": "Checks whether a given date falls on a weekend.", "author": "axorax", - "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", "tags": [ "datetime", "weekend" ], - "contributors": [] + "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" }, { "title": "Day of the Week String", "description": "Gets the string of the day of the week for a given date.", "author": "axorax", - "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", "tags": [ "datetime", "weekday" ], - "contributors": [] + "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" }, { "title": "Generate Date Range List", "description": "Generates a list of dates between two given dates.", "author": "axorax", - "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", "tags": [ "datetime", "range" ], - "contributors": [] + "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" }, { "title": "Get Current Date and Time as String", "description": "Fetches the current date and time as a formatted string.", "author": "e3nviction", - "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", "tags": [ "datetime", "current", "string" ], - "contributors": [] + "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" }, { "title": "Get Number of Days in a Month", "description": "Determines the number of days in a specific month and year.", "author": "axorax", - "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", "tags": [ "datetime", "calendar" ], - "contributors": [] + "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" }, { "title": "Measure Execution Time", "description": "Measures the execution time of a code block.", "author": "dostonnabotov", - "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", "tags": [ "time", "execution" ], - "contributors": [] + "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" } ] }, @@ -105,25 +105,25 @@ "title": "Create Custom Exception Type", "description": "Create a Custom Exception Type that can be called with raise.", "author": "mrcool7387", - "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", "tags": [ "python", "error-creation", "organisation", "utility" ], - "contributors": [] + "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" }, { "title": "Retry Function Execution on Exception", "description": "Retries a function execution a specified number of times if it raises an exception.", "author": "axorax", - "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", "tags": [ "error-handling", "retry" ], - "contributors": [] + "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" } ] }, @@ -134,48 +134,48 @@ "title": "Find Files", "description": "Finds all files of the specified type within a given directory.", "author": "Jackeastern", - "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", "tags": [ "os", "filesystem", "file_search" ], - "contributors": [] + "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" }, { "title": "Get File Extension", "description": "Gets the extension of a file.", "author": "axorax", - "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", "tags": [ "file", "extension" ], - "contributors": [] + "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" }, { "title": "List Files in Directory", "description": "Lists all files in a specified directory.", "author": "axorax", - "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", "tags": [ "file", "list", "directory" ], - "contributors": [] + "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" }, { "title": "Read File in Chunks", "description": "Reads a file in chunks of a specified size.", "author": "axorax", - "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", "tags": [ "file", "read", "chunks" ], - "contributors": [] + "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" } ] }, @@ -186,73 +186,73 @@ "title": "Filter JSON Data", "description": "Filters a JSON object based on a condition and returns the filtered data.", "author": "axorax", - "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", "tags": [ "json", "filter", "data" ], - "contributors": [] + "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" }, { "title": "Flatten Nested JSON", "description": "Flattens a nested JSON object into a flat dictionary.", "author": "axorax", - "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", "tags": [ "json", "flatten", "nested" ], - "contributors": [] + "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" }, { "title": "Merge Multiple JSON Files", "description": "Merges multiple JSON files into one and writes the merged data into a new file.", "author": "axorax", - "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", "tags": [ "json", "merge", "file" ], - "contributors": [] + "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" }, { "title": "Read JSON File", "description": "Reads a JSON file and parses its content.", "author": "e3nviction", - "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", "tags": [ "json", "file", "read" ], - "contributors": [] + "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" }, { "title": "Update JSON File", "description": "Updates an existing JSON file with new data or modifies the existing values.", "author": "axorax", - "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", "tags": [ "json", "update", "file" ], - "contributors": [] + "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" }, { "title": "Write JSON File", "description": "Writes a dictionary to a JSON file.", "author": "e3nviction", - "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", "tags": [ "json", "file", "write" ], - "contributors": [] + "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" } ] }, @@ -263,81 +263,81 @@ "title": "Find Duplicates in a List", "description": "Identifies duplicate elements in a list.", "author": "axorax", - "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", "tags": [ "list", "duplicates" ], - "contributors": [] + "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" }, { "title": "Find Intersection of Two Lists", "description": "Finds the common elements between two lists.", "author": "axorax", - "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", "tags": [ "list", "intersection" ], - "contributors": [] + "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" }, { "title": "Find Maximum Difference in List", "description": "Finds the maximum difference between any two elements in a list.", "author": "axorax", - "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", "tags": [ "list", "difference" ], - "contributors": [] + "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" }, { "title": "Flatten Nested List", "description": "Flattens a multi-dimensional list into a single list.", "author": "dostonnabotov", - "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", "tags": [ "list", "flatten" ], - "contributors": [] + "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" }, { "title": "Flatten Unevenly Nested Lists", "description": "Converts unevenly nested lists of any depth into a single flat list.", "author": "agilarasu", - "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", "tags": [ "list", "flattening", "nested-lists", "depth" ], - "contributors": [] + "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" }, { "title": "Partition List", "description": "Partitions a list into sublists of a given size.", "author": "axorax", - "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", "tags": [ "list", "partition" ], - "contributors": [] + "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" }, { "title": "Remove Duplicates", "description": "Removes duplicate elements from a list while maintaining order.", "author": "dostonnabotov", - "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", "tags": [ "list", "duplicates", "filter" ], - "contributors": [] + "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" } ] }, @@ -348,68 +348,67 @@ "title": "Calculate Compound Interest", "description": "Calculates compound interest for a given principal amount, rate, and time period.", "author": "axorax", - "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", "tags": [ "python", "math", "compound interest", "finance" ], - "contributors": [] + "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" }, { "title": "Check Perfect Square", "description": "Checks if a number is a perfect square.", "author": "axorax", - "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", "tags": [ "math", "perfect square", "check" ], - "contributors": [] + "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" }, { "title": "Check Prime Number", "description": "Checks if a number is a prime number.", "author": "dostonnabotov", - "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", "tags": [ "math", "prime", "check" ], - "contributors": [] + "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" }, { "title": "Convert Binary to Decimal", "description": "Converts a binary string to its decimal equivalent.", "author": "axorax", - "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", "tags": [ "math", "binary", "decimal", "conversion" ], - "contributors": [] + "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" }, { "title": "Convert Bytes to Human-Readable Format", "description": "Converts a size in bytes to a human-readable format.", "author": "axorax", - "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", "tags": [ "bytes", "format" ], - "contributors": [] + "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" }, { "title": "Find LCM (Least Common Multiple)", "description": "Calculates the least common multiple (LCM) of two numbers.", "author": "axorax", - "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", "tags": [ "python", "math", @@ -417,20 +416,21 @@ "gcd", "utility" ], - "contributors": [] + "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" }, { "title": "Solve Quadratic Equation", "description": "Solves a quadratic equation ax^2 + bx + c = 0 and returns the roots.", "author": "axorax", - "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", "tags": [ "math", "quadratic", "equation", "solver" ], - "contributors": [] + "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" } ] }, @@ -441,46 +441,46 @@ "title": "Create SQLite Database Table", "description": "Creates a table in an SQLite database with a dynamic schema.", "author": "e3nviction", - "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", "tags": [ "sqlite", "database", "table" ], - "contributors": [] + "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" }, { "title": "Insert Data into Sqlite Table", "description": "Inserts a row into a specified SQLite table using a dictionary of fields and values.", "author": "e3nviction", - "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", "tags": [ "sqlite", "database" ], - "contributors": [] + "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" }, { "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", - "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", "tags": [ "sqlite", "database" ], - "contributors": [] + "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" }, { "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", - "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", "tags": [ "sqlite", "database" ], - "contributors": [] + "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" } ] }, @@ -491,222 +491,222 @@ "title": "Capitalize Words", "description": "Capitalizes the first letter of each word in a string.", "author": "axorax", - "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", "tags": [ "string", "capitalize" ], - "contributors": [] + "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" }, { "title": "Check Anagram", "description": "Checks if two strings are anagrams of each other.", "author": "SteliosGee", - "code": "def is_anagram(s1, s2):\n return sorted(s1) == sorted(s2)\n\n# Usage:\nis_anagram('listen', 'silent') # Returns: True\n", "tags": [ "string", "anagram", "check" ], - "contributors": [] + "contributors": [], + "code": "def is_anagram(s1, s2):\n return sorted(s1) == sorted(s2)\n\n# Usage:\nis_anagram('listen', 'silent') # Returns: True\n" }, { "title": "Check Palindrome", "description": "Checks if a string is a palindrome.", "author": "dostonnabotov", - "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", "tags": [ "string", "palindrome" ], - "contributors": [] + "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" }, { "title": "Convert Snake Case to Camel Case", "description": "Converts a snake_case string to camelCase.", "author": "axorax", - "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", "tags": [ "string", "snake-case", "camel-case", "convert" ], - "contributors": [] + "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" }, { "title": "Convert String to ASCII", "description": "Converts a string into its ASCII representation.", "author": "axorax", - "code": "def string_to_ascii(s):\n return [ord(char) for char in s]\n\n# Usage:\nstring_to_ascii('hello') # Returns: [104, 101, 108, 108, 111]\n", "tags": [ "string", "ascii", "convert" ], - "contributors": [] + "contributors": [], + "code": "def string_to_ascii(s):\n return [ord(char) for char in s]\n\n# Usage:\nstring_to_ascii('hello') # Returns: [104, 101, 108, 108, 111]\n" }, { "title": "Count Character Frequency", "description": "Counts the frequency of each character in a string.", "author": "axorax", - "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", "tags": [ "string", "character-frequency" ], - "contributors": [] + "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" }, { "title": "Count Vowels", "description": "Counts the number of vowels in a string.", "author": "SteliosGee", - "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", "tags": [ "string", "vowels", "count" ], - "contributors": [] + "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" }, { "title": "Count Words", "description": "Counts the number of words in a string.", "author": "axorax", - "code": "def count_words(s):\n return len(s.split())\n\n# Usage:\ncount_words('The quick brown fox') # Returns: 4\n", "tags": [ "string", "word-count" ], - "contributors": [] + "contributors": [], + "code": "def count_words(s):\n return len(s.split())\n\n# Usage:\ncount_words('The quick brown fox') # Returns: 4\n" }, { "title": "Find All Substrings", "description": "Finds all substrings of a given string.", "author": "axorax", - "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", "tags": [ "string", "substring", "find" ], - "contributors": [] + "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" }, { "title": "Find Longest Word", "description": "Finds the longest word in a string.", "author": "axorax", - "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", "tags": [ "string", "longest-word" ], - "contributors": [] + "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" }, { "title": "Find Unique Characters", "description": "Finds all unique characters in a string.", "author": "axorax", - "code": "def find_unique_chars(s):\n return ''.join(sorted(set(s)))\n\n# Usage:\nfind_unique_chars('banana') # Results: 'abn'\n", "tags": [ "string", "unique", "characters" ], - "contributors": [] + "contributors": [], + "code": "def find_unique_chars(s):\n return ''.join(sorted(set(s)))\n\n# Usage:\nfind_unique_chars('banana') # Results: 'abn'\n" }, { "title": "Generate Random String", "description": "Generates a random alphanumeric string.", "author": "dostonnabotov", - "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", "tags": [ "random", "string" ], - "contributors": [] + "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" }, { "title": "Remove Duplicate Characters", "description": "Removes duplicate characters from a string while maintaining the order.", "author": "axorax", - "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", "tags": [ "string", "duplicates", "remove" ], - "contributors": [] + "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" }, { "title": "Remove Punctuation", "description": "Removes punctuation from a string.", "author": "SteliosGee", - "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", "tags": [ "string", "punctuation", "remove" ], - "contributors": [] + "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" }, { "title": "Remove Specific Characters", "description": "Removes specific characters from a string.", "author": "axorax", - "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", "tags": [ "string", "remove", "characters" ], - "contributors": [] + "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" }, { "title": "Remove Whitespace", "description": "Removes all whitespace from a string.", "author": "axorax", - "code": "def remove_whitespace(s):\n return ''.join(s.split())\n\n# Usage:\nremove_whitespace('hello world') # Returns: 'helloworld'\n", "tags": [ "string", "whitespace", "remove" ], - "contributors": [] + "contributors": [], + "code": "def remove_whitespace(s):\n return ''.join(s.split())\n\n# Usage:\nremove_whitespace('hello world') # Returns: 'helloworld'\n" }, { "title": "Reverse String", "description": "Reverses the characters in a string.", "author": "dostonnabotov", - "code": "def reverse_string(s):\n return s[::-1]\n\n# Usage:\nreverse_string('hello') # Returns: 'olleh'\n", "tags": [ "string", "reverse" ], - "contributors": [] + "contributors": [], + "code": "def reverse_string(s):\n return s[::-1]\n\n# Usage:\nreverse_string('hello') # Returns: 'olleh'\n" }, { "title": "Split Camel Case", "description": "Splits a camel case string into separate words.", "author": "axorax", - "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", "tags": [ "string", "camel-case", "split" ], - "contributors": [] + "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" }, { "title": "Truncate String", "description": "Truncates a string to a specified length and adds an ellipsis.", "author": "axorax", - "code": "def truncate_string(s, length):\n return s[:length] + '...' if len(s) > length else s\n\n# Usage:\ntruncate_string('This is a long string', 10) # Returns: 'This is a ...'\n", "tags": [ "string", "truncate" ], - "contributors": [] + "contributors": [], + "code": "def truncate_string(s, length):\n return s[:length] + '...' if len(s) > length else s\n\n# Usage:\ntruncate_string('This is a long string', 10) # Returns: 'This is a ...'\n" } ] } diff --git a/public/consolidated/rust.json b/public/consolidated/rust.json index d8eb2297..4a150d77 100644 --- a/public/consolidated/rust.json +++ b/public/consolidated/rust.json @@ -6,12 +6,12 @@ "title": "Hello, World!", "description": "Prints Hello, World! to the terminal.", "author": "James-Beans", - "code": "fn main() { // Defines the main running function\n println!(\"Hello, World!\"); // Prints Hello, World! to the terminal.\n}\n", "tags": [ "printing", "hello-world" ], - "contributors": [] + "contributors": [], + "code": "fn main() { // Defines the main running function\n println!(\"Hello, World!\"); // Prints Hello, World! to the terminal.\n}\n" } ] }, @@ -22,23 +22,23 @@ "title": "Find Files", "description": "Finds all files of the specified extension within a given directory.", "author": "Mathys-Gasnier", - "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", "tags": [ "file", "search" ], - "contributors": [] + "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" }, { "title": "Read File Lines", "description": "Reads all lines from a file and returns them as a vector of strings.", "author": "Mathys-Gasnier", - "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", "tags": [ "file", "read" ], - "contributors": [] + "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" } ] }, @@ -49,12 +49,12 @@ "title": "Capitalize String", "description": "Makes the first letter of a string uppercase.", "author": "Mathys-Gasnier", - "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", "tags": [ "string", "capitalize" ], - "contributors": [] + "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" } ] } diff --git a/public/consolidated/scss.json b/public/consolidated/scss.json index 1b7e05c6..dd8414b1 100644 --- a/public/consolidated/scss.json +++ b/public/consolidated/scss.json @@ -6,25 +6,25 @@ "title": "Fade In Animation", "description": "Animates the fade-in effect.", "author": "dostonnabotov", - "code": "@keyframes fade-in {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n@mixin fade-in($duration: 1s, $easing: ease-in-out) {\n animation: fade-in $duration $easing;\n}\n", "tags": [ "animation", "fade", "css" ], - "contributors": [] + "contributors": [], + "code": "@keyframes fade-in {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n@mixin fade-in($duration: 1s, $easing: ease-in-out) {\n animation: fade-in $duration $easing;\n}\n" }, { "title": "Slide In From Left", "description": "Animates content sliding in from the left.", "author": "dostonnabotov", - "code": "@keyframes slide-in-left {\n from {\n transform: translateX(-100%);\n }\n to {\n transform: translateX(0);\n }\n}\n\n@mixin slide-in-left($duration: 0.5s, $easing: ease-out) {\n animation: slide-in-left $duration $easing;\n}\n", "tags": [ "animation", "slide", "css" ], - "contributors": [] + "contributors": [], + "code": "@keyframes slide-in-left {\n from {\n transform: translateX(-100%);\n }\n to {\n transform: translateX(0);\n }\n}\n\n@mixin slide-in-left($duration: 0.5s, $easing: ease-out) {\n animation: slide-in-left $duration $easing;\n}\n" } ] }, @@ -35,25 +35,25 @@ "title": "Border Radius Helper", "description": "Applies a customizable border-radius.", "author": "dostonnabotov", - "code": "@mixin border-radius($radius: 4px) {\n border-radius: $radius;\n}\n", "tags": [ "border", "radius", "css" ], - "contributors": [] + "contributors": [], + "code": "@mixin border-radius($radius: 4px) {\n border-radius: $radius;\n}\n" }, { "title": "Box Shadow Helper", "description": "Generates a box shadow with customizable values.", "author": "dostonnabotov", - "code": "@mixin box-shadow($x: 0px, $y: 4px, $blur: 10px, $spread: 0px, $color: rgba(0, 0, 0, 0.1)) {\n box-shadow: $x $y $blur $spread $color;\n}\n", "tags": [ "box-shadow", "css", "effects" ], - "contributors": [] + "contributors": [], + "code": "@mixin box-shadow($x: 0px, $y: 4px, $blur: 10px, $spread: 0px, $color: rgba(0, 0, 0, 0.1)) {\n box-shadow: $x $y $blur $spread $color;\n}\n" } ] }, @@ -64,13 +64,13 @@ "title": "Primary Button", "description": "Generates a styled primary button.", "author": "dostonnabotov", - "code": "@mixin primary-button($bg: #007bff, $color: #fff) {\n background-color: $bg;\n color: $color;\n padding: 0.5rem 1rem;\n border: none;\n border-radius: 4px;\n cursor: pointer;\n\n &:hover {\n background-color: darken($bg, 10%);\n }\n}\n", "tags": [ "button", "primary", "css" ], - "contributors": [] + "contributors": [], + "code": "@mixin primary-button($bg: #007bff, $color: #fff) {\n background-color: $bg;\n color: $color;\n padding: 0.5rem 1rem;\n border: none;\n border-radius: 4px;\n cursor: pointer;\n\n &:hover {\n background-color: darken($bg, 10%);\n }\n}\n" } ] }, @@ -81,19 +81,18 @@ "title": "Aspect Ratio", "description": "Ensures that elements maintain a specific aspect ratio.", "author": "dostonnabotov", - "code": "@mixin aspect-ratio($width, $height) {\n position: relative;\n width: 100%;\n padding-top: ($height / $width) * 100%;\n > * {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n }\n}\n", "tags": [ "aspect-ratio", "layout", "css" ], - "contributors": [] + "contributors": [], + "code": "@mixin aspect-ratio($width, $height) {\n position: relative;\n width: 100%;\n padding-top: ($height / $width) * 100%;\n > * {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n }\n}\n" }, { "title": "Dark Theme", "description": "SCSS mixin to change styles for dark themes.", "author": "gihanrangana", - "code": "@mixin isDark($type: 'module') {\n $root: &;\n\n @if $type == 'module' {\n :global {\n @at-root body[theme='dark'] #{$root} {\n @content;\n }\n }\n } @else {\n &[theme='dark'] {\n @content;\n }\n }\n}\n\n// Usage:\n.container{\n\tbackground: #f0f0f0;\n\t@include isDark {\n\t\tbackground: #222;\n\t}\n}\n", "tags": [ "css", "mixin", @@ -101,31 +100,32 @@ "dark-theme", "layout" ], - "contributors": [] + "contributors": [], + "code": "@mixin isDark($type: 'module') {\n $root: &;\n\n @if $type == 'module' {\n :global {\n @at-root body[theme='dark'] #{$root} {\n @content;\n }\n }\n } @else {\n &[theme='dark'] {\n @content;\n }\n }\n}\n\n// Usage:\n.container{\n\tbackground: #f0f0f0;\n\t@include isDark {\n\t\tbackground: #222;\n\t}\n}\n" }, { "title": "Flex Center", "description": "A mixin to center content using flexbox.", "author": "dostonnabotov", - "code": "@mixin flex-center {\n display: flex;\n justify-content: center;\n align-items: center;\n}\n", "tags": [ "flex", "center", "css" ], - "contributors": [] + "contributors": [], + "code": "@mixin flex-center {\n display: flex;\n justify-content: center;\n align-items: center;\n}\n" }, { "title": "Grid Container", "description": "Creates a responsive grid container with customizable column counts.", "author": "dostonnabotov", - "code": "@mixin grid-container($columns: 12, $gap: 1rem) {\n display: grid;\n grid-template-columns: repeat($columns, 1fr);\n gap: $gap;\n}\n", "tags": [ "grid", "layout", "css" ], - "contributors": [] + "contributors": [], + "code": "@mixin grid-container($columns: 12, $gap: 1rem) {\n display: grid;\n grid-template-columns: repeat($columns, 1fr);\n gap: $gap;\n}\n" } ] }, @@ -136,50 +136,50 @@ "title": "Font Import Helper", "description": "Simplifies importing custom fonts in Sass.", "author": "dostonnabotov", - "code": "@mixin import-font($family, $weight: 400, $style: normal) {\n @font-face {\n font-family: #{$family};\n font-weight: #{$weight};\n font-style: #{$style};\n src: url('/fonts/#{$family}-#{$weight}.woff2') format('woff2'),\n url('/fonts/#{$family}-#{$weight}.woff') format('woff');\n }\n}\n", "tags": [ "mixin", "fonts", "css" ], - "contributors": [] + "contributors": [], + "code": "@mixin import-font($family, $weight: 400, $style: normal) {\n @font-face {\n font-family: #{$family};\n font-weight: #{$weight};\n font-style: #{$style};\n src: url('/fonts/#{$family}-#{$weight}.woff2') format('woff2'),\n url('/fonts/#{$family}-#{$weight}.woff') format('woff');\n }\n}\n" }, { "title": "Line Clamp Mixin", "description": "A Sass mixin to clamp text to a specific number of lines.", "author": "dostonnabotov", - "code": "@mixin line-clamp($number) {\n display: -webkit-box;\n -webkit-box-orient: vertical;\n -webkit-line-clamp: $number;\n overflow: hidden;\n}\n", "tags": [ "mixin", "typography", "css" ], - "contributors": [] + "contributors": [], + "code": "@mixin line-clamp($number) {\n display: -webkit-box;\n -webkit-box-orient: vertical;\n -webkit-line-clamp: $number;\n overflow: hidden;\n}\n" }, { "title": "Text Gradient", "description": "Adds a gradient color effect to text.", "author": "dostonnabotov", - "code": "@mixin text-gradient($from, $to) {\n background: linear-gradient(to right, $from, $to);\n -webkit-background-clip: text;\n -webkit-text-fill-color: transparent;\n}\n", "tags": [ "mixin", "gradient", "text", "css" ], - "contributors": [] + "contributors": [], + "code": "@mixin text-gradient($from, $to) {\n background: linear-gradient(to right, $from, $to);\n -webkit-background-clip: text;\n -webkit-text-fill-color: transparent;\n}\n" }, { "title": "Text Overflow Ellipsis", "description": "Ensures long text is truncated with an ellipsis.", "author": "dostonnabotov", - "code": "@mixin text-ellipsis {\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n", "tags": [ "mixin", "text", "css" ], - "contributors": [] + "contributors": [], + "code": "@mixin text-ellipsis {\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n" } ] }, @@ -190,25 +190,25 @@ "title": "Clearfix", "description": "Provides a clearfix utility for floating elements.", "author": "dostonnabotov", - "code": "@mixin clearfix {\n &::after {\n content: '';\n display: block;\n clear: both;\n }\n}\n", "tags": [ "clearfix", "utility", "css" ], - "contributors": [] + "contributors": [], + "code": "@mixin clearfix {\n &::after {\n content: '';\n display: block;\n clear: both;\n }\n}\n" }, { "title": "Responsive Breakpoints", "description": "Generates media queries for responsive design.", "author": "dostonnabotov", - "code": "@mixin breakpoint($breakpoint) {\n @if $breakpoint == sm {\n @media (max-width: 576px) { @content; }\n } @else if $breakpoint == md {\n @media (max-width: 768px) { @content; }\n } @else if $breakpoint == lg {\n @media (max-width: 992px) { @content; }\n } @else if $breakpoint == xl {\n @media (max-width: 1200px) { @content; }\n }\n}\n", "tags": [ "responsive", "media-queries", "css" ], - "contributors": [] + "contributors": [], + "code": "@mixin breakpoint($breakpoint) {\n @if $breakpoint == sm {\n @media (max-width: 576px) { @content; }\n } @else if $breakpoint == md {\n @media (max-width: 768px) { @content; }\n } @else if $breakpoint == lg {\n @media (max-width: 992px) { @content; }\n } @else if $breakpoint == xl {\n @media (max-width: 1200px) { @content; }\n }\n}\n" } ] } diff --git a/public/consolidated/typescript.json b/public/consolidated/typescript.json index 3a11ec37..98a0680b 100644 --- a/public/consolidated/typescript.json +++ b/public/consolidated/typescript.json @@ -6,13 +6,13 @@ "title": "Exclusive Types", "description": "Allows to have a type which conforms to either/or.", "author": "px-d", - "code": "type Exclusive = T | U extends Record\n ?\n | ({ [P in Exclude]?: never } & U)\n | ({ [P in Exclude]?: never } & T)\n : T | U;\n\n\n// Usage:\ntype A = { name: string; email?: string; provider?: string };\ntype B = { name: string; phone?: string; country?: string };\n\ntype EitherOr = Exclusive;\n\nconst w: EitherOr = { name: \"John\", email: \"j@d.c\" }; // ✅\nconst x: EitherOr = { name: \"John\", phone: \"+123 456\" }; // ✅\nconst y: EitherOr = { name: \"John\", email: \"\", phone: \"\" }; // ⛔️\nconst z: EitherOr = { name: \"John\", phne: \"\", provider: \"\" }; // ⛔️\n", "tags": [ "typescript", "helper-types", "typedefinition" ], - "contributors": [] + "contributors": [], + "code": "type Exclusive = T | U extends Record\n ?\n | ({ [P in Exclude]?: never } & U)\n | ({ [P in Exclude]?: never } & T)\n : T | U;\n\n\n// Usage:\ntype A = { name: string; email?: string; provider?: string };\ntype B = { name: string; phone?: string; country?: string };\n\ntype EitherOr = Exclusive;\n\nconst w: EitherOr = { name: \"John\", email: \"j@d.c\" }; // ✅\nconst x: EitherOr = { name: \"John\", phone: \"+123 456\" }; // ✅\nconst y: EitherOr = { name: \"John\", email: \"\", phone: \"\" }; // ⛔️\nconst z: EitherOr = { name: \"John\", phne: \"\", provider: \"\" }; // ⛔️\n" } ] } diff --git a/utils/snippetParser.ts b/utils/snippetParser.ts index 09482b47..cff74f5d 100644 --- a/utils/snippetParser.ts +++ b/utils/snippetParser.ts @@ -76,7 +76,6 @@ function parseSnippet(snippetPath, name, text) { title: properties.title, description: properties.description, author: properties.author, - code, tags: properties.tags .split(",") .map((tag) => tag.trim()) @@ -85,6 +84,7 @@ function parseSnippet(snippetPath, name, text) { .split(",") .map((contributor) => contributor.trim()) .filter((contributor) => contributor), + code, }; }