diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..d01653a8 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +text eol=lf diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index feb9e7be..c7ed00c9 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,6 +1,8 @@ + + # Description - + ## Type of Change diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3d2503c2..8dd13a55 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -18,28 +18,65 @@ If you have a feature request or want to fix a bug, feel free to: --- +## Snippets Guidelines + +### Snippet Tags + +Tags must describe the snippet with simple word. \ +For example a snippet that capitalize a word would have `string` and `capitalize` as tags. \ +**! Do not add the language you are using as a tag, nor some generic keyword like `utility` !** + +### Snippet Format + +**All** snippets should follow the following structure: +- A `code` segment, containing a function with the actual snippet functionnality +- An `example` segement, containing one or more examples of use + +Example in javascript: +```js +function example(x) { + return x * 2; +} + +// Usage: +example(5) // Returns: 10 +``` +If your function doesn't return anything just show how to use it. \ +If the result of your function is too complicated to be expressed in a single comment, your snippet is probably too complex to begin with. + +### Snippet boundaries + +To **check if your snippet will not get refused** ask yourself those questions: +- **Does the standard library of my language provide an easy way of doing this ?** +- **Does that snippet have a real, and practical use case ?** +- **Could it be split into separate parts to be better understood ?** + +If one of question is true, then your snippet will most likely get refused ! + +--- + ## Adding Snippets ### Adding a New Snippet -To add a new code snippet: +1. **Ensure your snippet match [guidelines](#snippets-guidelines)** -1. **Navigate to the relevant folder:** +2. **Navigate to the relevant folder:** - Go to the `/snippets` folder in the root directory. - Locate the folder for the programming language of your snippet, such as `javascript` or `python`. -2. **Choose the correct category:** +3. **Choose the correct category:** - Within the language folder, find the relevant category folder for your snippet. - If no suitable category exists, refer to [Adding a New Category](#adding-a-new-category). -3. **Create a markdown file:** +4. **Create a markdown file:** - Create a new file with a `.md` extension. - Name the file appropriately, keeping it descriptive and concise. -4. **Add your snippet:** +5. **Add your snippet:** - Use the following format to structure your snippet: @@ -74,11 +111,11 @@ console.log(formatDate(new Date())); // Output: '2024-12-10' ``` ```` -5. **Use syntax highlighting:** +6. **Use syntax highlighting:** - Enclose your code with triple backticks (```). - Specify the language after the first set of backticks for syntax highlighting. -6. **Test your snippet:** +7. **Test your snippet:** - Ensure your code runs as expected. \ To test that your snippets are formatted correctly use the `snippets:check` script: ``` diff --git a/cspell-dict.txt b/cspell-dict.txt index aae6809b..4d39d3eb 100644 --- a/cspell-dict.txt +++ b/cspell-dict.txt @@ -1 +1,2 @@ quicksnip +slugifyed diff --git a/public/consolidated/c.json b/public/consolidated/c.json index b9a0e854..a9a23234 100644 --- a/public/consolidated/c.json +++ b/public/consolidated/c.json @@ -7,10 +7,8 @@ "description": "Prints Hello, World! to the terminal.", "author": "0xHouss", "tags": [ - "c", "printing", - "hello-world", - "utility" + "hello-world" ], "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" @@ -25,26 +23,11 @@ "description": "Calculates the factorial of a number.", "author": "0xHouss", "tags": [ - "c", "math", - "factorial", - "utility" + "factorial" ], "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" - }, - { - "title": "Power Function", - "description": "Calculates the power of a number.", - "author": "0xHouss", - "tags": [ - "c", - "math", - "power", - "utility" - ], - "contributors": [], - "code": "int power(int x, int n) {\n int y = 1;\n\n for (int i = 0; i < n; i++)\n y *= x;\n\n return y;\n}\n" + "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 71066e57..e560e82d 100644 --- a/public/consolidated/cpp.json +++ b/public/consolidated/cpp.json @@ -7,10 +7,8 @@ "description": "Prints Hello, World! to the terminal.", "author": "James-Beans", "tags": [ - "cpp", "printing", - "hello-world", - "utility" + "hello-world" ], "contributors": [], "code": "#include // Includes the input/output stream library\n\nint main() { // Defines the main function\n std::cout << \"Hello, World!\" << std::endl; // Outputs Hello, World! and a newline\n return 0; // indicate the program executed successfully\n}\n" @@ -25,13 +23,12 @@ "description": "Convert vector into queue quickly", "author": "mrityunjay2003", "tags": [ - "cpp", "data structures", "queue", "vector" ], "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" + "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" } ] }, @@ -43,12 +40,11 @@ "description": "Check if an integer is a prime number", "author": "MihneaMoso", "tags": [ - "cpp", "number", "prime" ], "contributors": [], - "code": "bool is_prime(int n) {\n if (n < 2) return false;\n if (n == 2 || n == 3) return true;\n if (n % 2 == 0) return false;\n for (int i = 3; i * i <= n; i += 2) {\n if (n % i == 0) return false;\n }\n return true;\n}\n\n// Usage\n#include \n\nint main() {\n std::cout << is_prime(29) << std::endl; // Output: 1\n return 0;\n}\n" + "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" } ] }, @@ -60,26 +56,22 @@ "description": "Reverses the characters in a string.", "author": "Vaibhav-kesarwani", "tags": [ - "cpp", "array", - "reverse", - "utility" + "reverse" ], "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" + "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", "tags": [ - "cpp", "string", - "split", - "utility" + "split" ], "contributors": [], - "code": "#include \n#include \n\nstd::vector split_string(std::string str, std::string delim) {\n std::vector splits;\n int i = 0, j;\n int inc = delim.length();\n while (j != std::string::npos) {\n j = str.find(delim, i);\n splits.push_back(str.substr(i, j - i));\n i = j + inc;\n }\n return splits;\n}\n" + "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 96b83c2f..63ff0ec1 100644 --- a/public/consolidated/csharp.json +++ b/public/consolidated/csharp.json @@ -7,10 +7,8 @@ "description": "Prints Hello, World! to the terminal.", "author": "chaitanya-jvnm", "tags": [ - "c#", "printing", - "hello-world", - "utility" + "hello-world" ], "contributors": [], "code": "public class Program {\n public static void Main(string[] args) {\n System.Console.WriteLine(\"Hello, World!\");\n }\n}\n" @@ -25,26 +23,22 @@ "description": "Generates a new GUID", "author": "chaitanya-jvnm", "tags": [ - "c#", "guid", - "generate", - "utility" + "generate" ], "contributors": [], - "code": "public static string GenerateGuid() {\n return Guid.NewGuid().ToString();\n}\n" + "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", "tags": [ - "c#", "guid", - "validate", - "utility" + "validate" ], "contributors": [], - "code": "public static bool IsGuid(string str) {\n return Guid.TryParse(str, out _);\n}\n" + "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" } ] }, @@ -56,39 +50,22 @@ "description": "Decodes a JWT.", "author": "chaitanya-jvnm", "tags": [ - "c#", "jwt", - "decode", - "utility" + "decode" ], "contributors": [], - "code": "/// \n/// Decodes the JWT\n/// \npublic static string DecodeJwt(string token) {\n return new JwtSecurityTokenHandler().ReadJwtToken(token).ToString();\n}\n\n//Example\nstring token = \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\";\n\nstring decodedJwt = DecodeJwt(token);\n\nConsole.WriteLine(decodedJwt); //Prints {\"alg\":\"HS256\",\"typ\":\"JWT\"}.{\"sub\":\"1234567890\",\"name\":\"John Doe\",\"iat\":1516239022}\n" - }, - { - "title": "Generate JWT", - "description": "Generates a new JWT.", - "author": "chaitanya-jvnm", - "tags": [ - "c#", - "jwt", - "generate", - "utility" - ], - "contributors": [], - "code": "public static string GenerateJwt(string secret, string issuer, string audience, int expirationMinutes) {\n var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));\n var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);\n var token = new JwtSecurityToken(issuer, audience, null, expires: DateTime.UtcNow.AddMinutes(expirationMinutes), signingCredentials: credentials);\n return new JwtSecurityTokenHandler().WriteToken(token);\n}\n" + "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", "tags": [ - "c#", "jwt", - "validate", - "utility" + "validate" ], "contributors": [], - "code": "public static bool ValidateJwt(string token, string secret) {\n var tokenHandler = new JwtSecurityTokenHandler();\n var validationParameters = new TokenValidationParameters {\n ValidateIssuerSigningKey = true,\n IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret)),\n ValidateIssuer = false,\n ValidateAudience = false\n };\n try {\n tokenHandler.ValidateToken(token, validationParameters, out _);\n return true;\n }\n catch {\n return false\n }\n}\n\n//Example\nstring JWT = \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\";\n\nstring correctSecret = \"your-256-bit-secret\";\nstring wrongSecret = \"this-is-not-the-right-secret\";\n\nConsole.WriteLine(ValidateJwt(JWT, correctSecret)) // returns True\nConsole.WriteLine(ValidateJwt(JWT, wrongSecret)) // returns False\n\n" + "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" } ] }, @@ -96,17 +73,15 @@ "categoryName": "List Utilities", "snippets": [ { - "title": "Swap two items at determined indexes", + "title": "Swap items at index", "description": "Swaps two items at determined indexes", "author": "omegaleo", "tags": [ - "csharp", - "c#", "list", - "utility" + "swapping" ], "contributors": [], - "code": "/// \n/// Swaps the position of 2 elements inside of a List\n/// \n/// List with swapped elements\npublic 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\nConsole.WriteLine(list[0]); // Outputs: Test\nConsole.WriteLine(list[1]); // Outputs: Test2\n\nlist = list.Swap(0, 1).ToList();\n\nConsole.WriteLine(list[0]); // Outputs: Test2\nConsole.WriteLine(list[1]); // Outputs: Test\n" + "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" } ] }, @@ -118,26 +93,22 @@ "description": "Makes the first letter of a string uppercase.", "author": "chaitanya-jvnm", "tags": [ - "c#", "string", - "capitalize", - "utility" + "capitalize" ], "contributors": [], - "code": "/// \n/// Capitalize the first character of the string\n/// \npublic static string Capitalize(this string str) {\n return str.Substring(0, 1).ToUpper() + str.Substring(1);\n}\n\n//Example\nstring example = \"hello\";\nstring captializedExample = example.Capitalize();\nConsole.WriteLine(captializedExample); // prints \"Hello\"\n" + "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 a String", + "title": "Truncate String", "description": "Cut off a string once it reaches a determined amount of characters and add '...' to the end of the string", "author": "omegaleo", "tags": [ - "csharp", - "c#", - "list", - "utility" + "string", + "truncate" ], "contributors": [], - "code": "/// \n/// Cut off a string once it reaches a amount of characters and add '...' to the end of the string\n/// \npublic static string Truncate(this string value, int maxChars)\n{\n return value.Length <= maxChars ? value : value.Substring(0, maxChars) + \"...\";\n}\n\nvar str = \"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam tristique rhoncus bibendum. Vivamus laoreet tortor vel neque lacinia, nec rhoncus ligula pellentesque. Nullam eu ornare nibh. Donec tincidunt viverra nulla.\";\n\nConsole.WriteLine(str); // Outputs the full string\nConsole.WriteLine(str.Truncate(5)); // Outputs Lorem...\n" + "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 23361ad7..b759c611 100644 --- a/public/consolidated/css.json +++ b/public/consolidated/css.json @@ -7,7 +7,6 @@ "description": "Adds a 3D effect to a button when clicked.", "author": "dostonnabotov", "tags": [ - "css", "button", "3D", "effect" @@ -20,7 +19,6 @@ "description": "Creates a hover effect with a color transition.", "author": "dostonnabotov", "tags": [ - "css", "button", "hover", "transition" @@ -33,7 +31,6 @@ "description": "A macOS-like button style, with hover and shading effects.", "author": "e3nviction", "tags": [ - "css", "button", "macos", "hover", @@ -52,7 +49,6 @@ "description": "Applies a blur effect to the background of an element.", "author": "dostonnabotov", "tags": [ - "css", "blur", "background", "effects" @@ -65,7 +61,6 @@ "description": "Adds a glowing effect on hover.", "author": "dostonnabotov", "tags": [ - "css", "hover", "glow", "effects" @@ -78,7 +73,6 @@ "description": "A card with an image that transitions from grayscale to full color on hover.", "author": "Haider-Mukhtar", "tags": [ - "css", "hover", "image", "effects" @@ -96,7 +90,6 @@ "description": "Resets some default browser styles, ensuring consistency across browsers.", "author": "AmeerMoustafa", "tags": [ - "css", "reset", "browser", "layout" @@ -109,7 +102,6 @@ "description": "Creates columns with equal widths using flexbox.", "author": "dostonnabotov", "tags": [ - "css", "flexbox", "columns", "layout" @@ -122,7 +114,6 @@ "description": "Equal sized items in a responsive grid", "author": "xshubhamg", "tags": [ - "css", "layout", "grid" ], @@ -134,8 +125,8 @@ "description": "The different responsive breakpoints.", "author": "kruimol", "tags": [ - "css", - "responsive" + "responsive", + "media queries" ], "contributors": [], "code": "/* Phone */\n.element {\n margin: 0 10%\n}\n\n/* Tablet */\n@media (min-width: 640px) {\n .element {\n margin: 0 20%\n }\n}\n\n/* Desktop base */\n@media (min-width: 768px) {\n .element {\n margin: 0 30%\n }\n}\n\n/* Desktop large */\n@media (min-width: 1024px) {\n .element {\n margin: 0 40%\n }\n}\n\n/* Desktop extra large */\n@media (min-width: 1280px) {\n .element {\n margin: 0 60%\n }\n}\n\n/* Desktop bige */\n@media (min-width: 1536px) {\n .element {\n margin: 0 80%\n }\n}\n" @@ -145,7 +136,6 @@ "description": "Ensures the footer always stays at the bottom of the page.", "author": "dostonnabotov", "tags": [ - "css", "layout", "footer", "sticky" @@ -163,7 +153,6 @@ "description": "Adds space between letters for better readability.", "author": "dostonnabotov", "tags": [ - "css", "typography", "spacing" ], @@ -175,7 +164,6 @@ "description": "Adjusts font size based on viewport width.", "author": "dostonnabotov", "tags": [ - "css", "font", "responsive", "typography" diff --git a/public/consolidated/haskell.json b/public/consolidated/haskell.json index bc693249..b4a97f3c 100644 --- a/public/consolidated/haskell.json +++ b/public/consolidated/haskell.json @@ -7,65 +7,36 @@ "description": "Searches for an element in a sorted array using binary search.", "author": "ACR1209", "tags": [ - "haskell", "array", "binary-search", "search" ], "contributors": [], - "code": "binarySearch :: Ord a => a -> [a] -> Maybe Int\nbinarySearch _ [] = Nothing\nbinarySearch target xs = go 0 (length xs - 1)\n where\n go low high\n | low > high = Nothing\n | midElem < target = go (mid + 1) high\n | midElem > target = go low (mid - 1)\n | otherwise = Just mid\n where\n mid = (low + high) `div` 2\n midElem = xs !! mid\n\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" + "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", "tags": [ - "haskell", "array", "chunk", "utility" ], "contributors": [], - "code": "chunkArray :: Int -> [a] -> [[a]]\nchunkArray _ [] = []\nchunkArray n xs = take n xs : chunkArray n (drop n xs)\n\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": "Flatten Array", - "description": "Flattens a multi-dimensional array.", - "author": "ACR1209", - "tags": [ - "haskell", - "array", - "flatten", - "utility" - ], - "contributors": [], - "code": "flatten :: [[a]] -> [a]\nflatten = concat\n\nmain :: IO ()\nmain = do\n let array = [[1, 2], [2], [3], [4]]\n print $ flatten array -- Output: [1, 2, 2, 3, 4]\n" + "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", "tags": [ - "haskell", "array", "matrix", "transpose" ], "contributors": [], - "code": "transposeMatrix :: [[a]] -> [[a]]\ntransposeMatrix [] = []\ntransposeMatrix ([]:_) = []\ntransposeMatrix xs = map head xs : transposeMatrix (map tail xs)\n\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" - }, - { - "title": "Remove duplicates", - "description": "Removes duplicate values from an array.", - "author": "ACR1209", - "tags": [ - "haskell", - "array", - "deduplicate", - "utility" - ], - "contributors": [], - "code": "import Data.List (nub)\n\nremoveDuplicates :: Eq a => [a] -> [a]\nremoveDuplicates = nub\n\n-- Usage\nmain :: IO ()\nmain = do\n let array = [1, 2, 2, 3, 4, 4, 5]\n print $ removeDuplicates array -- Output: [1, 2, 3, 4, 5]\n" + "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" } ] }, @@ -77,7 +48,6 @@ "description": "Prints Hello, World! to the terminal.", "author": "ACR1209", "tags": [ - "haskell", "printing", "hello-world", "utility" @@ -90,70 +60,31 @@ { "categoryName": "File Handling", "snippets": [ - { - "title": "Append to File", - "description": "Appends text to an existing file.", - "author": "ACR1209", - "tags": [ - "haskell", - "file", - "append", - "utilty" - ], - "contributors": [], - "code": "import System.IO\n\nappendToFile :: FilePath -> String -> IO ()\nappendToFile = appendFile \n\nmain :: IO ()\nmain = do\n let file = \"example.txt\"\n let text = \"This will be appended to the file.\\n\"\n appendToFile file text\n" - }, - { - "title": "Check if File Exists", - "description": "Checks if a file exists at a given path.", - "author": "ACR1209", - "tags": [ - "haskell", - "file", - "exists" - ], - "contributors": [], - "code": "import System.Directory (doesFileExist)\n\ncheckFileExists :: FilePath -> IO Bool\ncheckFileExists = doesFileExist\n\nmain :: IO ()\nmain = do\n let file = \"example.txt\"\n exists <- checkFileExists file\n if exists then putStrLn \"File exists.\" else putStrLn \"File does not exist.\"\n" - }, { "title": "Find Files in Directory by Type", "description": "Finds all files in a directory with a specific extension.", "author": "ACR1209", "tags": [ - "haskell", "file", "search", "extension", "filesystem" ], "contributors": [], - "code": "import System.Directory (listDirectory)\nimport System.FilePath (takeExtension)\n\nfindFilesByExtension :: FilePath -> String -> IO [FilePath]\nfindFilesByExtension dir ext = do\n files <- listDirectory dir\n return $ filter (\\f -> takeExtension f == ext) files\n\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" + "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", "tags": [ - "haskell", "file", "read", "chunks", "utility" ], "contributors": [], - "code": "import System.IO (openFile, IOMode(ReadMode), hGetContents)\nimport Data.List (unfoldr)\n\nreadFileInChunks :: FilePath -> Int -> IO [[String]]\nreadFileInChunks filePath chunkSize = do\n handle <- openFile filePath ReadMode\n contents <- hGetContents handle\n let linesList = lines contents\n return $ go linesList\n where\n go [] = []\n go xs = take chunkSize xs : go (drop chunkSize xs)\n\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" - }, - { - "title": "Write to File", - "description": "Writes text to a file, overwriting any existing content.", - "author": "ACR1209", - "tags": [ - "haskell", - "file", - "write" - ], - "contributors": [], - "code": "import System.IO (writeFile)\n\nwriteToFile :: FilePath -> String -> IO ()\nwriteToFile = writeFile\n\nmain :: IO ()\nmain = do\n let file = \"example.txt\"\n let content = \"This is new content.\"\n writeToFile file content\n" + "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" } ] }, @@ -165,51 +96,47 @@ "description": "Using the Either monad to handle errors in a computation.", "author": "ACR1209", "tags": [ - "haskell", "monads", "either", "error handling" ], "contributors": [], - "code": "safeDiv :: Int -> Int -> Either String Int\nsafeDiv _ 0 = Left \"Division by zero error\"\nsafeDiv x y = Right (x `div` y)\n\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" + "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", "tags": [ - "haskell", "monads", "maybe" ], "contributors": [], - "code": "safeDiv :: Int -> Int -> Maybe Int\nsafeDiv _ 0 = Nothing\nsafeDiv x y = Just (x `div` y)\n\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" + "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", "tags": [ - "haskell", "monads", "state", "state-management" ], "contributors": [], - "code": "import Control.Monad.State\n\nincrement :: State Int Int\nincrement = do\n count <- get\n put (count + 1)\n return count\n\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" + "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", "tags": [ - "haskell", "monads", "writer", "logs" ], "contributors": [], - "code": "import Control.Monad.Writer\n\naddAndLog :: Int -> Int -> Writer [String] Int\naddAndLog x y = do\n tell [\"Adding \" ++ show x ++ \" and \" ++ show y]\n return (x + y)\n\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" + "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" } ] }, @@ -217,11 +144,10 @@ "categoryName": "String Manipulation", "snippets": [ { - "title": "Transform Camel Case to Snake Case", + "title": "CamelCase to snake_case", "description": "Converts a Camel Case string to Snake case.", "author": "ACR1209", "tags": [ - "haskell", "string", "convert", "camel-case", @@ -229,53 +155,49 @@ "utility" ], "contributors": [], - "code": "import Data.Char (isUpper, toLower)\n\ncamelToSnake :: String -> String\ncamelToSnake [] = []\ncamelToSnake (x:xs)\n | isUpper x = '_' : toLower x : camelToSnake xs\n | otherwise = x : camelToSnake xs\n\nmain :: IO ()\nmain = do\n let camelCase = \"camelCaseToSnakeCase\"\n print $ camelToSnake camelCase -- Output: \"camel_case_to_snake_case\"\n" + "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", "tags": [ - "haskell", "string", "capitalize", "words" ], "contributors": [], - "code": "import Data.Char (toUpper)\n\ncapitalizeWords :: String -> String\ncapitalizeWords = unwords . map capitalize . words\n where\n capitalize [] = []\n capitalize (x:xs) = toUpper x : xs\n\nmain :: IO ()\nmain = do\n let sentence = \"haskell is awesome\"\n print $ capitalizeWords sentence -- Output: \"Haskell Is Awesome\"\n" + "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", "tags": [ - "haskell", "string", "occurrences", "word-count" ], "contributors": [], - "code": "import Data.List (group, sort)\n\ncountWordOccurrences :: String -> [(String, Int)]\ncountWordOccurrences = map (\\(w:ws) -> (w, length (w:ws))) . group . sort . words\n\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" + "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", "tags": [ - "haskell", "string", "punctuation", "remove" ], "contributors": [], - "code": "import Data.Char (isPunctuation)\n\nremovePunctuation :: String -> String\nremovePunctuation = filter (not . isPunctuation)\n\nmain :: IO ()\nmain = do\n let text = \"Hello, Haskell! How's it going?\"\n print $ removePunctuation text -- Output: \"Hello Haskell Hows it going\"\n" + "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": "Transform from Snake Case to Camel Case", + "title": "Snake_Case to CamelCase", "description": "Converts a Snake Case string to Camel Case.", "author": "ACR1209", "tags": [ - "haskell", "string", "convert", "snake-case", @@ -283,20 +205,19 @@ "utilty" ], "contributors": [], - "code": "import Data.Char (toUpper)\n\nsnakeToCamel :: String -> String\nsnakeToCamel [] = []\nsnakeToCamel ('_':x:xs) = toUpper x : snakeToCamel xs\nsnakeToCamel (x:xs) = x : snakeToCamel xs\n\nmain :: IO ()\nmain = do\n let snakeCase = \"snake_case_to_camel_case\"\n print $ snakeToCamel snakeCase -- Output: \"snakeCaseToCamelCase\"\n" + "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 Strings", + "title": "Truncate String", "description": "Truncates a string to a specified length, optionally adding an ellipsis.", "author": "ACR1209", "tags": [ - "haskell", "string", "truncate", "utility" ], "contributors": [], - "code": "truncateString :: Int -> String -> String\ntruncateString maxLength str\n | length str <= maxLength = str\n | otherwise = take (maxLength - 3) str ++ \"...\"\n\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" + "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 9ea5b9b1..f7635148 100644 --- a/public/consolidated/html.json +++ b/public/consolidated/html.json @@ -7,7 +7,6 @@ "description": "Full-height grid layout with header navigation using nesting syntax.", "author": "GreenMan36", "tags": [ - "html", "css", "layout", "sticky", @@ -22,7 +21,6 @@ "description": "Full-height layout with sticky header and footer, using modern viewport units and flexbox.", "author": "GreenMan36", "tags": [ - "html", "css", "layout", "sticky", diff --git a/public/consolidated/javascript.json b/public/consolidated/javascript.json index 7b1ceee5..4ac0819f 100644 --- a/public/consolidated/javascript.json +++ b/public/consolidated/javascript.json @@ -2,80 +2,58 @@ { "categoryName": "Array Manipulation", "snippets": [ - { - "title": "Flatten Array", - "description": "Flattens a multi-dimensional array.", - "author": "dostonnabotov", - "tags": [ - "javascript", - "array", - "flatten", - "utility" - ], - "contributors": [], - "code": "const flattenArray = (arr) => arr.flat(Infinity);\n\n// Usage:\nconst nestedArray = [1, [2, [3, [4]]]];\nconsole.log(flattenArray(nestedArray)); // Output: [1, 2, 3, 4]\n" - }, { "title": "Partition Array", "description": "Splits an array into two arrays based on a callback function.", "author": "Swaraj-Singh-30", "tags": [ - "javascript", "array", "partition", - "reduce", - "utility" + "reduce" ], "contributors": [], - "code": "const partition = (arr, callback) =>\n arr.reduce(\n ([pass, fail], elem) => (callback(elem) ? [[...pass, elem], fail] : [pass, [...fail, elem]]),\n [[], []]\n );\n\n// Usage:\nconst numbers = [1, 2, 3, 4, 5, 6];\nconst isEven = (n) => n % 2 === 0;\nconsole.log(partition(numbers, isEven)); // Output: [[2, 4, 6], [1, 3, 5]]\n" + "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", "tags": [ - "javascript", "array", - "deduplicate", - "utility" + "deduplicate" ], "contributors": [], - "code": "const removeDuplicates = (arr) => [...new Set(arr)];\n\n// Usage:\nconst numbers = [1, 2, 2, 3, 4, 4, 5];\nconsole.log(removeDuplicates(numbers)); // Output: [1, 2, 3, 4, 5]\n" + "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 like null, undefined, and false from an array.", + "description": "Removes falsy values from an array.", "author": "mubasshir", "tags": [ - "javascript", "array", "falsy", "filter" ], "contributors": [], - "code": "const removeFalsy = (arr) => arr.filter(Boolean);\n\n// Usage:\nconst array = [0, 1, false, 2, \"\", 3, null];\nconsole.log(removeFalsy(array)); // Output: [1, 2, 3]\n" + "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", "tags": [ - "javascript", "array", - "shuffle", - "utility" + "shuffle" ], "contributors": [], - "code": "function shuffleArray(array) {\n for (let i = array.length - 1; i >= 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n [array[i], array[j]] = [array[j], array[i]];\n }\n}\n" + "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", "tags": [ - "javascript", "array", - "utility", "map" ], "contributors": [], @@ -91,10 +69,8 @@ "description": "Prints Hello, World! to the terminal.", "author": "James-Beans", "tags": [ - "javascript", "printing", - "hello-world", - "utility" + "hello-world" ], "contributors": [], "code": "console.log(\"Hello, World!\"); // Prints Hello, World! to the console\n" @@ -104,139 +80,97 @@ { "categoryName": "Date And Time", "snippets": [ - { - "title": "Add Days to a Date", - "description": "Adds a specified number of days to a given date.", - "author": "axorax", - "tags": [ - "javascript", - "date", - "add-days", - "utility" - ], - "contributors": [], - "code": "const addDays = (date, days) => {\n const result = new Date(date);\n result.setDate(result.getDate() + days);\n return result;\n};\n\n// Usage:\nconst today = new Date();\nconsole.log(addDays(today, 10)); // Output: Date object 10 days ahead\n" - }, { "title": "Check Leap Year", "description": "Determines if a given year is a leap year.", "author": "axorax", "tags": [ - "javascript", "date", - "leap-year", - "utility" + "leap-year" ], "contributors": [], - "code": "const isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n\n// Usage:\nconsole.log(isLeapYear(2024)); // Output: true\nconsole.log(isLeapYear(2023)); // Output: false\n" + "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", "tags": [ - "javascript", "date", "unix", - "timestamp", - "utility" + "timestamp" ], "contributors": [], - "code": "/**\n * Converts a date string or Date object to Unix timestamp in seconds.\n *\n * @param {string|Date} input - A valid date string or Date object.\n * @returns {number} - The Unix timestamp in seconds.\n * @throws {Error} - Throws an error if the input is invalid.\n */\nfunction 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\nconsole.log(convertToUnixSeconds('2025-01-01T12:00:00Z')); // 1735732800\nconsole.log(convertToUnixSeconds(new Date('2025-01-01T12:00:00Z'))); // 1735732800\nconsole.log(convertToUnixSeconds(new Date())); //Current Unix timestamp in seconds (varies depending on execution time)\n" + "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", "tags": [ - "javascript", - "date", - "format", - "utility" - ], - "contributors": [], - "code": "const formatDate = (date) => date.toISOString().split('T')[0];\n\n// Usage:\nconsole.log(formatDate(new Date())); // Output: '2024-12-10'\n" - }, - { - "title": "Get Current Timestamp", - "description": "Retrieves the current timestamp in milliseconds since January 1, 1970.", - "author": "axorax", - "tags": [ - "javascript", "date", - "timestamp", - "utility" + "format" ], "contributors": [], - "code": "const getCurrentTimestamp = () => Date.now();\n\n// Usage:\nconsole.log(getCurrentTimestamp()); // Output: 1691825935839 (example)\n" + "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", "tags": [ - "javascript", "date", - "day-of-year", - "utility" + "day-of-year" ], "contributors": [], - "code": "const getDayOfYear = (date) => {\n const startOfYear = new Date(date.getFullYear(), 0, 0);\n const diff = date - startOfYear + (startOfYear.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000;\n return Math.floor(diff / (1000 * 60 * 60 * 24));\n};\n\n// Usage:\nconst today = new Date('2024-12-31');\nconsole.log(getDayOfYear(today)); // Output: 366 (in a leap year)\n" + "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", "tags": [ - "javascript", "date", - "days-in-month", - "utility" + "days-in-month" ], "contributors": [], - "code": "const getDaysInMonth = (year, month) => new Date(year, month + 1, 0).getDate();\n\n// Usage:\nconsole.log(getDaysInMonth(2024, 1)); // Output: 29 (February in a leap year)\nconsole.log(getDaysInMonth(2023, 1)); // Output: 28\n" + "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", "tags": [ - "javascript", "date", - "time-difference", - "utility" + "time-difference" ], "contributors": [], - "code": "const getTimeDifference = (date1, date2) => {\n const diff = Math.abs(date2 - date1);\n return Math.ceil(diff / (1000 * 60 * 60 * 24));\n};\n\n// Usage:\nconst date1 = new Date('2024-01-01');\nconst date2 = new Date('2024-12-31');\nconsole.log(getTimeDifference(date1, date2)); // Output: 365\n" + "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", "tags": [ - "javascript", "date", "time", "relative", "future", - "past", - "utility" + "past" ], "contributors": [], - "code": "const getRelativeTime = (date) => {\n const now = Date.now();\n const diff = date.getTime() - now;\n const seconds = Math.abs(Math.floor(diff / 1000));\n const minutes = Math.abs(Math.floor(seconds / 60));\n const hours = Math.abs(Math.floor(minutes / 60));\n const days = Math.abs(Math.floor(hours / 24));\n const years = Math.abs(Math.floor(days / 365));\n\n if (Math.abs(diff) < 1000) return 'just now';\n\n const isFuture = diff > 0;\n\n if (years > 0) return `${isFuture ? 'in ' : ''}${years} ${years === 1 ? 'year' : 'years'}${isFuture ? '' : ' ago'}`;\n if (days > 0) return `${isFuture ? 'in ' : ''}${days} ${days === 1 ? 'day' : 'days'}${isFuture ? '' : ' ago'}`;\n if (hours > 0) return `${isFuture ? 'in ' : ''}${hours} ${hours === 1 ? 'hour' : 'hours'}${isFuture ? '' : ' ago'}`;\n if (minutes > 0) return `${isFuture ? 'in ' : ''}${minutes} ${minutes === 1 ? 'minute' : 'minutes'}${isFuture ? '' : ' ago'}`;\n\n return `${isFuture ? 'in ' : ''}${seconds} ${seconds === 1 ? 'second' : 'seconds'}${isFuture ? '' : ' ago'}`;\n}\n\n// usage\nconst pastDate = new Date('2021-12-29 13:00:00');\nconst futureDate = new Date('2026-12-29 13:00:00');\nconsole.log(getRelativeTime(pastDate)); // x years ago\nconsole.log(getRelativeTime(new Date())); // just now\nconsole.log(getRelativeTime(futureDate)); // in x years\n" + "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", "tags": [ - "javascript", "date", - "start-of-day", - "utility" + "start-of-day" ], "contributors": [], - "code": "const startOfDay = (date) => new Date(date.setHours(0, 0, 0, 0));\n\n// Usage:\nconst today = new Date();\nconsole.log(startOfDay(today)); // Output: Date object for midnight\n" + "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" } ] }, @@ -248,65 +182,22 @@ "description": "Changes the inline style of an element.", "author": "axorax", "tags": [ - "javascript", "dom", - "style", - "utility" + "style" ], "contributors": [], "code": "const changeElementStyle = (element, styleObj) => {\n Object.entries(styleObj).forEach(([property, value]) => {\n element.style[property] = value;\n });\n};\n\n// Usage:\nconst element = document.querySelector('.my-element');\nchangeElementStyle(element, { color: 'red', backgroundColor: 'yellow' });\n" }, - { - "title": "Get Element Position", - "description": "Gets the position of an element relative to the viewport.", - "author": "axorax", - "tags": [ - "javascript", - "dom", - "position", - "utility" - ], - "contributors": [], - "code": "const getElementPosition = (element) => {\n const rect = element.getBoundingClientRect();\n return { x: rect.left, y: rect.top };\n};\n\n// Usage:\nconst element = document.querySelector('.my-element');\nconst position = getElementPosition(element);\nconsole.log(position); // { x: 100, y: 150 }\n" - }, { "title": "Remove Element", "description": "Removes a specified element from the DOM.", "author": "axorax", "tags": [ - "javascript", "dom", - "remove", - "utility" + "remove" ], "contributors": [], "code": "const removeElement = (element) => {\n if (element && element.parentNode) {\n element.parentNode.removeChild(element);\n }\n};\n\n// Usage:\nconst element = document.querySelector('.my-element');\nremoveElement(element);\n" - }, - { - "title": "Smooth Scroll to Element", - "description": "Scrolls smoothly to a specified element.", - "author": "dostonnabotov", - "tags": [ - "javascript", - "dom", - "scroll", - "ui" - ], - "contributors": [], - "code": "const smoothScroll = (element) => {\n element.scrollIntoView({ behavior: 'smooth' });\n};\n\n// Usage:\nconst target = document.querySelector('#target');\nsmoothScroll(target);\n" - }, - { - "title": "Toggle Class", - "description": "Toggles a class on an element.", - "author": "dostonnabotov", - "tags": [ - "javascript", - "dom", - "class", - "utility" - ], - "contributors": [], - "code": "const toggleClass = (element, className) => {\n element.classList.toggle(className);\n};\n\n// Usage:\nconst element = document.querySelector('.my-element');\ntoggleClass(element, 'active');\n" } ] }, @@ -318,77 +209,65 @@ "description": "Composes multiple functions into a single function, where the output of one function becomes the input of the next.", "author": "axorax", "tags": [ - "javascript", "function", - "compose", - "utility" + "compose" ], "contributors": [], - "code": "const compose = (...funcs) => (initialValue) => {\n return funcs.reduce((acc, func) => func(acc), initialValue);\n};\n\n// Usage:\nconst add2 = (x) => x + 2;\nconst multiply3 = (x) => x * 3;\nconst composed = compose(multiply3, add2);\nconsole.log(composed(5)); // Output: 21 ((5 + 2) * 3)\n" + "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", "tags": [ - "javascript", "curry", - "function", - "utility" + "function" ], "contributors": [], - "code": "const curry = (func) => {\n const curried = (...args) => {\n if (args.length >= func.length) {\n return func(...args);\n }\n return (...nextArgs) => curried(...args, ...nextArgs);\n };\n return curried;\n};\n\n// Usage:\nconst add = (a, b, c) => a + b + c;\nconst curriedAdd = curry(add);\nconsole.log(curriedAdd(1)(2)(3)); // Output: 6\nconsole.log(curriedAdd(1, 2)(3)); // Output: 6\n" + "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", "tags": [ - "javascript", - "utility", "debounce", "performance" ], "contributors": [], - "code": "const debounce = (func, delay) => {\n let timeout;\n\n return (...args) => {\n clearTimeout(timeout);\n timeout = setTimeout(() => func(...args), delay);\n };\n};\n\n// Usage:\nwindow.addEventListener('resize', debounce(() => console.log('Resized!'), 500));\n" + "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", "tags": [ - "javascript", "color", "hex", "contrast", - "brightness", - "utility" + "brightness" ], "contributors": [], - "code": "const getContrastColor = (hexColor) => {\n // Expand short hex color to full format\n if (hexColor.length === 4) {\n hexColor = `#${hexColor[1]}${hexColor[1]}${hexColor[2]}${hexColor[2]}${hexColor[3]}${hexColor[3]}`;\n }\n const r = parseInt(hexColor.slice(1, 3), 16);\n const g = parseInt(hexColor.slice(3, 5), 16);\n const b = parseInt(hexColor.slice(5, 7), 16);\n const brightness = (r * 299 + g * 587 + b * 114) / 1000;\n return brightness >= 128 ? \"#000000\" : \"#FFFFFF\";\n};\n\n// Usage:\nconsole.log(getContrastColor('#fff')); // Output: #000000 (black)\nconsole.log(getContrastColor('#123456')); // Output: #FFFFFF (white)\nconsole.log(getContrastColor('#ff6347')); // Output: #000000 (black)\nconsole.log(getContrastColor('#f4f')); // Output: #000000 (black)\n" + "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", "tags": [ - "javascript", "memoization", - "optimization", - "utility" + "optimization" ], "contributors": [], - "code": "const memoize = (func) => {\n const cache = new Map();\n return (...args) => {\n const key = JSON.stringify(args);\n if (cache.has(key)) {\n return cache.get(key);\n }\n const result = func(...args);\n cache.set(key, result);\n return result;\n };\n};\n\n// Usage:\nconst factorial = memoize((n) => (n <= 1 ? 1 : n * factorial(n - 1)));\nconsole.log(factorial(5)); // Output: 120\nconsole.log(factorial(5)); // Output: 120 (retrieved from cache)\n" + "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", "tags": [ - "javascript", "function", - "once", - "utility" + "once" ], "contributors": [], "code": "const once = (func) => {\n let called = false;\n return (...args) => {\n if (!called) {\n called = true;\n return func(...args);\n }\n };\n};\n\n// Usage:\nconst initialize = once(() => console.log('Initialized!'));\ninitialize(); // Output: Initialized!\ninitialize(); // No output\n" @@ -398,23 +277,19 @@ "description": "Limits how often a function can be executed within a given time window.", "author": "axorax", "tags": [ - "javascript", "function", - "rate-limiting", - "utility" + "rate-limiting" ], "contributors": [], - "code": "const rateLimit = (func, limit, timeWindow) => {\n let queue = [];\n setInterval(() => {\n if (queue.length) {\n const next = queue.shift();\n func(...next.args);\n }\n }, timeWindow);\n return (...args) => {\n if (queue.length < limit) {\n queue.push({ args });\n }\n };\n};\n\n// Usage:\nconst fetchData = () => console.log('Fetching data...');\nconst rateLimitedFetch = rateLimit(fetchData, 2, 1000);\nsetInterval(() => rateLimitedFetch(), 200); // Only calls fetchData twice every second\n" + "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", "tags": [ - "javascript", "function", - "repeat", - "utility" + "repeat" ], "contributors": [], "code": "const times = (func, n) => {\n Array.from(Array(n)).forEach(() => {\n func();\n });\n};\n\n// Usage:\nconst randomFunction = () => console.log('Function called!');\ntimes(randomFunction, 3); // Logs 'Function called!' three times\n" @@ -431,20 +306,7 @@ "promises" ], "contributors": [], - "code": "const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\n// Usage:\nasync function main() {\n console.log('Hello');\n await sleep(2000); // Waits for 2 seconds\n console.log('World!');\n}\n\nmain();\n" - }, - { - "title": "Throttle Function", - "description": "Limits a function execution to once every specified time interval.", - "author": "dostonnabotov", - "tags": [ - "javascript", - "utility", - "throttle", - "performance" - ], - "contributors": [], - "code": "const throttle = (func, limit) => {\n let lastFunc;\n let lastRan;\n return (...args) => {\n const context = this;\n if (!lastRan) {\n func.apply(context, args);\n lastRan = Date.now();\n } else {\n clearTimeout(lastFunc);\n lastFunc = setTimeout(() => {\n if (Date.now() - lastRan >= limit) {\n func.apply(context, args);\n lastRan = Date.now();\n }\n }, limit - (Date.now() - lastRan));\n }\n };\n};\n\n// Usage:\ndocument.addEventListener('scroll', throttle(() => console.log('Scrolled!'), 1000));\n" + "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" } ] }, @@ -456,10 +318,8 @@ "description": "Stores a value in localStorage under the given key.", "author": "dostonnabotov", "tags": [ - "javascript", "localStorage", - "storage", - "utility" + "storage" ], "contributors": [], "code": "const addToLocalStorage = (key, value) => {\n localStorage.setItem(key, JSON.stringify(value));\n};\n\n// Usage:\naddToLocalStorage('user', { name: 'John', age: 30 });\n" @@ -469,39 +329,22 @@ "description": "Checks if a specific item exists in localStorage.", "author": "axorax", "tags": [ - "javascript", "localStorage", - "storage", - "utility" + "storage" ], "contributors": [], "code": "const isItemInLocalStorage = (key) => {\n return localStorage.getItem(key) !== null;\n};\n\n// Usage:\nconsole.log(isItemInLocalStorage('user')); // Output: true or false\n" }, - { - "title": "Clear All localStorage", - "description": "Clears all data from localStorage.", - "author": "dostonnabotov", - "tags": [ - "javascript", - "localStorage", - "storage", - "utility" - ], - "contributors": [], - "code": "const clearLocalStorage = () => {\n localStorage.clear();\n};\n\n// Usage:\nclearLocalStorage(); // Removes all items from localStorage\n" - }, { "title": "Retrieve Item from localStorage", "description": "Retrieves a value from localStorage by key and parses it.", "author": "dostonnabotov", "tags": [ - "javascript", "localStorage", - "storage", - "utility" + "storage" ], "contributors": [], - "code": "const getFromLocalStorage = (key) => {\n const item = localStorage.getItem(key);\n return item ? JSON.parse(item) : null;\n};\n\n// Usage:\nconst user = getFromLocalStorage('user');\nconsole.log(user); // Output: { name: 'John', age: 30 }\n" + "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" } ] }, @@ -513,78 +356,66 @@ "description": "Converts a number to a currency format with a specific locale.", "author": "axorax", "tags": [ - "javascript", "number", - "currency", - "utility" + "currency" ], "contributors": [], - "code": "const convertToCurrency = (num, locale = 'en-US', currency = 'USD') => {\n return new Intl.NumberFormat(locale, {\n style: 'currency',\n currency: currency\n }).format(num);\n};\n\n// Usage:\nconsole.log(convertToCurrency(1234567.89)); // Output: '$1,234,567.89'\nconsole.log(convertToCurrency(987654.32, 'de-DE', 'EUR')); // Output: '987.654,32 €'\n" + "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", "tags": [ - "javascript", "number", - "roman", - "utility" + "roman" ], "contributors": [], - "code": "const numberToRoman = (num) => {\n const romanNumerals = {\n 1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L',\n 90: 'XC', 100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M'\n };\n let result = '';\n Object.keys(romanNumerals).reverse().forEach(value => {\n while (num >= value) {\n result += romanNumerals[value];\n num -= value;\n }\n });\n return result;\n};\n\n// Usage:\nconsole.log(numberToRoman(1994)); // Output: 'MCMXCIV'\nconsole.log(numberToRoman(58)); // Output: 'LVIII'\n" + "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", "tags": [ - "javascript", "number", - "scientific", - "utility" + "scientific" ], "contributors": [], - "code": "const toScientificNotation = (num) => {\n if (isNaN(num)) {\n throw new Error('Input must be a number');\n }\n if (num === 0) {\n return '0e+0';\n }\n const exponent = Math.floor(Math.log10(Math.abs(num)));\n const mantissa = num / Math.pow(10, exponent);\n return `${mantissa.toFixed(2)}e${exponent >= 0 ? '+' : ''}${exponent}`;\n};\n\n// Usage:\nconsole.log(toScientificNotation(12345)); // Output: '1.23e+4'\nconsole.log(toScientificNotation(0.0005678)); // Output: '5.68e-4'\nconsole.log(toScientificNotation(1000)); // Output: '1.00e+3'\nconsole.log(toScientificNotation(0)); // Output: '0e+0'\nconsole.log(toScientificNotation(-54321)); // Output: '-5.43e+4'\n" + "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 Number with Commas", "description": "Formats a number with commas for better readability (e.g., 1000 -> 1,000).", "author": "axorax", "tags": [ - "javascript", "number", - "format", - "utility" + "format" ], "contributors": [], - "code": "const formatNumberWithCommas = (num) => {\n return num.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n};\n\n// Usage:\nconsole.log(formatNumberWithCommas(1000)); // Output: '1,000'\nconsole.log(formatNumberWithCommas(1234567)); // Output: '1,234,567'\nconsole.log(formatNumberWithCommas(987654321)); // Output: '987,654,321'\n" + "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", "tags": [ - "javascript", "number", - "format", - "utility" + "format" ], "contributors": [], - "code": "const nFormatter = (num) => {\n if (!num) return;\n num = parseFloat(num.toString().replace(/[^0-9.]/g, ''));\n const suffixes = ['', 'K', 'M', 'B', 'T', 'P', 'E'];\n let index = 0;\n while (num >= 1000 && index < suffixes.length - 1) {\n num /= 1000;\n index++;\n }\n return num.toFixed(2).replace(/\\.0+$|(\\.[0-9]*[1-9])0+$/, '$1') + suffixes[index];\n};\n\n// Usage:\nconsole.log(nFormatter(1234567)); // Output: '1.23M'\n" + "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", "tags": [ - "javascript", "number", - "words", - "utility" + "words" ], "contributors": [], - "code": "const numberToWords = (num) => {\n const below20 = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'];\n const tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];\n const above1000 = ['Hundred', 'Thousand', 'Million', 'Billion'];\n if (num < 20) return below20[num];\n let words = '';\n for (let i = 0; num > 0; i++) {\n if (i > 0 && num % 1000 !== 0) words = above1000[i] + ' ' + words;\n if (num % 100 >= 20) {\n words = tens[Math.floor(num / 10)] + ' ' + words;\n num %= 10;\n }\n if (num < 20) words = below20[num] + ' ' + words;\n num = Math.floor(num / 100);\n }\n return words.trim();\n};\n\n// Usage:\nconsole.log(numberToWords(123)); // Output: 'One Hundred Twenty Three'\nconsole.log(numberToWords(2045)); // Output: 'Two Thousand Forty Five'\n" + "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" } ] }, @@ -596,198 +427,149 @@ "description": "Checks whether an object has no own enumerable properties.", "author": "axorax", "tags": [ - "javascript", "object", "check", "empty" ], "contributors": [], - "code": "function isEmptyObject(obj) {\n return Object.keys(obj).length === 0;\n}\n\n// Usage:\nconsole.log(isEmptyObject({})); // Output: true\nconsole.log(isEmptyObject({ a: 1 })); // Output: false\n" - }, - { - "title": "Clone Object Shallowly", - "description": "Creates a shallow copy of an object.", - "author": "axorax", - "tags": [ - "javascript", - "object", - "clone", - "shallow" - ], - "contributors": [], - "code": "function shallowClone(obj) {\n return { ...obj };\n}\n\n// Usage:\nconst obj = { a: 1, b: 2 };\nconst clone = shallowClone(obj);\nconsole.log(clone); // Output: { a: 1, b: 2 }\n" + "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", "tags": [ - "javascript", "object", "compare", "shallow" ], "contributors": [], - "code": "function shallowEqual(obj1, obj2) {\n const keys1 = Object.keys(obj1);\n const keys2 = Object.keys(obj2);\n if (keys1.length !== keys2.length) return false;\n return keys1.every(key => obj1[key] === obj2[key]);\n}\n\n// Usage:\nconst obj1 = { a: 1, b: 2 };\nconst obj2 = { a: 1, b: 2 };\nconst obj3 = { a: 1, b: 3 };\nconsole.log(shallowEqual(obj1, obj2)); // Output: true\nconsole.log(shallowEqual(obj1, obj3)); // Output: false\n" + "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", "tags": [ - "javascript", "object", "query string", "url" ], "contributors": [], - "code": "function toQueryString(obj) {\n return Object.entries(obj)\n .map(([key, value]) => encodeURIComponent(key) + '=' + encodeURIComponent(value))\n .join('&');\n}\n\n// Usage:\nconst params = { search: 'test', page: 1 };\nconsole.log(toQueryString(params)); // Output: 'search=test&page=1'\n" + "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", "tags": [ - "javascript", "object", "count", "properties" ], "contributors": [], - "code": "function countProperties(obj) {\n return Object.keys(obj).length;\n}\n\n// Usage:\nconst obj = { a: 1, b: 2, c: 3 };\nconsole.log(countProperties(obj)); // Output: 3\n" + "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": "Filter Object", "description": "Filter out entries in an object where the value is falsy, including empty strings, empty objects, null, and undefined.", "author": "realvishalrana", "tags": [ - "javascript", "object", - "filter", - "utility" + "filter" ], "contributors": [], - "code": "export const filterObject = (object = {}) =>\n Object.fromEntries(\n Object.entries(object)\n .filter(([key, value]) => value !== null && value !== undefined && value !== '' && (typeof value !== 'object' || Object.keys(value).length > 0))\n );\n\n// Usage:\nconst obj1 = { a: 1, b: null, c: undefined, d: 4, e: '', f: {} };\nconsole.log(filterObject(obj1)); // Output: { a: 1, d: 4 }\n\nconst obj2 = { x: 0, y: false, z: 'Hello', w: [] };\nconsole.log(filterObject(obj2)); // Output: { z: 'Hello' }\n\nconst obj3 = { name: 'John', age: null, address: { city: 'New York' }, phone: '' };\nconsole.log(filterObject(obj3)); // Output: { name: 'John', address: { city: 'New York' } }\n\nconst obj4 = { a: 0, b: '', c: false, d: {}, e: 'Valid' };\nconsole.log(filterObject(obj4)); // Output: { e: 'Valid' }\n" + "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", "tags": [ - "javascript", "object", - "flatten", - "utility" + "flatten" ], "contributors": [], - "code": "function flattenObject(obj, prefix = '') {\n return Object.keys(obj).reduce((acc, key) => {\n const fullPath = prefix ? `${prefix}.${key}` : key;\n if (typeof obj[key] === 'object' && obj[key] !== null) {\n Object.assign(acc, flattenObject(obj[key], fullPath));\n } else {\n acc[fullPath] = obj[key];\n }\n return acc;\n }, {});\n}\n\n// Usage:\nconst nestedObj = { a: { b: { c: 1 }, d: 2 }, e: 3 };\nconsole.log(flattenObject(nestedObj)); // Output: { 'a.b.c': 1, 'a.d': 2, e: 3 }\n" + "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", "tags": [ - "javascript", "object", "freeze", "immutable" ], "contributors": [], - "code": "function freezeObject(obj) {\n return Object.freeze(obj);\n}\n\n// Usage:\nconst obj = { a: 1, b: 2 };\nconst frozenObj = freezeObject(obj);\nfrozenObj.a = 42; // This will fail silently in strict mode.\nconsole.log(frozenObj.a); // Output: 1\n" + "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", "tags": [ - "javascript", "object", - "nested", - "utility" + "nested" ], "contributors": [], - "code": "const getNestedValue = (obj, path) => {\n const keys = path.split('.');\n return keys.reduce((currentObject, key) => {\n return currentObject && typeof currentObject === 'object' ? currentObject[key] : undefined;\n }, obj);\n};\n\n// Usage:\nconst obj = { a: { b: { c: 42 } } };\nconsole.log(getNestedValue(obj, 'a.b.c')); // Output: 42\n" + "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", "tags": [ - "javascript", "object", - "invert", - "utility" + "invert" ], "contributors": [], - "code": "function invertObject(obj) {\n return Object.fromEntries(\n Object.entries(obj).map(([key, value]) => [value, key])\n );\n}\n\n// Usage:\nconst obj = { a: 1, b: 2, c: 3 };\nconsole.log(invertObject(obj)); // Output: { '1': 'a', '2': 'b', '3': 'c' }\n" + "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", "tags": [ - "javascript", "object", "merge", "deep" ], "contributors": [], - "code": "function deepMerge(...objects) {\n return objects.reduce((acc, obj) => {\n Object.keys(obj).forEach(key => {\n if (typeof obj[key] === 'object' && obj[key] !== null) {\n acc[key] = deepMerge(acc[key] || {}, obj[key]);\n } else {\n acc[key] = obj[key];\n }\n });\n return acc;\n }, {});\n}\n\n// Usage:\nconst obj1 = { a: 1, b: { c: 2 } };\nconst obj2 = { b: { d: 3 }, e: 4 };\nconsole.log(deepMerge(obj1, obj2)); // Output: { a: 1, b: { c: 2, d: 3 }, e: 4 }\n" + "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", "tags": [ - "javascript", "object", - "omit", - "utility" + "omit" ], "contributors": [], - "code": "function omitKeys(obj, keys) {\n return Object.fromEntries(\n Object.entries(obj).filter(([key]) => !keys.includes(key))\n );\n}\n\n// Usage:\nconst obj = { a: 1, b: 2, c: 3 };\nconsole.log(omitKeys(obj, ['b', 'c'])); // Output: { a: 1 }\n" + "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", "tags": [ - "javascript", "object", - "pick", - "utility" + "pick" ], "contributors": [], - "code": "function pickKeys(obj, keys) {\n return Object.fromEntries(\n Object.entries(obj).filter(([key]) => keys.includes(key))\n );\n}\n\n// Usage:\nconst obj = { a: 1, b: 2, c: 3 };\nconsole.log(pickKeys(obj, ['a', 'c'])); // Output: { a: 1, c: 3 }\n" + "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", "tags": [ - "javascript", "array", - "unique", - "utility" - ], - "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];\nconsole.log(uniqueByKey('id', arr)); // Output: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]\n" - } - ] - }, - { - "categoryName": "Regular Expression", - "snippets": [ - { - "title": "Regex Match Utility Function", - "description": "Enhanced regular expression matching utility.", - "author": "aumirza", - "tags": [ - "javascript", - "regex" + "unique" ], "contributors": [], - "code": "/**\n* @param {string | number} input\n* The input string to match\n* @param {regex | string} expression\n* Regular expression\n* @param {string} flags\n* Optional Flags\n*\n* @returns {array}\n* [{\n* match: '...',\n* matchAtIndex: 0,\n* capturedGroups: [ '...', '...' ]\n* }]\n*/\nfunction regexMatch(input, expression, flags = 'g') {\n let regex =\n expression instanceof RegExp\n ? expression\n : new RegExp(expression, flags);\n let matches = input.matchAll(regex);\n matches = [...matches];\n return matches.map((item) => {\n return {\n match: item[0],\n matchAtIndex: item.index,\n capturedGroups: item.length > 1 ? item.slice(1) : undefined,\n };\n });\n}\n" + "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" } ] }, @@ -799,26 +581,23 @@ "description": "Capitalizes the first letter of a string.", "author": "dostonnabotov", "tags": [ - "javascript", "string", - "capitalize", - "utility" + "capitalize" ], "contributors": [], - "code": "const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);\n\n// Usage:\nconsole.log(capitalize('hello')); // Output: 'Hello'\n" + "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", "tags": [ - "javascript", "check", "palindrome", "string" ], "contributors": [], - "code": "function isPalindrome(str) {\n const cleanStr = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();\n return cleanStr === cleanStr.split('').reverse().join('');\n}\n\n// Example usage:\nconsole.log(isPalindrome('A man, a plan, a canal, Panama')); // Output: true\n" + "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", @@ -830,7 +609,7 @@ "camelCase" ], "contributors": [], - "code": "function toCamelCase(str) {\n return str.replace(/\\W+(.)/g, (match, chr) => chr.toUpperCase());\n}\n\n// Example usage:\nconsole.log(toCamelCase('hello world test')); // Output: 'helloWorldTest'\n" + "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", @@ -842,7 +621,7 @@ "paramCase" ], "contributors": [], - "code": "function toParamCase(str) {\n return str.toLowerCase().replace(/\\s+/g, '-');\n}\n\n// Example usage:\nconsole.log(toParamCase('Hello World Test')); // Output: 'hello-world-test'\n" + "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", @@ -854,7 +633,7 @@ "pascalCase" ], "contributors": [], - "code": "function toPascalCase(str) {\n return str.replace(/\\b\\w/g, (s) => s.toUpperCase()).replace(/\\W+(.)/g, (match, chr) => chr.toUpperCase());\n}\n\n// Example usage:\nconsole.log(toPascalCase('hello world test')); // Output: 'HelloWorldTest'\n" + "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", @@ -866,7 +645,7 @@ "snake_case" ], "contributors": [], - "code": "function toSnakeCase(str) {\n return str.replace(/([a-z])([A-Z])/g, '$1_$2')\n .replace(/\\s+/g, '_')\n .toLowerCase();\n}\n\n// Example usage:\nconsole.log(toSnakeCase('Hello World Test')); // Output: 'hello_world_test'\n" + "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", @@ -878,7 +657,7 @@ "titleCase" ], "contributors": [], - "code": "function toTitleCase(str) {\n return str.toLowerCase().replace(/\\b\\w/g, (s) => s.toUpperCase());\n}\n\n// Example usage:\nconsole.log(toTitleCase('hello world test')); // Output: 'Hello World Test'\n" + "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", @@ -890,33 +669,33 @@ "spaces" ], "contributors": [], - "code": "function tabsToSpaces(str, spacesPerTab = 4) {\n return str.replace(/\\t/g, ' '.repeat(spacesPerTab));\n}\n\n// Example usage:\nconsole.log(tabsToSpaces('Hello\\tWorld', 2)); // Output: 'Hello World'\n" + "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", "tags": [ - "javascript", "string", "manipulation", "word count", "count" ], "contributors": [], - "code": "function countWords(str) {\n return str.trim().split(/\\s+/).length;\n}\n\n// Example usage:\nconsole.log(countWords('Hello world! This is a test.')); // Output: 6\n" + "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", "tags": [ - "javascript", "data", - "utility" + "prefix", + "postfix", + "format" ], "contributors": [], - "code": "const dataWithPrefix = (data, fallback = '-', prefix = '', postfix = '') => {\n return data ? `${prefix}${data}${postfix}` : fallback;\n};\n\n// Usage:\nconsole.log(dataWithPrefix('123', '-', '(', ')')); // Output: '(123)'\nconsole.log(dataWithPrefix('', '-', '(', ')')); // Output: '-'\nconsole.log(dataWithPrefix('Hello', 'N/A', 'Mr. ', '')); // Output: 'Mr. Hello'\nconsole.log(dataWithPrefix(null, 'N/A', 'Mr. ', '')); // Output: 'N/A'\n" + "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", @@ -928,7 +707,7 @@ "name" ], "contributors": [], - "code": "function getInitials(name) {\n return name.split(' ').map(part => part.charAt(0).toUpperCase()).join('');\n}\n\n// Example usage:\nconsole.log(getInitials('John Doe')); // Output: 'JD'\n" + "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": "Mask Sensitive Information", @@ -940,7 +719,7 @@ "sensitive" ], "contributors": [], - "code": "function maskSensitiveInfo(str, visibleCount = 4, maskChar = '*') {\n return str.slice(0, visibleCount) + maskChar.repeat(Math.max(0, str.length - visibleCount));\n}\n\n// Example usage:\nconsole.log(maskSensitiveInfo('123456789', 4)); // Output: '1234*****'\nconsole.log(maskSensitiveInfo('example@mail.com', 2, '#')); // Output: 'ex#############'\n" + "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", @@ -952,31 +731,29 @@ "manipulation" ], "contributors": [], - "code": "function padString(str, length, char = ' ') {\n const totalPad = length - str.length;\n const padStart = Math.floor(totalPad / 2);\n const padEnd = totalPad - padStart;\n return char.repeat(padStart) + str + char.repeat(padEnd);\n}\n\n// Example usage:\nconsole.log(padString('hello', 10, '*')); // Output: '**hello***'\n" + "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", "tags": [ - "javascript", "function", "random" ], "contributors": [], - "code": "function makeid(length, characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {\n return Array.from({ length }, () => characters.charAt(Math.floor(Math.random() * characters.length))).join('');\n}\n\nconsole.log(makeid(5, \"1234\" /* (optional) */));\n" + "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", "tags": [ - "javascript", "string", "whitespace" ], "contributors": [], - "code": "function removeWhitespace(str) {\n return str.replace(/\\s+/g, '');\n}\n\n// Example usage:\nconsole.log(removeWhitespace('Hello world!')); // Output: 'Helloworld!'\n" + "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", @@ -988,47 +765,41 @@ "vowels" ], "contributors": [], - "code": "function removeVowels(str) {\n return str.replace(/[aeiouAEIOU]/g, '');\n}\n\n// Example usage:\nconsole.log(removeVowels('Hello World')); // Output: 'Hll Wrld'\n" + "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", "tags": [ - "javascript", "string", - "reverse", - "utility" + "reverse" ], "contributors": [], - "code": "const reverseString = (str) => str.split('').reverse().join('');\n\n// Usage:\nconsole.log(reverseString('hello')); // Output: 'olleh'\n" + "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", "tags": [ - "javascript", "string", - "slug", - "utility" + "slug" ], "contributors": [], - "code": "const slugify = (string, separator = \"-\") => {\n return string\n .toString() // Cast to string (optional)\n .toLowerCase() // Convert the string to lowercase letters\n .trim() // Remove whitespace from both sides of a string (optional)\n .replace(/\\s+/g, separator) // Replace spaces with {separator}\n .replace(/[^\\w\\-]+/g, \"\") // Remove all non-word chars\n .replace(/\\_/g, separator) // Replace _ with {separator}\n .replace(/\\-\\-+/g, separator) // Replace multiple - with single {separator}\n .replace(/\\-$/g, \"\"); // Remove trailing -\n};\n\n// Usage:\nconst title = \"Hello, World! This is a Test.\";\nconsole.log(slugify(title)); // Output: 'hello-world-this-is-a-test'\nconsole.log(slugify(title, \"_\")); // Output: 'hello_world_this_is_a_test'\n" + "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", "tags": [ - "javascript", "string", "truncate", - "utility", "text" ], "contributors": [], - "code": "const truncateText = (text = '', maxLength = 50) => {\n return `${text.slice(0, maxLength)}${text.length >= maxLength ? '...' : ''}`;\n};\n\n// Usage:\nconst title = \"Hello, World! This is a Test.\";\nconsole.log(truncateText(title)); // Output: 'Hello, World! This is a Test.'\nconsole.log(truncateText(title, 10)); // Output: 'Hello, Wor...'\n" + "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 940ca4a2..953272b8 100644 --- a/public/consolidated/python.json +++ b/public/consolidated/python.json @@ -7,10 +7,8 @@ "description": "Prints Hello, World! to the terminal.", "author": "James-Beans", "tags": [ - "python", "printing", - "hello-world", - "utility" + "hello-world" ], "contributors": [], "code": "print(\"Hello, World!\") # Prints Hello, World! to the terminal.\n" @@ -25,76 +23,78 @@ "description": "Calculates the difference between two dates in milliseconds.", "author": "e3nviction", "tags": [ - "python", "datetime", - "utility" + "difference" ], "contributors": [], - "code": "from datetime import datetime\n\ndef date_difference_in_millis(date1, date2):\n delta = date2 - date1\n return delta.total_seconds() * 1000\n\n# Usage:\nd1 = datetime(2023, 1, 1, 12, 0, 0)\nd2 = datetime(2023, 1, 1, 12, 1, 0)\nprint(date_difference_in_millis(d1, d2))\n" + "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", "tags": [ - "python", "datetime", - "weekend", - "utility" + "weekend" ], "contributors": [], - "code": "from datetime import datetime\n\ndef is_weekend(date):\n try:\n return date.weekday() >= 5 # Saturday = 5, Sunday = 6\n except AttributeError:\n raise TypeError(\"Input must be a datetime object\")\n\n# Usage:\ndate = datetime(2023, 1, 1)\nweekend = is_weekend(date)\nprint(weekend) # Output: True (Sunday)\n" + "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": "Determine Day of the Week", - "description": "Calculates the day of the week for a given date.", + "title": "Day of the Week String", + "description": "Gets the string of the day of the week for a given date.", "author": "axorax", "tags": [ - "python", "datetime", - "weekday", - "utility" + "weekday" ], "contributors": [], - "code": "from datetime import datetime\n\ndef get_day_of_week(date):\n days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\n try:\n return days[date.weekday()]\n except IndexError:\n raise ValueError(\"Invalid date\")\n\n# Usage:\ndate = datetime(2023, 1, 1)\nday = get_day_of_week(date)\nprint(day) # Output: 'Sunday'\n" + "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", "tags": [ - "python", "datetime", - "range", - "utility" + "range" ], "contributors": [], - "code": "from datetime import datetime, timedelta\n\ndef generate_date_range(start_date, end_date):\n if start_date > end_date:\n raise ValueError(\"start_date must be before end_date\")\n\n current_date = start_date\n date_list = []\n while current_date <= end_date:\n date_list.append(current_date)\n current_date += timedelta(days=1)\n\n return date_list\n\n# Usage:\nstart = datetime(2023, 1, 1)\nend = datetime(2023, 1, 5)\ndates = generate_date_range(start, end)\nfor d in dates:\n print(d.strftime('%Y-%m-%d'))\n# Output: '2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05'\n" + "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 String", + "title": "Get Current Date and Time as String", "description": "Fetches the current date and time as a formatted string.", "author": "e3nviction", "tags": [ - "python", "datetime", - "utility" + "current", + "string" ], "contributors": [], - "code": "from datetime import datetime\n\ndef get_current_datetime_string():\n return datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n\n# Usage:\nprint(get_current_datetime_string()) # Output: '2023-01-01 12:00:00'\n" + "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", "tags": [ - "python", "datetime", - "calendar", - "utility" + "calendar" + ], + "contributors": [], + "code": "from calendar import monthrange\nfrom datetime import datetime\n\ndef get_days_in_month(year, month):\n try:\n return monthrange(year, month)[1]\n except ValueError as e:\n raise ValueError(f\"Invalid month or year: {e}\")\n\n# Usage:\nget_days_in_month(2023, 2) # Returns: 28 (for non-leap year February)\n" + }, + { + "title": "Measure Execution Time", + "description": "Measures the execution time of a code block.", + "author": "dostonnabotov", + "tags": [ + "time", + "execution" ], "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:\ndays = get_days_in_month(2023, 2)\nprint(days) # Output: 28 (for non-leap year February)\n" + "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" } ] }, @@ -114,195 +114,68 @@ "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": "Handle File Not Found Error", - "description": "Attempts to open a file and handles the case where the file does not exist.", - "author": "axorax", - "tags": [ - "python", - "error-handling", - "file", - "utility" - ], - "contributors": [], - "code": "def read_file_safe(filepath):\n try:\n with open(filepath, 'r') as file:\n return file.read()\n except FileNotFoundError:\n return \"File not found!\"\n\n# Usage:\nprint(read_file_safe('nonexistent.txt')) # Output: 'File not found!'\n" - }, { "title": "Retry Function Execution on Exception", "description": "Retries a function execution a specified number of times if it raises an exception.", "author": "axorax", "tags": [ - "python", "error-handling", - "retry", - "utility" + "retry" ], "contributors": [], "code": "import time\n\ndef retry(func, retries=3, delay=1):\n for attempt in range(retries):\n try:\n return func()\n except Exception as e:\n print(f\"Attempt {attempt + 1} failed: {e}\")\n time.sleep(delay)\n raise Exception(\"All retry attempts failed\")\n\n# Usage:\ndef unstable_function():\n raise ValueError(\"Simulated failure\")\n\n# Retry 3 times with 2 seconds delay:\ntry:\n retry(unstable_function, retries=3, delay=2)\nexcept Exception as e:\n print(e) # Output: All retry attempts failed\n" - }, - { - "title": "Safe Division", - "description": "Performs division with error handling.", - "author": "e3nviction", - "tags": [ - "python", - "error-handling", - "division", - "utility" - ], - "contributors": [], - "code": "def safe_divide(a, b):\n try:\n return a / b\n except ZeroDivisionError:\n return 'Cannot divide by zero!'\n\n# Usage:\nprint(safe_divide(10, 2)) # Output: 5.0\nprint(safe_divide(10, 0)) # Output: 'Cannot divide by zero!'\n" - }, - { - "title": "Validate Input with Exception Handling", - "description": "Validates user input and handles invalid input gracefully.", - "author": "axorax", - "tags": [ - "python", - "error-handling", - "validation", - "utility" - ], - "contributors": [], - "code": "def validate_positive_integer(input_value):\n try:\n value = int(input_value)\n if value < 0:\n raise ValueError(\"The number must be positive\")\n return value\n except ValueError as e:\n return f\"Invalid input: {e}\"\n\n# Usage:\nprint(validate_positive_integer('10')) # Output: 10\nprint(validate_positive_integer('-5')) # Output: Invalid input: The number must be positive\nprint(validate_positive_integer('abc')) # Output: Invalid input: invalid literal for int() with base 10: 'abc'\n" } ] }, { "categoryName": "File Handling", "snippets": [ - { - "title": "Append to File", - "description": "Appends content to the end of a file.", - "author": "axorax", - "tags": [ - "python", - "file", - "append", - "utility" - ], - "contributors": [], - "code": "def append_to_file(filepath, content):\n with open(filepath, 'a') as file:\n file.write(content + '\\n')\n\n# Usage:\nappend_to_file('example.txt', 'This is an appended line.')\n" - }, - { - "title": "Check if File Exists", - "description": "Checks if a file exists at the specified path.", - "author": "axorax", - "tags": [ - "python", - "file", - "exists", - "check", - "utility" - ], - "contributors": [], - "code": "import os\n\ndef file_exists(filepath):\n return os.path.isfile(filepath)\n\n# Usage:\nprint(file_exists('example.txt')) # Output: True or False\n" - }, - { - "title": "Copy File", - "description": "Copies a file from source to destination.", - "author": "axorax", - "tags": [ - "python", - "file", - "copy", - "utility" - ], - "contributors": [], - "code": "import shutil\n\ndef copy_file(src, dest):\n shutil.copy(src, dest)\n\n# Usage:\ncopy_file('example.txt', 'copy_of_example.txt')\n" - }, - { - "title": "Delete File", - "description": "Deletes a file at the specified path.", - "author": "axorax", - "tags": [ - "python", - "file", - "delete", - "utility" - ], - "contributors": [], - "code": "import os\n\ndef delete_file(filepath):\n if os.path.exists(filepath):\n os.remove(filepath)\n print(f'File {filepath} deleted.')\n else:\n print(f'File {filepath} does not exist.')\n\n# Usage:\ndelete_file('example.txt')\n" - }, { "title": "Find Files", "description": "Finds all files of the specified type within a given directory.", "author": "Jackeastern", "tags": [ - "python", "os", "filesystem", "file_search" ], "contributors": [], - "code": "import os\n\ndef find_files(directory, file_type):\n file_type = file_type.lower() # Convert file_type to lowercase\n found_files = []\n\n for root, _, files in os.walk(directory):\n for file in files:\n file_ext = os.path.splitext(file)[1].lower()\n if file_ext == file_type:\n full_path = os.path.join(root, file)\n found_files.append(full_path)\n\n return found_files\n\n# Example Usage:\npdf_files = find_files('/path/to/your/directory', '.pdf')\nprint(pdf_files)\n" + "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", "tags": [ - "python", "file", - "extension", - "utility" + "extension" ], "contributors": [], - "code": "import os\n\ndef get_file_extension(filepath):\n return os.path.splitext(filepath)[1]\n\n# Usage:\nprint(get_file_extension('example.txt')) # Output: '.txt'\n" + "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", "tags": [ - "python", "file", "list", - "directory", - "utility" + "directory" ], "contributors": [], - "code": "import os\n\ndef list_files(directory):\n return [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]\n\n# Usage:\nfiles = list_files('/path/to/directory')\nprint(files)\n" + "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", "tags": [ - "python", "file", "read", - "chunks", - "utility" + "chunks" ], "contributors": [], - "code": "def read_file_in_chunks(filepath, chunk_size):\n with open(filepath, 'r') as file:\n while chunk := file.read(chunk_size):\n yield chunk\n\n# Usage:\nfor chunk in read_file_in_chunks('example.txt', 1024):\n print(chunk)\n" - }, - { - "title": "Read File Lines", - "description": "Reads all lines from a file and returns them as a list.", - "author": "dostonnabotov", - "tags": [ - "python", - "file", - "read", - "utility" - ], - "contributors": [], - "code": "def read_file_lines(filepath):\n with open(filepath, 'r') as file:\n return file.readlines()\n\n# Usage:\nlines = read_file_lines('example.txt')\nprint(lines)\n" - }, - { - "title": "Write to File", - "description": "Writes content to a file.", - "author": "dostonnabotov", - "tags": [ - "python", - "file", - "write", - "utility" - ], - "contributors": [], - "code": "def write_to_file(filepath, content):\n with open(filepath, 'w') as file:\n file.write(content)\n\n# Usage:\nwrite_to_file('example.txt', 'Hello, World!')\n" + "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" } ] }, @@ -314,33 +187,30 @@ "description": "Filters a JSON object based on a condition and returns the filtered data.", "author": "axorax", "tags": [ - "python", "json", "filter", "data" ], "contributors": [], - "code": "import json\n\ndef filter_json_data(filepath, condition):\n with open(filepath, 'r') as file:\n data = json.load(file)\n\n # Filter data based on the provided condition\n filtered_data = [item for item in data if condition(item)]\n\n return filtered_data\n\n# Usage:\ncondition = lambda x: x['age'] > 25\nfiltered = filter_json_data('data.json', condition)\nprint(filtered)\n" + "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", "tags": [ - "python", "json", "flatten", "nested" ], "contributors": [], - "code": "def flatten_json(nested_json, prefix=''):\n flat_dict = {}\n for key, value in nested_json.items():\n if isinstance(value, dict):\n flat_dict.update(flatten_json(value, prefix + key + '.'))\n else:\n flat_dict[prefix + key] = value\n return flat_dict\n\n# Usage:\nnested_json = {'name': 'John', 'address': {'city': 'New York', 'zip': '10001'}}\nflattened = flatten_json(nested_json)\nprint(flattened) # Output: {'name': 'John', 'address.city': 'New York', 'address.zip': '10001'}\n" + "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", "tags": [ - "python", "json", "merge", "file" @@ -353,46 +223,30 @@ "description": "Reads a JSON file and parses its content.", "author": "e3nviction", "tags": [ - "python", "json", "file", "read" ], "contributors": [], - "code": "import json\n\ndef read_json(filepath):\n with open(filepath, 'r') as file:\n return json.load(file)\n\n# Usage:\ndata = read_json('data.json')\nprint(data)\n" + "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", "tags": [ - "python", "json", "update", "file" ], "contributors": [], - "code": "import json\n\ndef update_json(filepath, new_data):\n # Read the existing JSON data\n with open(filepath, 'r') as file:\n data = json.load(file)\n\n # Update the data with the new content\n data.update(new_data)\n\n # Write the updated data back to the JSON file\n with open(filepath, 'w') as file:\n json.dump(data, file, indent=4)\n\n# Usage:\nnew_data = {'age': 31}\nupdate_json('data.json', new_data)\n" - }, - { - "title": "Validate JSON Schema", - "description": "Validates a JSON object against a predefined schema.", - "author": "axorax", - "tags": [ - "python", - "json", - "validation", - "schema" - ], - "contributors": [], - "code": "import jsonschema\nfrom jsonschema import validate\n\ndef validate_json_schema(data, schema):\n try:\n validate(instance=data, schema=schema)\n return True # Data is valid\n except jsonschema.exceptions.ValidationError as err:\n return False # Data is invalid\n\n# Usage:\nschema = {\n 'type': 'object',\n 'properties': {\n 'name': {'type': 'string'},\n 'age': {'type': 'integer'}\n },\n 'required': ['name', 'age']\n}\ndata = {'name': 'John', 'age': 30}\nis_valid = validate_json_schema(data, schema)\nprint(is_valid) # Output: True\n" + "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", "tags": [ - "python", "json", "file", "write" @@ -410,93 +264,80 @@ "description": "Identifies duplicate elements in a list.", "author": "axorax", "tags": [ - "python", "list", - "duplicates", - "utility" + "duplicates" ], "contributors": [], - "code": "def find_duplicates(lst):\n seen = set()\n duplicates = set()\n for item in lst:\n if item in seen:\n duplicates.add(item)\n else:\n seen.add(item)\n return list(duplicates)\n\n# Usage:\ndata = [1, 2, 3, 2, 4, 5, 1]\nprint(find_duplicates(data)) # Output: [1, 2]\n" + "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", "tags": [ - "python", "list", - "intersection", - "utility" + "intersection" ], "contributors": [], - "code": "def list_intersection(lst1, lst2):\n return [item for item in lst1 if item in lst2]\n\n# Usage:\nlist_a = [1, 2, 3, 4]\nlist_b = [3, 4, 5, 6]\nprint(list_intersection(list_a, list_b)) # Output: [3, 4]\n" + "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", "tags": [ - "python", "list", - "difference", - "utility" + "difference" ], "contributors": [], - "code": "def max_difference(lst):\n if not lst or len(lst) < 2:\n return 0\n return max(lst) - min(lst)\n\n# Usage:\ndata = [10, 3, 5, 20, 7]\nprint(max_difference(data)) # Output: 17\n" + "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", "tags": [ - "python", "list", - "flatten", - "utility" + "flatten" ], "contributors": [], - "code": "def flatten_list(lst):\n return [item for sublist in lst for item in sublist]\n\n# Usage:\nnested_list = [[1, 2], [3, 4], [5]]\nprint(flatten_list(nested_list)) # Output: [1, 2, 3, 4, 5]\n" + "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", "tags": [ - "python", "list", "flattening", "nested-lists", - "depth", - "utilities" + "depth" ], "contributors": [], - "code": "def flatten(nested_list):\n \"\"\"\n Flattens unevenly nested lists of any depth into a single flat list.\n \"\"\"\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]\nflattened = list(flatten(nested_list))\nprint(flattened) # Output: [1, 2, 3, 4, 5]\n" + "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", "tags": [ - "python", "list", - "partition", - "utility" + "partition" ], "contributors": [], - "code": "def partition_list(lst, size):\n for i in range(0, len(lst), size):\n yield lst[i:i + size]\n\n# Usage:\ndata = [1, 2, 3, 4, 5, 6, 7]\npartitions = list(partition_list(data, 3))\nprint(partitions) # Output: [[1, 2, 3], [4, 5, 6], [7]]\n" + "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", "tags": [ - "python", "list", "duplicates", - "utility" + "filter" ], "contributors": [], - "code": "def remove_duplicates(lst):\n return list(dict.fromkeys(lst))\n\n# Usage:\nprint(remove_duplicates([1, 2, 2, 3, 4, 4, 5])) # Output: [1, 2, 3, 4, 5]\n" + "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" } ] }, @@ -514,60 +355,55 @@ "finance" ], "contributors": [], - "code": "def compound_interest(principal, rate, time, n=1):\n return principal * (1 + rate / n) ** (n * time)\n\n# Usage:\nprint(compound_interest(1000, 0.05, 5)) # Output: 1276.2815625000003\nprint(compound_interest(1000, 0.05, 5, 12)) # Output: 1283.68\n" + "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", "tags": [ - "python", "math", "perfect square", "check" ], "contributors": [], - "code": "def is_perfect_square(n):\n if n < 0:\n return False\n root = int(n**0.5)\n return root * root == n\n\n# Usage:\nprint(is_perfect_square(16)) # Output: True\nprint(is_perfect_square(20)) # Output: False\n" + "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", "tags": [ - "python", "math", "prime", "check" ], "contributors": [], - "code": "def is_prime(n):\n if n <= 1:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return False\n return True\n\n# Usage:\nprint(is_prime(17)) # Output: True\n" + "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", "tags": [ - "python", "math", "binary", "decimal", "conversion" ], "contributors": [], - "code": "def binary_to_decimal(binary_str):\n return int(binary_str, 2)\n\n# Usage:\nprint(binary_to_decimal('1010')) # Output: 10\nprint(binary_to_decimal('1101')) # Output: 13\n" + "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": "Find Factorial", - "description": "Calculates the factorial of a number.", - "author": "dostonnabotov", + "title": "Convert Bytes to Human-Readable Format", + "description": "Converts a size in bytes to a human-readable format.", + "author": "axorax", "tags": [ - "python", - "math", - "factorial", - "utility" + "bytes", + "format" ], "contributors": [], - "code": "def factorial(n):\n if n == 0:\n return 1\n return n * factorial(n - 1)\n\n# Usage:\nprint(factorial(5)) # Output: 120\n" + "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)", @@ -581,21 +417,20 @@ "utility" ], "contributors": [], - "code": "def lcm(a, b):\n return abs(a * b) // gcd(a, b)\n\n# Usage:\nprint(lcm(12, 15)) # Output: 60\nprint(lcm(7, 5)) # Output: 35\n" + "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", "tags": [ - "python", "math", "quadratic", "equation", "solver" ], "contributors": [], - "code": "import cmath\n\ndef solve_quadratic(a, b, c):\n discriminant = cmath.sqrt(b**2 - 4 * a * c)\n root1 = (-b + discriminant) / (2 * a)\n root2 = (-b - discriminant) / (2 * a)\n return root1, root2\n\n# Usage:\nprint(solve_quadratic(1, -3, 2)) # Output: ((2+0j), (1+0j))\nprint(solve_quadratic(1, 2, 5)) # Output: ((-1+2j), (-1-2j))\n" + "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" } ] }, @@ -607,7 +442,6 @@ "description": "Creates a table in an SQLite database with a dynamic schema.", "author": "e3nviction", "tags": [ - "python", "sqlite", "database", "table" @@ -620,10 +454,8 @@ "description": "Inserts a row into a specified SQLite table using a dictionary of fields and values.", "author": "e3nviction", "tags": [ - "python", "sqlite", - "database", - "utility" + "database" ], "contributors": [], "code": "import sqlite3\n\ndef insert_into_table(db_path, table_name, data):\n with sqlite3.connect(db_path) as conn:\n columns = ', '.join(data.keys())\n placeholders = ', '.join(['?'] * len(data))\n sql = f\"INSERT INTO {table_name} ({columns}) VALUES ({placeholders})\"\n conn.execute(sql, tuple(data.values()))\n conn.commit()\n\n# Usage:\ndb_path = 'example.db'\ntable_name = 'users'\ndata = {\n 'name': 'John Doe',\n 'email': 'john@example.com',\n 'age': 30\n}\ninsert_into_table(db_path, table_name, data)\n" @@ -633,10 +465,8 @@ "description": "Fetches data from a specified SQLite table, with options for selecting specific columns and applying a WHERE clause.", "author": "pl44t", "tags": [ - "python", "sqlite", - "database", - "utility" + "database" ], "contributors": [], "code": "import sqlite3\n\ndef query_table(db_path, table_name, columns='*', where_clause=None):\n with sqlite3.connect(db_path) as conn:\n cursor = conn.cursor()\n sql = f\"SELECT {columns} FROM {table_name}\"\n if where_clause:\n sql += f\" WHERE {where_clause}\"\n cursor.execute(sql)\n return cursor.fetchall()\n\n# Usage:\ndb_path = 'example.db'\ntable_name = 'users'\ncolumns = 'id, name, email'\nwhere_clause = 'age > 25'\nresult = query_table(db_path, table_name, columns, where_clause)\nfor row in result:\n print(row)\n\n" @@ -646,10 +476,8 @@ "description": "Updates records in a specified SQLite table, allowing dynamic column updates and an optional WHERE clause.", "author": "pl44t", "tags": [ - "python", "sqlite", - "database", - "utility" + "database" ], "contributors": [], "code": "import sqlite3\n\ndef update_table(db_path, table_name, updates, where_clause=None):\n with sqlite3.connect(db_path) as conn:\n set_clause = ', '.join([f\"{col} = ?\" for col in updates.keys()])\n sql = f\"UPDATE {table_name} SET {set_clause}\"\n if where_clause:\n sql += f\" WHERE {where_clause}\"\n conn.execute(sql, tuple(updates.values()))\n conn.commit()\n\n# Usage:\ndb_path = 'example.db'\ntable_name = 'users'\nupdates = {'name': 'Jane Doe', 'age': 28}\nwhere_clause = \"id = 1\"\nupdate_table(db_path, table_name, updates, where_clause)\n\n" @@ -664,290 +492,221 @@ "description": "Capitalizes the first letter of each word in a string.", "author": "axorax", "tags": [ - "python", "string", - "capitalize", - "utility" + "capitalize" ], "contributors": [], - "code": "def capitalize_words(s):\n return ' '.join(word.capitalize() for word in s.split())\n\n# Usage:\nprint(capitalize_words('hello world')) # Output: 'Hello World'\n" + "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", "tags": [ - "python", "string", "anagram", - "check", - "utility" + "check" ], "contributors": [], - "code": "def is_anagram(s1, s2):\n return sorted(s1) == sorted(s2)\n\n# Usage:\nprint(is_anagram('listen', 'silent')) # Output: True\n" + "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", "tags": [ - "python", "string", - "palindrome", - "utility" + "palindrome" ], "contributors": [], - "code": "def is_palindrome(s):\n s = s.lower().replace(' ', '')\n return s == s[::-1]\n\n# Usage:\nprint(is_palindrome('A man a plan a canal Panama')) # Output: True\n" + "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", "tags": [ - "python", "string", "snake-case", "camel-case", - "convert", - "utility" + "convert" ], "contributors": [], - "code": "def snake_to_camel(s):\n parts = s.split('_')\n return parts[0] + ''.join(word.capitalize() for word in parts[1:])\n\n# Usage:\nprint(snake_to_camel('hello_world')) # Output: 'helloWorld'\n" + "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", "tags": [ - "python", "string", "ascii", - "convert", - "utility" + "convert" ], "contributors": [], - "code": "def string_to_ascii(s):\n return [ord(char) for char in s]\n\n# Usage:\nprint(string_to_ascii('hello')) # Output: [104, 101, 108, 108, 111]\n" + "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", "tags": [ - "python", "string", - "character-frequency", - "utility" + "character-frequency" ], "contributors": [], - "code": "from collections import Counter\n\ndef char_frequency(s):\n return dict(Counter(s))\n\n# Usage:\nprint(char_frequency('hello')) # Output: {'h': 1, 'e': 1, 'l': 2, 'o': 1}\n" + "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", "tags": [ - "python", "string", "vowels", - "count", - "utility" + "count" ], "contributors": [], - "code": "def count_vowels(s):\n vowels = 'aeiou'\n return len([char for char in s.lower() if char in vowels])\n\n# Usage:\nprint(count_vowels('hello')) # Output: 2\n" + "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", "tags": [ - "python", "string", - "word-count", - "utility" + "word-count" ], "contributors": [], - "code": "def count_words(s):\n return len(s.split())\n\n# Usage:\nprint(count_words('The quick brown fox')) # Output: 4\n" + "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", "tags": [ - "python", "string", "substring", - "find", - "utility" + "find" ], "contributors": [], - "code": "def find_substrings(s):\n substrings = []\n for i in range(len(s)):\n for j in range(i + 1, len(s) + 1):\n substrings.append(s[i:j])\n return substrings\n\n# Usage:\nprint(find_substrings('abc')) # Output: ['a', 'ab', 'abc', 'b', 'bc', 'c']\n" + "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", "tags": [ - "python", "string", - "longest-word", - "utility" + "longest-word" ], "contributors": [], - "code": "def find_longest_word(s):\n words = s.split()\n return max(words, key=len) if words else ''\n\n# Usage:\nprint(find_longest_word('The quick brown fox')) # Output: 'quick'\n" + "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", "tags": [ - "python", "string", "unique", - "characters", - "utility" + "characters" + ], + "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", + "tags": [ + "random", + "string" ], "contributors": [], - "code": "def find_unique_chars(s):\n return ''.join(sorted(set(s)))\n\n# Usage:\nprint(find_unique_chars('banana')) # Output: 'abn'\n" + "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", "tags": [ - "python", "string", "duplicates", - "remove", - "utility" + "remove" ], "contributors": [], - "code": "def remove_duplicate_chars(s):\n seen = set()\n return ''.join(char for char in s if not (char in seen or seen.add(char)))\n\n# Usage:\nprint(remove_duplicate_chars('programming')) # Output: 'progamin'\n" + "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", "tags": [ - "python", "string", "punctuation", - "remove", - "utility" + "remove" ], "contributors": [], - "code": "import string\n\ndef remove_punctuation(s):\n return s.translate(str.maketrans('', '', string.punctuation))\n\n# Usage:\nprint(remove_punctuation('Hello, World!')) # Output: 'Hello World'\n" + "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", "tags": [ - "python", "string", "remove", - "characters", - "utility" + "characters" ], "contributors": [], - "code": "def remove_chars(s, chars):\n return ''.join(c for c in s if c not in chars)\n\n# Usage:\nprint(remove_chars('hello world', 'eo')) # Output: 'hll wrld'\n" + "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", "tags": [ - "python", "string", "whitespace", - "remove", - "utility" + "remove" ], "contributors": [], - "code": "def remove_whitespace(s):\n return ''.join(s.split())\n\n# Usage:\nprint(remove_whitespace('hello world')) # Output: 'helloworld'\n" + "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", "tags": [ - "python", "string", - "reverse", - "utility" + "reverse" ], "contributors": [], - "code": "def reverse_string(s):\n return s[::-1]\n\n# Usage:\nprint(reverse_string('hello')) # Output: 'olleh'\n" + "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", "tags": [ - "python", "string", "camel-case", - "split", - "utility" + "split" ], "contributors": [], - "code": "import re\n\ndef split_camel_case(s):\n return ' '.join(re.findall(r'[A-Z][a-z]*|[a-z]+', s))\n\n# Usage:\nprint(split_camel_case('camelCaseString')) # Output: 'camel Case String'\n" + "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", "tags": [ - "python", "string", - "truncate", - "utility" - ], - "contributors": [], - "code": "def truncate_string(s, length):\n return s[:length] + '...' if len(s) > length else s\n\n# Usage:\nprint(truncate_string('This is a long string', 10)) # Output: 'This is a ...'\n" - } - ] - }, - { - "categoryName": "Utilities", - "snippets": [ - { - "title": "Convert Bytes to Human-Readable Format", - "description": "Converts a size in bytes to a human-readable format.", - "author": "axorax", - "tags": [ - "python", - "bytes", - "format", - "utility" - ], - "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:\nprint(bytes_to_human_readable(123456789)) # Output: '117.74 MB'\n" - }, - { - "title": "Generate Random String", - "description": "Generates a random alphanumeric string.", - "author": "dostonnabotov", - "tags": [ - "python", - "random", - "string", - "utility" - ], - "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:\nprint(random_string(10)) # Output: Random 10-character string\n" - }, - { - "title": "Measure Execution Time", - "description": "Measures the execution time of a code block.", - "author": "dostonnabotov", - "tags": [ - "python", - "time", - "execution", - "utility" + "truncate" ], "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)\n" + "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 68d92de1..4a150d77 100644 --- a/public/consolidated/rust.json +++ b/public/consolidated/rust.json @@ -7,10 +7,8 @@ "description": "Prints Hello, World! to the terminal.", "author": "James-Beans", "tags": [ - "rust", "printing", - "hello-world", - "utility" + "hello-world" ], "contributors": [], "code": "fn main() { // Defines the main running function\n println!(\"Hello, World!\"); // Prints Hello, World! to the terminal.\n}\n" @@ -25,25 +23,22 @@ "description": "Finds all files of the specified extension within a given directory.", "author": "Mathys-Gasnier", "tags": [ - "rust", "file", "search" ], "contributors": [], - "code": "fn find_files(directory: &str, file_type: &str) -> std::io::Result> {\n let mut result = vec![];\n\n for entry in std::fs::read_dir(directory)? {\n let dir = entry?;\n let path = dir.path();\n if dir.file_type().is_ok_and(|t| !t.is_file()) &&\n path.extension().is_some_and(|ext| ext != file_type) {\n continue;\n }\n result.push(path)\n }\n\n Ok(result)\n}\n\n// Usage:\nlet files = find_files(\"/path/to/your/directory\", \".pdf\")\n" + "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", "tags": [ - "rust", "file", - "read", - "utility" + "read" ], "contributors": [], - "code": "fn read_lines(file_name: &str) -> std::io::Result>\n Ok(\n std::fs::read_to_string(file_name)?\n .lines()\n .map(String::from)\n .collect()\n )\n}\n\n// Usage:\nlet lines = read_lines(\"path/to/file.txt\").expect(\"Failed to read lines from file\")\n" + "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" } ] }, @@ -55,13 +50,11 @@ "description": "Makes the first letter of a string uppercase.", "author": "Mathys-Gasnier", "tags": [ - "rust", "string", - "capitalize", - "utility" + "capitalize" ], "contributors": [], - "code": "fn capitalized(str: &str) -> String {\n let mut chars = str.chars();\n match chars.next() {\n None => String::new(),\n Some(f) => f.to_uppercase().chain(chars).collect(),\n }\n}\n\n// Usage:\nassert_eq!(capitalized(\"lower_case\"), \"Lower_case\")\n" + "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 498f3665..dd8414b1 100644 --- a/public/consolidated/scss.json +++ b/public/consolidated/scss.json @@ -7,7 +7,6 @@ "description": "Animates the fade-in effect.", "author": "dostonnabotov", "tags": [ - "scss", "animation", "fade", "css" @@ -20,7 +19,6 @@ "description": "Animates content sliding in from the left.", "author": "dostonnabotov", "tags": [ - "scss", "animation", "slide", "css" @@ -38,7 +36,6 @@ "description": "Applies a customizable border-radius.", "author": "dostonnabotov", "tags": [ - "scss", "border", "radius", "css" @@ -51,7 +48,6 @@ "description": "Generates a box shadow with customizable values.", "author": "dostonnabotov", "tags": [ - "scss", "box-shadow", "css", "effects" @@ -69,7 +65,6 @@ "description": "Generates a styled primary button.", "author": "dostonnabotov", "tags": [ - "scss", "button", "primary", "css" @@ -87,7 +82,6 @@ "description": "Ensures that elements maintain a specific aspect ratio.", "author": "dostonnabotov", "tags": [ - "scss", "aspect-ratio", "layout", "css" @@ -100,7 +94,6 @@ "description": "SCSS mixin to change styles for dark themes.", "author": "gihanrangana", "tags": [ - "scss", "css", "mixin", "snippet", @@ -115,7 +108,6 @@ "description": "A mixin to center content using flexbox.", "author": "dostonnabotov", "tags": [ - "scss", "flex", "center", "css" @@ -128,7 +120,6 @@ "description": "Creates a responsive grid container with customizable column counts.", "author": "dostonnabotov", "tags": [ - "scss", "grid", "layout", "css" @@ -146,7 +137,6 @@ "description": "Simplifies importing custom fonts in Sass.", "author": "dostonnabotov", "tags": [ - "sass", "mixin", "fonts", "css" @@ -159,7 +149,6 @@ "description": "A Sass mixin to clamp text to a specific number of lines.", "author": "dostonnabotov", "tags": [ - "sass", "mixin", "typography", "css" @@ -172,7 +161,6 @@ "description": "Adds a gradient color effect to text.", "author": "dostonnabotov", "tags": [ - "sass", "mixin", "gradient", "text", @@ -186,7 +174,6 @@ "description": "Ensures long text is truncated with an ellipsis.", "author": "dostonnabotov", "tags": [ - "sass", "mixin", "text", "css" @@ -204,7 +191,6 @@ "description": "Provides a clearfix utility for floating elements.", "author": "dostonnabotov", "tags": [ - "scss", "clearfix", "utility", "css" @@ -217,7 +203,6 @@ "description": "Generates media queries for responsive design.", "author": "dostonnabotov", "tags": [ - "scss", "responsive", "media-queries", "css" diff --git a/snippets/c/basics/hello-world.md b/snippets/c/basics/hello-world.md index c8122d5a..90b42e7d 100644 --- a/snippets/c/basics/hello-world.md +++ b/snippets/c/basics/hello-world.md @@ -2,7 +2,7 @@ title: Hello, World! description: Prints Hello, World! to the terminal. author: 0xHouss -tags: c,printing,hello-world,utility +tags: printing,hello-world --- ```c diff --git a/snippets/c/mathematical-functions/factorial-function.md b/snippets/c/mathematical-functions/factorial-function.md index 7e8a7b08..7f8dae94 100644 --- a/snippets/c/mathematical-functions/factorial-function.md +++ b/snippets/c/mathematical-functions/factorial-function.md @@ -2,7 +2,7 @@ title: Factorial Function description: Calculates the factorial of a number. author: 0xHouss -tags: c,math,factorial,utility +tags: math,factorial --- ```c @@ -14,4 +14,7 @@ int factorial(int x) { return y; } + +// Usage: +factorial(4); // Returns: 24 ``` diff --git a/snippets/c/mathematical-functions/power-function.md b/snippets/c/mathematical-functions/power-function.md deleted file mode 100644 index c9a81262..00000000 --- a/snippets/c/mathematical-functions/power-function.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: Power Function -description: Calculates the power of a number. -author: 0xHouss -tags: c,math,power,utility ---- - -```c -int power(int x, int n) { - int y = 1; - - for (int i = 0; i < n; i++) - y *= x; - - return y; -} -``` diff --git a/snippets/cpp/basics/hello-world.md b/snippets/cpp/basics/hello-world.md index eadaa386..8036ac6c 100644 --- a/snippets/cpp/basics/hello-world.md +++ b/snippets/cpp/basics/hello-world.md @@ -2,7 +2,7 @@ title: Hello, World! description: Prints Hello, World! to the terminal. author: James-Beans -tags: cpp,printing,hello-world,utility +tags: printing,hello-world --- ```cpp diff --git a/snippets/cpp/data-structure-conversion/vector-to-queue.md b/snippets/cpp/data-structure-conversion/vector-to-queue.md index e31d90fe..a00e0be7 100644 --- a/snippets/cpp/data-structure-conversion/vector-to-queue.md +++ b/snippets/cpp/data-structure-conversion/vector-to-queue.md @@ -1,7 +1,7 @@ --- title: Vector to Queue description: Convert vector into queue quickly -tags: cpp, data structures,queue,vector +tags: data structures,queue,vector author: mrityunjay2003 --- @@ -13,4 +13,7 @@ author: mrityunjay2003 std::queue vectorToQueue(const std::vector& v) { return std::queue(std::deque(v.begin(), v.end())); } -``` \ No newline at end of file + +std::vector vec = { 1, 2, 3, 4, 5 }; +vectorToQueue(&vec); // Returns: std::queue { 1, 2, 3, 4, 5 } +``` diff --git a/snippets/cpp/math-and-numbers/check-prime.md b/snippets/cpp/math-and-numbers/check-prime-number.md similarity index 71% rename from snippets/cpp/math-and-numbers/check-prime.md rename to snippets/cpp/math-and-numbers/check-prime-number.md index cb4a2a8c..e2059c25 100644 --- a/snippets/cpp/math-and-numbers/check-prime.md +++ b/snippets/cpp/math-and-numbers/check-prime-number.md @@ -1,7 +1,7 @@ --- title: Check Prime Number description: Check if an integer is a prime number -tags: cpp, number, prime +tags: number, prime author: MihneaMoso --- @@ -16,11 +16,6 @@ bool is_prime(int n) { return true; } -// Usage -#include - -int main() { - std::cout << is_prime(29) << std::endl; // Output: 1 - return 0; -} +// Usage: +is_prime(29); // Returns: true ``` diff --git a/snippets/cpp/string-manipulation/reverse-string.md b/snippets/cpp/string-manipulation/reverse-string.md index de209c88..615189b1 100644 --- a/snippets/cpp/string-manipulation/reverse-string.md +++ b/snippets/cpp/string-manipulation/reverse-string.md @@ -2,7 +2,7 @@ title: Reverse String description: Reverses the characters in a string. author: Vaibhav-kesarwani -tags: cpp,array,reverse,utility +tags: array,reverse --- ```cpp @@ -14,4 +14,6 @@ std::string reverseString(const std::string& input) { std::reverse(reversed.begin(), reversed.end()); return reversed; } + +reverseString("quicksnip"); // Returns: "pinskciuq" ``` diff --git a/snippets/cpp/string-manipulation/split-string.md b/snippets/cpp/string-manipulation/split-string.md index f903a2b2..362b719c 100644 --- a/snippets/cpp/string-manipulation/split-string.md +++ b/snippets/cpp/string-manipulation/split-string.md @@ -2,7 +2,7 @@ title: Split String description: Splits a string by a delimiter author: saminjay -tags: cpp,string,split,utility +tags: string,split --- ```cpp @@ -20,4 +20,7 @@ std::vector split_string(std::string str, std::string delim) { } return splits; } + +// Usage: +split_string("quick_-snip", "_-"); // Returns: std::vector { "quick", "snip" } ``` diff --git a/snippets/csharp/basics/hello-world.md b/snippets/csharp/basics/hello-world.md index 3bca885e..d13463c6 100644 --- a/snippets/csharp/basics/hello-world.md +++ b/snippets/csharp/basics/hello-world.md @@ -2,13 +2,13 @@ title: Hello, World! description: Prints Hello, World! to the terminal. author: chaitanya-jvnm -tags: c#,printing,hello-world,utility +tags: printing,hello-world --- -```c# +```csharp public class Program { public static void Main(string[] args) { System.Console.WriteLine("Hello, World!"); } } -``` \ No newline at end of file +``` diff --git a/snippets/csharp/guid-utilities/generate-guid.md b/snippets/csharp/guid-utilities/generate-guid.md index eaa59a95..43682edf 100644 --- a/snippets/csharp/guid-utilities/generate-guid.md +++ b/snippets/csharp/guid-utilities/generate-guid.md @@ -2,11 +2,14 @@ title: Generate GUID description: Generates a new GUID author: chaitanya-jvnm -tags: c#,guid,generate,utility +tags: guid,generate --- -```c# +```csharp public static string GenerateGuid() { return Guid.NewGuid().ToString(); } -``` \ No newline at end of file + +// Usage: +GenerateGuid(); // Returns: 1c4c38d8-64e4-431b-884a-c6eec2ab02cd (Uuid is random) +``` diff --git a/snippets/csharp/guid-utilities/validate-guid.md b/snippets/csharp/guid-utilities/validate-guid.md index 579fc726..2989dfb7 100644 --- a/snippets/csharp/guid-utilities/validate-guid.md +++ b/snippets/csharp/guid-utilities/validate-guid.md @@ -2,11 +2,15 @@ title: Validate GUID description: Checks if a string is a valid GUID. author: chaitanya-jvnm -tags: c#,guid,validate,utility +tags: guid,validate --- -```c# +```csharp public static bool IsGuid(string str) { return Guid.TryParse(str, out _); } + +// Usage: +IsGuid("1c4c38d8-64e4-431b-884a-c6eec2ab02cd"); // Returns: true +IsGuid("quicksnip"); // Returns: false ``` \ No newline at end of file diff --git a/snippets/csharp/jwt-utilities/decode-jwt.md b/snippets/csharp/jwt-utilities/decode-jwt.md index 609410e7..6c4c9e01 100644 --- a/snippets/csharp/jwt-utilities/decode-jwt.md +++ b/snippets/csharp/jwt-utilities/decode-jwt.md @@ -2,21 +2,15 @@ title: Decode JWT description: Decodes a JWT. author: chaitanya-jvnm -tags: c#,jwt,decode,utility +tags: jwt,decode --- -```c# -/// -/// Decodes the JWT -/// +```csharp public static string DecodeJwt(string token) { return new JwtSecurityTokenHandler().ReadJwtToken(token).ToString(); } -//Example +// Usage: string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"; - -string decodedJwt = DecodeJwt(token); - -Console.WriteLine(decodedJwt); //Prints {"alg":"HS256","typ":"JWT"}.{"sub":"1234567890","name":"John Doe","iat":1516239022} -``` \ No newline at end of file +DecodeJwt(token); // Returns: "{\"alg\":\"HS256\",\"typ\":\"JWT\"}.{\"sub\":\"1234567890\",\"name\":\"John Doe\",\"iat\":1516239022}" +``` diff --git a/snippets/csharp/jwt-utilities/generate-jwt.md b/snippets/csharp/jwt-utilities/generate-jwt.md deleted file mode 100644 index 1074ce7b..00000000 --- a/snippets/csharp/jwt-utilities/generate-jwt.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -title: Generate JWT -description: Generates a new JWT. -author: chaitanya-jvnm -tags: c#,jwt,generate,utility ---- - -```c# -public static string GenerateJwt(string secret, string issuer, string audience, int expirationMinutes) { - var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret)); - var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); - var token = new JwtSecurityToken(issuer, audience, null, expires: DateTime.UtcNow.AddMinutes(expirationMinutes), signingCredentials: credentials); - return new JwtSecurityTokenHandler().WriteToken(token); -} -``` \ No newline at end of file diff --git a/snippets/csharp/jwt-utilities/validate-jwt.md b/snippets/csharp/jwt-utilities/validate-jwt.md index 855a6c73..48765e7d 100644 --- a/snippets/csharp/jwt-utilities/validate-jwt.md +++ b/snippets/csharp/jwt-utilities/validate-jwt.md @@ -2,10 +2,10 @@ title: Validate JWT description: Validates a JWT. author: chaitanya-jvnm -tags: c#,jwt,validate,utility +tags: jwt,validate --- -```c# +```csharp public static bool ValidateJwt(string token, string secret) { var tokenHandler = new JwtSecurityTokenHandler(); var validationParameters = new TokenValidationParameters { @@ -23,13 +23,11 @@ public static bool ValidateJwt(string token, string secret) { } } -//Example +// Usage: string JWT = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"; - string correctSecret = "your-256-bit-secret"; string wrongSecret = "this-is-not-the-right-secret"; -Console.WriteLine(ValidateJwt(JWT, correctSecret)) // returns True -Console.WriteLine(ValidateJwt(JWT, wrongSecret)) // returns False - +ValidateJwt(JWT, correctSecret); // Returns: true +ValidateJwt(JWT, wrongSecret); // Returns: false ``` \ No newline at end of file diff --git a/snippets/csharp/list-utilities/swap-items-at-index.md b/snippets/csharp/list-utilities/swap-items-at-index.md index 4e8113a4..5cf47d9f 100644 --- a/snippets/csharp/list-utilities/swap-items-at-index.md +++ b/snippets/csharp/list-utilities/swap-items-at-index.md @@ -1,15 +1,11 @@ --- -title: Swap two items at determined indexes +title: Swap items at index description: Swaps two items at determined indexes author: omegaleo -tags: csharp,c#,list,utility +tags: list,swapping --- ```csharp -/// -/// Swaps the position of 2 elements inside of a List -/// -/// List with swapped elements public static IList Swap(this IList list, int indexA, int indexB) { (list[indexA], list[indexB]) = (list[indexB], list[indexA]); @@ -18,11 +14,5 @@ public static IList Swap(this IList list, int indexA, int indexB) var list = new List() {"Test", "Test2"}; -Console.WriteLine(list[0]); // Outputs: Test -Console.WriteLine(list[1]); // Outputs: Test2 - -list = list.Swap(0, 1).ToList(); - -Console.WriteLine(list[0]); // Outputs: Test2 -Console.WriteLine(list[1]); // Outputs: Test +list.Swap(0, 1); // Swaps "Test" and "Test2" in place ``` diff --git a/snippets/csharp/string-utilities/capitalize-first-letter.md b/snippets/csharp/string-utilities/capitalize-first-letter.md index bad45334..c047398e 100644 --- a/snippets/csharp/string-utilities/capitalize-first-letter.md +++ b/snippets/csharp/string-utilities/capitalize-first-letter.md @@ -2,19 +2,14 @@ title: Capitalize first letter description: Makes the first letter of a string uppercase. author: chaitanya-jvnm -tags: c#,string,capitalize,utility +tags: string,capitalize --- -```c# -/// -/// Capitalize the first character of the string -/// +```csharp public static string Capitalize(this string str) { return str.Substring(0, 1).ToUpper() + str.Substring(1); } -//Example -string example = "hello"; -string captializedExample = example.Capitalize(); -Console.WriteLine(captializedExample); // prints "Hello" -``` \ No newline at end of file +// Usage: +"quicksnip".Capitalize(); // Returns: "Quicksnip" +``` diff --git a/snippets/csharp/string-utilities/truncate-string.md b/snippets/csharp/string-utilities/truncate-string.md index 5213bed4..6acc4032 100644 --- a/snippets/csharp/string-utilities/truncate-string.md +++ b/snippets/csharp/string-utilities/truncate-string.md @@ -1,21 +1,16 @@ --- -title: Truncate a String +title: Truncate String description: Cut off a string once it reaches a determined amount of characters and add '...' to the end of the string author: omegaleo -tags: csharp,c#,list,utility +tags: string,truncate --- ```csharp -/// -/// Cut off a string once it reaches a amount of characters and add '...' to the end of the string -/// public static string Truncate(this string value, int maxChars) { return value.Length <= maxChars ? value : value.Substring(0, maxChars) + "..."; } -var str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam tristique rhoncus bibendum. Vivamus laoreet tortor vel neque lacinia, nec rhoncus ligula pellentesque. Nullam eu ornare nibh. Donec tincidunt viverra nulla."; - -Console.WriteLine(str); // Outputs the full string -Console.WriteLine(str.Truncate(5)); // Outputs Lorem... +// Usage: +"Quicksnip".Truncate(5); // Returns: "Quick..." ``` diff --git a/snippets/css/buttons/3d-button-effect.md b/snippets/css/buttons/3d-button-effect.md index 3498993a..0c4de95c 100644 --- a/snippets/css/buttons/3d-button-effect.md +++ b/snippets/css/buttons/3d-button-effect.md @@ -2,7 +2,7 @@ title: 3D Button Effect description: Adds a 3D effect to a button when clicked. author: dostonnabotov -tags: css,button,3D,effect +tags: button,3D,effect --- ```css diff --git a/snippets/css/buttons/button-hover-effect.md b/snippets/css/buttons/button-hover-effect.md index 22f4c2d4..fe1e3b9f 100644 --- a/snippets/css/buttons/button-hover-effect.md +++ b/snippets/css/buttons/button-hover-effect.md @@ -2,7 +2,7 @@ title: Button Hover Effect description: Creates a hover effect with a color transition. author: dostonnabotov -tags: css,button,hover,transition +tags: button,hover,transition --- ```css diff --git a/snippets/css/buttons/macos-button.md b/snippets/css/buttons/macos-button.md index 2da30207..2040baa8 100644 --- a/snippets/css/buttons/macos-button.md +++ b/snippets/css/buttons/macos-button.md @@ -2,7 +2,7 @@ title: MacOS Button description: A macOS-like button style, with hover and shading effects. author: e3nviction -tags: css,button,macos,hover,transition +tags: button,macos,hover,transition --- ```css diff --git a/snippets/css/effects/blur-background.md b/snippets/css/effects/blur-background.md index 2891e820..0c03820d 100644 --- a/snippets/css/effects/blur-background.md +++ b/snippets/css/effects/blur-background.md @@ -2,7 +2,7 @@ title: Blur Background description: Applies a blur effect to the background of an element. author: dostonnabotov -tags: css,blur,background,effects +tags: blur,background,effects --- ```css diff --git a/snippets/css/effects/hover-glow-effect.md b/snippets/css/effects/hover-glow-effect.md index 2c2ec862..e2d87219 100644 --- a/snippets/css/effects/hover-glow-effect.md +++ b/snippets/css/effects/hover-glow-effect.md @@ -2,7 +2,7 @@ title: Hover Glow Effect description: Adds a glowing effect on hover. author: dostonnabotov -tags: css,hover,glow,effects +tags: hover,glow,effects --- ```css diff --git a/snippets/css/effects/hover-to-reveal-color.md b/snippets/css/effects/hover-to-reveal-color.md index 0a355e5a..c284ea3a 100644 --- a/snippets/css/effects/hover-to-reveal-color.md +++ b/snippets/css/effects/hover-to-reveal-color.md @@ -2,7 +2,7 @@ title: Hover to Reveal Color description: A card with an image that transitions from grayscale to full color on hover. author: Haider-Mukhtar -tags: css,hover,image,effects +tags: hover,image,effects --- ```css diff --git a/snippets/css/layouts/css-reset.md b/snippets/css/layouts/css-reset.md index 9195135b..69b7cb37 100644 --- a/snippets/css/layouts/css-reset.md +++ b/snippets/css/layouts/css-reset.md @@ -2,7 +2,7 @@ title: CSS Reset description: Resets some default browser styles, ensuring consistency across browsers. author: AmeerMoustafa -tags: css,reset,browser,layout +tags: reset,browser,layout --- ```css diff --git a/snippets/css/layouts/equal-width-columns.md b/snippets/css/layouts/equal-width-columns.md index 69b4128d..0e383a62 100644 --- a/snippets/css/layouts/equal-width-columns.md +++ b/snippets/css/layouts/equal-width-columns.md @@ -2,7 +2,7 @@ title: Equal-Width Columns description: Creates columns with equal widths using flexbox. author: dostonnabotov -tags: css,flexbox,columns,layout +tags: flexbox,columns,layout --- ```css diff --git a/snippets/css/layouts/grid-layout.md b/snippets/css/layouts/grid-layout.md index 04ebd0e9..cd4425b5 100644 --- a/snippets/css/layouts/grid-layout.md +++ b/snippets/css/layouts/grid-layout.md @@ -2,7 +2,7 @@ title: Grid layout description: Equal sized items in a responsive grid author: xshubhamg -tags: css,layout,grid +tags: layout,grid --- ```css diff --git a/snippets/css/layouts/responsive-design.md b/snippets/css/layouts/responsive-design.md index 6d983451..95d5f028 100644 --- a/snippets/css/layouts/responsive-design.md +++ b/snippets/css/layouts/responsive-design.md @@ -2,7 +2,7 @@ title: Responsive Design description: The different responsive breakpoints. author: kruimol -tags: css,responsive +tags: responsive,media queries --- ```css diff --git a/snippets/css/layouts/sticky-footer.md b/snippets/css/layouts/sticky-footer.md index 8c8c7f09..9d1adc80 100644 --- a/snippets/css/layouts/sticky-footer.md +++ b/snippets/css/layouts/sticky-footer.md @@ -2,7 +2,7 @@ title: Sticky Footer description: Ensures the footer always stays at the bottom of the page. author: dostonnabotov -tags: css,layout,footer,sticky +tags: layout,footer,sticky --- ```css diff --git a/snippets/css/typography/letter-spacing.md b/snippets/css/typography/letter-spacing.md index 4871b714..73ad2cf5 100644 --- a/snippets/css/typography/letter-spacing.md +++ b/snippets/css/typography/letter-spacing.md @@ -2,7 +2,7 @@ title: Letter Spacing description: Adds space between letters for better readability. author: dostonnabotov -tags: css,typography,spacing +tags: typography,spacing --- ```css diff --git a/snippets/css/typography/responsive-font-sizing.md b/snippets/css/typography/responsive-font-sizing.md index 7eb87f2c..91f961e1 100644 --- a/snippets/css/typography/responsive-font-sizing.md +++ b/snippets/css/typography/responsive-font-sizing.md @@ -2,7 +2,7 @@ title: Responsive Font Sizing description: Adjusts font size based on viewport width. author: dostonnabotov -tags: css,font,responsive,typography +tags: font,responsive,typography --- ```css diff --git a/snippets/haskell/array-manipulation/binary-search.md b/snippets/haskell/array-manipulation/binary-search.md index 24be7973..0e6a2e9f 100644 --- a/snippets/haskell/array-manipulation/binary-search.md +++ b/snippets/haskell/array-manipulation/binary-search.md @@ -2,7 +2,7 @@ title: Binary Search description: Searches for an element in a sorted array using binary search. author: ACR1209 -tags: haskell,array,binary-search,search +tags: array,binary-search,search --- ```hs @@ -19,6 +19,7 @@ binarySearch target xs = go 0 (length xs - 1) mid = (low + high) `div` 2 midElem = xs !! mid +-- Usage: main :: IO () main = do let array = [1, 2, 3, 4, 5] diff --git a/snippets/haskell/array-manipulation/chunk-array.md b/snippets/haskell/array-manipulation/chunk-array.md index 6d85256e..006727fa 100644 --- a/snippets/haskell/array-manipulation/chunk-array.md +++ b/snippets/haskell/array-manipulation/chunk-array.md @@ -2,7 +2,7 @@ title: Chunk Array description: Splits an array into chunks of a specified size. author: ACR1209 -tags: haskell,array,chunk,utility +tags: array,chunk,utility --- ```hs @@ -10,6 +10,7 @@ chunkArray :: Int -> [a] -> [[a]] chunkArray _ [] = [] chunkArray n xs = take n xs : chunkArray n (drop n xs) +-- Usage: main :: IO () main = do let array = [1, 2, 3, 4, 5, 6] diff --git a/snippets/haskell/array-manipulation/flatten-array.md b/snippets/haskell/array-manipulation/flatten-array.md deleted file mode 100644 index 9be1cb27..00000000 --- a/snippets/haskell/array-manipulation/flatten-array.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: Flatten Array -description: Flattens a multi-dimensional array. -author: ACR1209 -tags: haskell,array,flatten,utility ---- - -```hs -flatten :: [[a]] -> [a] -flatten = concat - -main :: IO () -main = do - let array = [[1, 2], [2], [3], [4]] - print $ flatten array -- Output: [1, 2, 2, 3, 4] -``` diff --git a/snippets/haskell/array-manipulation/matrix-transpose.md b/snippets/haskell/array-manipulation/matrix-transpose.md index 8bec051d..38d81d37 100644 --- a/snippets/haskell/array-manipulation/matrix-transpose.md +++ b/snippets/haskell/array-manipulation/matrix-transpose.md @@ -2,7 +2,7 @@ title: Matrix Transpose description: Transposes a 2D matrix. author: ACR1209 -tags: haskell,array,matrix,transpose +tags: array,matrix,transpose --- ```hs @@ -11,6 +11,7 @@ transposeMatrix [] = [] transposeMatrix ([]:_) = [] transposeMatrix xs = map head xs : transposeMatrix (map tail xs) +-- Usage: main :: IO () main = do let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] diff --git a/snippets/haskell/array-manipulation/remove-duplicates.md b/snippets/haskell/array-manipulation/remove-duplicates.md deleted file mode 100644 index 3af42fa8..00000000 --- a/snippets/haskell/array-manipulation/remove-duplicates.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: Remove duplicates -description: Removes duplicate values from an array. -author: ACR1209 -tags: haskell,array,deduplicate,utility ---- - -```hs -import Data.List (nub) - -removeDuplicates :: Eq a => [a] -> [a] -removeDuplicates = nub - --- Usage -main :: IO () -main = do - let array = [1, 2, 2, 3, 4, 4, 5] - print $ removeDuplicates array -- Output: [1, 2, 3, 4, 5] -``` diff --git a/snippets/haskell/basics/hello-world.md b/snippets/haskell/basics/hello-world.md index a1da8874..044d5671 100644 --- a/snippets/haskell/basics/hello-world.md +++ b/snippets/haskell/basics/hello-world.md @@ -2,7 +2,7 @@ title: Hello, World! description: Prints Hello, World! to the terminal. author: ACR1209 -tags: haskell,printing,hello-world,utility +tags: printing,hello-world,utility --- ```haskell diff --git a/snippets/haskell/file-handling/append-to-file.md b/snippets/haskell/file-handling/append-to-file.md deleted file mode 100644 index ecdef843..00000000 --- a/snippets/haskell/file-handling/append-to-file.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: Append to File -description: Appends text to an existing file. -author: ACR1209 -tags: haskell,file,append,utilty ---- - -```hs -import System.IO - -appendToFile :: FilePath -> String -> IO () -appendToFile = appendFile - -main :: IO () -main = do - let file = "example.txt" - let text = "This will be appended to the file.\n" - appendToFile file text -``` \ No newline at end of file diff --git a/snippets/haskell/file-handling/file-exists.md b/snippets/haskell/file-handling/file-exists.md deleted file mode 100644 index 247761db..00000000 --- a/snippets/haskell/file-handling/file-exists.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: Check if File Exists -description: Checks if a file exists at a given path. -author: ACR1209 -tags: haskell,file,exists ---- - -```hs -import System.Directory (doesFileExist) - -checkFileExists :: FilePath -> IO Bool -checkFileExists = doesFileExist - -main :: IO () -main = do - let file = "example.txt" - exists <- checkFileExists file - if exists then putStrLn "File exists." else putStrLn "File does not exist." -``` \ No newline at end of file diff --git a/snippets/haskell/file-handling/find-files-with-extension-in-directory.md b/snippets/haskell/file-handling/find-files-in-directory-by-type.md similarity index 92% rename from snippets/haskell/file-handling/find-files-with-extension-in-directory.md rename to snippets/haskell/file-handling/find-files-in-directory-by-type.md index e9f4f9ce..58a0dab4 100644 --- a/snippets/haskell/file-handling/find-files-with-extension-in-directory.md +++ b/snippets/haskell/file-handling/find-files-in-directory-by-type.md @@ -2,7 +2,7 @@ title: Find Files in Directory by Type description: Finds all files in a directory with a specific extension. author: ACR1209 -tags: haskell,file,search,extension,filesystem +tags: file,search,extension,filesystem --- ```hs @@ -14,6 +14,7 @@ findFilesByExtension dir ext = do files <- listDirectory dir return $ filter (\f -> takeExtension f == ext) files +-- Usage: main :: IO () main = do let directory = "." diff --git a/snippets/haskell/file-handling/read-chunks.md b/snippets/haskell/file-handling/read-file-in-chunks.md similarity index 94% rename from snippets/haskell/file-handling/read-chunks.md rename to snippets/haskell/file-handling/read-file-in-chunks.md index d6844bd6..ca5c3868 100644 --- a/snippets/haskell/file-handling/read-chunks.md +++ b/snippets/haskell/file-handling/read-file-in-chunks.md @@ -2,7 +2,7 @@ title: Read File in Chunks description: Reads a file in chunks grouped by lines. author: ACR1209 -tags: haskell,file,read,chunks,utility +tags: file,read,chunks,utility --- ```hs @@ -19,6 +19,7 @@ readFileInChunks filePath chunkSize = do go [] = [] go xs = take chunkSize xs : go (drop chunkSize xs) +-- Usage: main :: IO () main = do let file = "example.txt" diff --git a/snippets/haskell/file-handling/write-to-file.md b/snippets/haskell/file-handling/write-to-file.md deleted file mode 100644 index 33fed448..00000000 --- a/snippets/haskell/file-handling/write-to-file.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: Write to File -description: Writes text to a file, overwriting any existing content. -author: ACR1209 -tags: haskell,file,write ---- - -```hs -import System.IO (writeFile) - -writeToFile :: FilePath -> String -> IO () -writeToFile = writeFile - -main :: IO () -main = do - let file = "example.txt" - let content = "This is new content." - writeToFile file content -``` \ No newline at end of file diff --git a/snippets/haskell/monads/either-monad.md b/snippets/haskell/monads/either-monad-for-error-handling.md similarity index 91% rename from snippets/haskell/monads/either-monad.md rename to snippets/haskell/monads/either-monad-for-error-handling.md index 883a4c50..bf4c107d 100644 --- a/snippets/haskell/monads/either-monad.md +++ b/snippets/haskell/monads/either-monad-for-error-handling.md @@ -2,7 +2,7 @@ title: Either Monad for Error Handling description: Using the Either monad to handle errors in a computation. author: ACR1209 -tags: haskell, monads, either, error handling +tags: monads, either, error handling --- ```hs @@ -10,6 +10,7 @@ safeDiv :: Int -> Int -> Either String Int safeDiv _ 0 = Left "Division by zero error" safeDiv x y = Right (x `div` y) +-- Usage: main :: IO () main = do let result = do diff --git a/snippets/haskell/monads/maybe-monad.md b/snippets/haskell/monads/maybe-monad.md index 4c33f856..b452f70d 100644 --- a/snippets/haskell/monads/maybe-monad.md +++ b/snippets/haskell/monads/maybe-monad.md @@ -2,7 +2,7 @@ title: Maybe Monad description: Using the Maybe monad to handle computations that might fail. author: ACR1209 -tags: haskell, monads, maybe +tags: monads, maybe --- ```hs @@ -10,6 +10,7 @@ safeDiv :: Int -> Int -> Maybe Int safeDiv _ 0 = Nothing safeDiv x y = Just (x `div` y) +-- Usage: main :: IO () main = do let result = do diff --git a/snippets/haskell/monads/state-monad.md b/snippets/haskell/monads/state-monad.md index a723bb55..baa09f14 100644 --- a/snippets/haskell/monads/state-monad.md +++ b/snippets/haskell/monads/state-monad.md @@ -2,7 +2,7 @@ title: State Monad description: Managing mutable state using the State monad. author: ACR1209 -tags: haskell, monads, state, state-management +tags: monads, state, state-management --- ```hs @@ -14,6 +14,7 @@ increment = do put (count + 1) return count +-- Usage: main :: IO () main = do let (res1, intermediateState) = runState increment 0 diff --git a/snippets/haskell/monads/writer-monad.md b/snippets/haskell/monads/writer-monad.md index f1b3ac97..089e2b17 100644 --- a/snippets/haskell/monads/writer-monad.md +++ b/snippets/haskell/monads/writer-monad.md @@ -2,7 +2,7 @@ title: Writer Monad description: Using the Writer monad to accumulate logs or other outputs alongside a computation. author: ACR1209 -tags: haskell, monads, writer, logs +tags: monads, writer, logs --- ```hs @@ -13,6 +13,7 @@ addAndLog x y = do tell ["Adding " ++ show x ++ " and " ++ show y] return (x + y) +-- Usage: main :: IO () main = do let (result, logs) = runWriter $ do diff --git a/snippets/haskell/string-manipulation/camelcase-to-snakecase.md b/snippets/haskell/string-manipulation/camelcase-to-snake-case.md similarity index 81% rename from snippets/haskell/string-manipulation/camelcase-to-snakecase.md rename to snippets/haskell/string-manipulation/camelcase-to-snake-case.md index c3c09a14..11c0fb34 100644 --- a/snippets/haskell/string-manipulation/camelcase-to-snakecase.md +++ b/snippets/haskell/string-manipulation/camelcase-to-snake-case.md @@ -1,8 +1,8 @@ --- -title: Transform Camel Case to Snake Case +title: CamelCase to snake_case description: Converts a Camel Case string to Snake case. author: ACR1209 -tags: haskell,string,convert,camel-case,snake-case,utility +tags: string,convert,camel-case,snake-case,utility --- ```hs @@ -14,6 +14,7 @@ camelToSnake (x:xs) | isUpper x = '_' : toLower x : camelToSnake xs | otherwise = x : camelToSnake xs +-- Usage: main :: IO () main = do let camelCase = "camelCaseToSnakeCase" diff --git a/snippets/haskell/string-manipulation/capitalize-words.md b/snippets/haskell/string-manipulation/capitalize-words.md index dbf75c61..613bf1d5 100644 --- a/snippets/haskell/string-manipulation/capitalize-words.md +++ b/snippets/haskell/string-manipulation/capitalize-words.md @@ -2,7 +2,7 @@ title: Capitalize Words description: Capitalizes the first letter of each word in a string. author: ACR1209 -tags: haskell,string,capitalize,words +tags: string,capitalize,words --- ```hs @@ -14,6 +14,7 @@ capitalizeWords = unwords . map capitalize . words capitalize [] = [] capitalize (x:xs) = toUpper x : xs +-- Usage: main :: IO () main = do let sentence = "haskell is awesome" diff --git a/snippets/haskell/string-manipulation/count-word-ocurrences.md b/snippets/haskell/string-manipulation/count-word-occurrences-in-string.md similarity index 91% rename from snippets/haskell/string-manipulation/count-word-ocurrences.md rename to snippets/haskell/string-manipulation/count-word-occurrences-in-string.md index 6c677631..eacf7249 100644 --- a/snippets/haskell/string-manipulation/count-word-ocurrences.md +++ b/snippets/haskell/string-manipulation/count-word-occurrences-in-string.md @@ -2,7 +2,7 @@ title: Count Word Occurrences in String description: Counts the occurrences of each word in a given string. author: ACR1209 -tags: haskell,string,occurrences,word-count +tags: string,occurrences,word-count --- ```hs @@ -11,6 +11,7 @@ import Data.List (group, sort) countWordOccurrences :: String -> [(String, Int)] countWordOccurrences = map (\(w:ws) -> (w, length (w:ws))) . group . sort . words +-- Usage: main :: IO () main = do let text = "haskell is awesome and haskell is fun" diff --git a/snippets/haskell/string-manipulation/remove-punctuation.md b/snippets/haskell/string-manipulation/remove-punctuation.md index 64bc18be..b2e3d4ff 100644 --- a/snippets/haskell/string-manipulation/remove-punctuation.md +++ b/snippets/haskell/string-manipulation/remove-punctuation.md @@ -2,7 +2,7 @@ title: Remove Punctuation description: Removes all punctuation from a given string. author: ACR1209 -tags: haskell,string,punctuation,remove +tags: string,punctuation,remove --- ```hs @@ -11,6 +11,7 @@ import Data.Char (isPunctuation) removePunctuation :: String -> String removePunctuation = filter (not . isPunctuation) +-- Usage: main :: IO () main = do let text = "Hello, Haskell! How's it going?" diff --git a/snippets/haskell/string-manipulation/snakecase-to-camelcase.md b/snippets/haskell/string-manipulation/snake-case-to-camelcase.md similarity index 79% rename from snippets/haskell/string-manipulation/snakecase-to-camelcase.md rename to snippets/haskell/string-manipulation/snake-case-to-camelcase.md index 14664088..6086ddf9 100644 --- a/snippets/haskell/string-manipulation/snakecase-to-camelcase.md +++ b/snippets/haskell/string-manipulation/snake-case-to-camelcase.md @@ -1,8 +1,8 @@ --- -title: Transform from Snake Case to Camel Case +title: Snake_Case to CamelCase description: Converts a Snake Case string to Camel Case. author: ACR1209 -tags: haskell,string,convert,snake-case,camel-case,utilty +tags: string,convert,snake-case,camel-case,utilty --- ```hs @@ -13,6 +13,7 @@ snakeToCamel [] = [] snakeToCamel ('_':x:xs) = toUpper x : snakeToCamel xs snakeToCamel (x:xs) = x : snakeToCamel xs +-- Usage: main :: IO () main = do let snakeCase = "snake_case_to_camel_case" diff --git a/snippets/haskell/string-manipulation/truncate-string.md b/snippets/haskell/string-manipulation/truncate-string.md index fe687d3c..bf4aebff 100644 --- a/snippets/haskell/string-manipulation/truncate-string.md +++ b/snippets/haskell/string-manipulation/truncate-string.md @@ -1,8 +1,8 @@ --- -title: Truncate Strings +title: Truncate String description: Truncates a string to a specified length, optionally adding an ellipsis. author: ACR1209 -tags: haskell,string,truncate,utility +tags: string,truncate,utility --- ```hs @@ -11,6 +11,7 @@ truncateString maxLength str | length str <= maxLength = str | otherwise = take (maxLength - 3) str ++ "..." +-- Usage: main :: IO () main = do let longString = "Haskell is a powerful functional programming language." diff --git a/snippets/html/basic-layouts/grid-layout-with-navigation.md b/snippets/html/basic-layouts/grid-layout-with-navigation.md index da6c47cf..fc23914e 100644 --- a/snippets/html/basic-layouts/grid-layout-with-navigation.md +++ b/snippets/html/basic-layouts/grid-layout-with-navigation.md @@ -2,7 +2,7 @@ title: Grid Layout with Navigation description: Full-height grid layout with header navigation using nesting syntax. author: GreenMan36 -tags: html,css,layout,sticky,grid,full-height +tags: css,layout,sticky,grid,full-height --- ```html diff --git a/snippets/html/basic-layouts/sticky-header-footer-layout.md b/snippets/html/basic-layouts/sticky-header-footer-layout.md index 26c065eb..56aae47f 100644 --- a/snippets/html/basic-layouts/sticky-header-footer-layout.md +++ b/snippets/html/basic-layouts/sticky-header-footer-layout.md @@ -2,7 +2,7 @@ title: Sticky Header-Footer Layout description: Full-height layout with sticky header and footer, using modern viewport units and flexbox. author: GreenMan36 -tags: html,css,layout,sticky,flexbox,viewport +tags: css,layout,sticky,flexbox,viewport --- ```html diff --git a/snippets/javascript/array-manipulation/flatten-array.md b/snippets/javascript/array-manipulation/flatten-array.md deleted file mode 100644 index 7d2546d8..00000000 --- a/snippets/javascript/array-manipulation/flatten-array.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Flatten Array -description: Flattens a multi-dimensional array. -author: dostonnabotov -tags: javascript,array,flatten,utility ---- - -```js -const flattenArray = (arr) => arr.flat(Infinity); - -// Usage: -const nestedArray = [1, [2, [3, [4]]]]; -console.log(flattenArray(nestedArray)); // Output: [1, 2, 3, 4] -``` diff --git a/snippets/javascript/array-manipulation/partition-an-array-into-two.md b/snippets/javascript/array-manipulation/partition-array.md similarity index 75% rename from snippets/javascript/array-manipulation/partition-an-array-into-two.md rename to snippets/javascript/array-manipulation/partition-array.md index cc26fd06..92c9bb3c 100644 --- a/snippets/javascript/array-manipulation/partition-an-array-into-two.md +++ b/snippets/javascript/array-manipulation/partition-array.md @@ -2,7 +2,7 @@ title: Partition Array description: Splits an array into two arrays based on a callback function. author: Swaraj-Singh-30 -tags: javascript,array,partition,reduce,utility +tags: array,partition,reduce --- ```js @@ -15,5 +15,5 @@ const partition = (arr, callback) => // Usage: const numbers = [1, 2, 3, 4, 5, 6]; const isEven = (n) => n % 2 === 0; -console.log(partition(numbers, isEven)); // Output: [[2, 4, 6], [1, 3, 5]] +partition(numbers, isEven); // Returns: [[2, 4, 6], [1, 3, 5]] ``` \ No newline at end of file diff --git a/snippets/javascript/array-manipulation/remove-duplicates.md b/snippets/javascript/array-manipulation/remove-duplicates.md index 134bfc89..4f04ac93 100644 --- a/snippets/javascript/array-manipulation/remove-duplicates.md +++ b/snippets/javascript/array-manipulation/remove-duplicates.md @@ -2,7 +2,7 @@ title: Remove Duplicates description: Removes duplicate values from an array. author: dostonnabotov -tags: javascript,array,deduplicate,utility +tags: array,deduplicate --- ```js @@ -10,5 +10,5 @@ const removeDuplicates = (arr) => [...new Set(arr)]; // Usage: const numbers = [1, 2, 2, 3, 4, 4, 5]; -console.log(removeDuplicates(numbers)); // Output: [1, 2, 3, 4, 5] +removeDuplicates(numbers); // Returns: [1, 2, 3, 4, 5] ``` diff --git a/snippets/javascript/array-manipulation/remove-falsy-value.md b/snippets/javascript/array-manipulation/remove-falsy-value.md deleted file mode 100644 index 2b9dd71f..00000000 --- a/snippets/javascript/array-manipulation/remove-falsy-value.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Remove Falsy Values -description: Removes falsy values like null, undefined, and false from an array. -author: mubasshir -tags: javascript,array,falsy,filter ---- - -```js -const removeFalsy = (arr) => arr.filter(Boolean); - -// Usage: -const array = [0, 1, false, 2, "", 3, null]; -console.log(removeFalsy(array)); // Output: [1, 2, 3] -``` diff --git a/snippets/javascript/array-manipulation/remove-falsy-values.md b/snippets/javascript/array-manipulation/remove-falsy-values.md new file mode 100644 index 00000000..2a6c72d7 --- /dev/null +++ b/snippets/javascript/array-manipulation/remove-falsy-values.md @@ -0,0 +1,14 @@ +--- +title: Remove Falsy Values +description: Removes falsy values from an array. +author: mubasshir +tags: array,falsy,filter +--- + +```js +const removeFalsy = (arr) => arr.filter(Boolean); + +// Usage: +const array = [0, 1, false, 2, "", 3, null]; +removeFalsy(array); // Returns: [1, 2, 3] +``` diff --git a/snippets/javascript/array-manipulation/shuffle-array.md b/snippets/javascript/array-manipulation/shuffle-array.md index 7f41f9aa..97670824 100644 --- a/snippets/javascript/array-manipulation/shuffle-array.md +++ b/snippets/javascript/array-manipulation/shuffle-array.md @@ -2,7 +2,7 @@ title: Shuffle Array description: Shuffles an Array. author: loxt-nixo -tags: javascript,array,shuffle,utility +tags: array,shuffle --- ```js @@ -12,4 +12,8 @@ function shuffleArray(array) { [array[i], array[j]] = [array[j], array[i]]; } } + +// Usage: +const array = [1, 2, 3, 4, 5]; +shuffleArray(array); // Shuffles `array` in place ``` diff --git a/snippets/javascript/array-manipulation/zip-arrays.md b/snippets/javascript/array-manipulation/zip-arrays.md index 12d3a7d7..d18a8371 100644 --- a/snippets/javascript/array-manipulation/zip-arrays.md +++ b/snippets/javascript/array-manipulation/zip-arrays.md @@ -2,7 +2,7 @@ title: Zip Arrays description: Combines two arrays by pairing corresponding elements from each array. author: Swaraj-Singh-30 -tags: javascript,array,utility,map +tags: array,map --- ```js diff --git a/snippets/javascript/basics/hello-world.md b/snippets/javascript/basics/hello-world.md index b65c84b9..d553cde6 100644 --- a/snippets/javascript/basics/hello-world.md +++ b/snippets/javascript/basics/hello-world.md @@ -2,7 +2,7 @@ title: Hello, World! description: Prints Hello, World! to the terminal. author: James-Beans -tags: javascript,printing,hello-world,utility +tags: printing,hello-world --- ```js diff --git a/snippets/javascript/date-and-time/add-days-to-a-date.md b/snippets/javascript/date-and-time/add-days-to-a-date.md deleted file mode 100644 index 34cb879a..00000000 --- a/snippets/javascript/date-and-time/add-days-to-a-date.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: Add Days to a Date -description: Adds a specified number of days to a given date. -author: axorax -tags: javascript,date,add-days,utility ---- - -```js -const addDays = (date, days) => { - const result = new Date(date); - result.setDate(result.getDate() + days); - return result; -}; - -// Usage: -const today = new Date(); -console.log(addDays(today, 10)); // Output: Date object 10 days ahead -``` diff --git a/snippets/javascript/date-and-time/check-leap-year.md b/snippets/javascript/date-and-time/check-leap-year.md index c65fac67..520b990f 100644 --- a/snippets/javascript/date-and-time/check-leap-year.md +++ b/snippets/javascript/date-and-time/check-leap-year.md @@ -2,13 +2,13 @@ title: Check Leap Year description: Determines if a given year is a leap year. author: axorax -tags: javascript,date,leap-year,utility +tags: date,leap-year --- ```js const isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; // Usage: -console.log(isLeapYear(2024)); // Output: true -console.log(isLeapYear(2023)); // Output: false +isLeapYear(2024); // Returns: true +isLeapYear(2023); // Returns: false ``` diff --git a/snippets/javascript/date-and-time/convert-to-unix-timestamp.md b/snippets/javascript/date-and-time/convert-to-unix-timestamp.md index 87bcceaa..12020d26 100644 --- a/snippets/javascript/date-and-time/convert-to-unix-timestamp.md +++ b/snippets/javascript/date-and-time/convert-to-unix-timestamp.md @@ -2,17 +2,10 @@ title: Convert to Unix Timestamp description: Converts a date to a Unix timestamp in seconds. author: Yugveer06 -tags: javascript,date,unix,timestamp,utility +tags: date,unix,timestamp --- ```js -/** - * Converts a date string or Date object to Unix timestamp in seconds. - * - * @param {string|Date} input - A valid date string or Date object. - * @returns {number} - The Unix timestamp in seconds. - * @throws {Error} - Throws an error if the input is invalid. - */ function convertToUnixSeconds(input) { if (typeof input === 'string') { if (!input.trim()) { @@ -39,8 +32,8 @@ function convertToUnixSeconds(input) { return Math.floor(date.getTime() / 1000); } -// Usage -console.log(convertToUnixSeconds('2025-01-01T12:00:00Z')); // 1735732800 -console.log(convertToUnixSeconds(new Date('2025-01-01T12:00:00Z'))); // 1735732800 -console.log(convertToUnixSeconds(new Date())); //Current Unix timestamp in seconds (varies depending on execution time) +// Usage: +convertToUnixSeconds('2025-01-01T12:00:00Z'); // Returns: 1735732800 +convertToUnixSeconds(new Date('2025-01-01T12:00:00Z')); // Returns: 1735732800 +convertToUnixSeconds(new Date()); // Returns: Current Unix timestamp in seconds ``` diff --git a/snippets/javascript/date-and-time/format-date.md b/snippets/javascript/date-and-time/format-date.md index db75a004..9c7ef8ff 100644 --- a/snippets/javascript/date-and-time/format-date.md +++ b/snippets/javascript/date-and-time/format-date.md @@ -2,12 +2,12 @@ title: Format Date description: Formats a date in 'YYYY-MM-DD' format. author: dostonnabotov -tags: javascript,date,format,utility +tags: date,format --- ```js const formatDate = (date) => date.toISOString().split('T')[0]; // Usage: -console.log(formatDate(new Date())); // Output: '2024-12-10' +formatDate(new Date(2024, 11, 10)); // Returns: '2024-12-10' ``` diff --git a/snippets/javascript/date-and-time/get-current-timestamp.md b/snippets/javascript/date-and-time/get-current-timestamp.md deleted file mode 100644 index 2581e299..00000000 --- a/snippets/javascript/date-and-time/get-current-timestamp.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Get Current Timestamp -description: Retrieves the current timestamp in milliseconds since January 1, 1970. -author: axorax -tags: javascript,date,timestamp,utility ---- - -```js -const getCurrentTimestamp = () => Date.now(); - -// Usage: -console.log(getCurrentTimestamp()); // Output: 1691825935839 (example) -``` diff --git a/snippets/javascript/date-and-time/get-day-of-the-year.md b/snippets/javascript/date-and-time/get-day-of-the-year.md index 9ac076db..6c7349c1 100644 --- a/snippets/javascript/date-and-time/get-day-of-the-year.md +++ b/snippets/javascript/date-and-time/get-day-of-the-year.md @@ -2,7 +2,7 @@ title: Get Day of the Year description: Calculates the day of the year (1-365 or 1-366 for leap years) for a given date. author: axorax -tags: javascript,date,day-of-year,utility +tags: date,day-of-year --- ```js @@ -13,6 +13,5 @@ const getDayOfYear = (date) => { }; // Usage: -const today = new Date('2024-12-31'); -console.log(getDayOfYear(today)); // Output: 366 (in a leap year) +getDayOfYear(new Date('2024-12-31')) // Returns: 366 (Leap year) ``` diff --git a/snippets/javascript/date-and-time/get-days-in-month.md b/snippets/javascript/date-and-time/get-days-in-month.md index d1c97b3e..a9eb8661 100644 --- a/snippets/javascript/date-and-time/get-days-in-month.md +++ b/snippets/javascript/date-and-time/get-days-in-month.md @@ -2,13 +2,13 @@ title: Get Days in Month description: Calculates the number of days in a specific month of a given year. author: axorax -tags: javascript,date,days-in-month,utility +tags: date,days-in-month --- ```js const getDaysInMonth = (year, month) => new Date(year, month + 1, 0).getDate(); // Usage: -console.log(getDaysInMonth(2024, 1)); // Output: 29 (February in a leap year) -console.log(getDaysInMonth(2023, 1)); // Output: 28 +getDaysInMonth(2024, 1); // Returns: 29 (February in a leap year) +getDaysInMonth(2023, 1); // Returns: 28 ``` diff --git a/snippets/javascript/date-and-time/get-time-difference.md b/snippets/javascript/date-and-time/get-time-difference.md index 57f4e210..11176ec7 100644 --- a/snippets/javascript/date-and-time/get-time-difference.md +++ b/snippets/javascript/date-and-time/get-time-difference.md @@ -2,7 +2,7 @@ title: Get Time Difference description: Calculates the time difference in days between two dates. author: dostonnabotov -tags: javascript,date,time-difference,utility +tags: date,time-difference --- ```js @@ -14,5 +14,5 @@ const getTimeDifference = (date1, date2) => { // Usage: const date1 = new Date('2024-01-01'); const date2 = new Date('2024-12-31'); -console.log(getTimeDifference(date1, date2)); // Output: 365 +getTimeDifference(date1, date2); // Returns: 365 ``` diff --git a/snippets/javascript/date-and-time/relative-time-formatter.md b/snippets/javascript/date-and-time/relative-time-formatter.md index 936f6aaa..bc095bae 100644 --- a/snippets/javascript/date-and-time/relative-time-formatter.md +++ b/snippets/javascript/date-and-time/relative-time-formatter.md @@ -2,7 +2,7 @@ title: Relative Time Formatter description: Displays how long ago a date occurred or how far in the future a date is. author: Yugveer06 -tags: javascript,date,time,relative,future,past,utility +tags: date,time,relative,future,past --- ```js @@ -27,10 +27,10 @@ const getRelativeTime = (date) => { return `${isFuture ? 'in ' : ''}${seconds} ${seconds === 1 ? 'second' : 'seconds'}${isFuture ? '' : ' ago'}`; } -// usage +// Usage: const pastDate = new Date('2021-12-29 13:00:00'); -const futureDate = new Date('2026-12-29 13:00:00'); -console.log(getRelativeTime(pastDate)); // x years ago -console.log(getRelativeTime(new Date())); // just now -console.log(getRelativeTime(futureDate)); // in x years +const futureDate = new Date('2099-12-29 13:00:00'); +getRelativeTime(pastDate); // x years ago +getRelativeTime(new Date()); // just now +getRelativeTime(futureDate); // in x years ``` diff --git a/snippets/javascript/date-and-time/start-of-the-day.md b/snippets/javascript/date-and-time/start-of-the-day.md index 39d417a8..f9f78524 100644 --- a/snippets/javascript/date-and-time/start-of-the-day.md +++ b/snippets/javascript/date-and-time/start-of-the-day.md @@ -2,7 +2,7 @@ title: Start of the Day description: Returns the start of the day (midnight) for a given date. author: axorax -tags: javascript,date,start-of-day,utility +tags: date,start-of-day --- ```js @@ -10,5 +10,5 @@ const startOfDay = (date) => new Date(date.setHours(0, 0, 0, 0)); // Usage: const today = new Date(); -console.log(startOfDay(today)); // Output: Date object for midnight +startOfDay(today); // Returns: Date object for midnight ``` diff --git a/snippets/javascript/dom-manipulation/change-element-style.md b/snippets/javascript/dom-manipulation/change-element-style.md index 32ec73ea..453a212c 100644 --- a/snippets/javascript/dom-manipulation/change-element-style.md +++ b/snippets/javascript/dom-manipulation/change-element-style.md @@ -2,7 +2,7 @@ title: Change Element Style description: Changes the inline style of an element. author: axorax -tags: javascript,dom,style,utility +tags: dom,style --- ```js diff --git a/snippets/javascript/dom-manipulation/get-element-position.md b/snippets/javascript/dom-manipulation/get-element-position.md deleted file mode 100644 index e7958b6a..00000000 --- a/snippets/javascript/dom-manipulation/get-element-position.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: Get Element Position -description: Gets the position of an element relative to the viewport. -author: axorax -tags: javascript,dom,position,utility ---- - -```js -const getElementPosition = (element) => { - const rect = element.getBoundingClientRect(); - return { x: rect.left, y: rect.top }; -}; - -// Usage: -const element = document.querySelector('.my-element'); -const position = getElementPosition(element); -console.log(position); // { x: 100, y: 150 } -``` diff --git a/snippets/javascript/dom-manipulation/remove-element.md b/snippets/javascript/dom-manipulation/remove-element.md index 5874b3cd..f319b964 100644 --- a/snippets/javascript/dom-manipulation/remove-element.md +++ b/snippets/javascript/dom-manipulation/remove-element.md @@ -2,7 +2,7 @@ title: Remove Element description: Removes a specified element from the DOM. author: axorax -tags: javascript,dom,remove,utility +tags: dom,remove --- ```js diff --git a/snippets/javascript/dom-manipulation/smooth-scroll-to-element.md b/snippets/javascript/dom-manipulation/smooth-scroll-to-element.md deleted file mode 100644 index eccc9c68..00000000 --- a/snippets/javascript/dom-manipulation/smooth-scroll-to-element.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: Smooth Scroll to Element -description: Scrolls smoothly to a specified element. -author: dostonnabotov -tags: javascript,dom,scroll,ui ---- - -```js -const smoothScroll = (element) => { - element.scrollIntoView({ behavior: 'smooth' }); -}; - -// Usage: -const target = document.querySelector('#target'); -smoothScroll(target); -``` diff --git a/snippets/javascript/dom-manipulation/toggle-class.md b/snippets/javascript/dom-manipulation/toggle-class.md deleted file mode 100644 index 30473093..00000000 --- a/snippets/javascript/dom-manipulation/toggle-class.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: Toggle Class -description: Toggles a class on an element. -author: dostonnabotov -tags: javascript,dom,class,utility ---- - -```js -const toggleClass = (element, className) => { - element.classList.toggle(className); -}; - -// Usage: -const element = document.querySelector('.my-element'); -toggleClass(element, 'active'); -``` diff --git a/snippets/javascript/function-utilities/compose-functions.md b/snippets/javascript/function-utilities/compose-functions.md index f05da50e..d56b95d2 100644 --- a/snippets/javascript/function-utilities/compose-functions.md +++ b/snippets/javascript/function-utilities/compose-functions.md @@ -2,7 +2,7 @@ title: Compose Functions description: Composes multiple functions into a single function, where the output of one function becomes the input of the next. author: axorax -tags: javascript,function,compose,utility +tags: function,compose --- ```js @@ -14,5 +14,5 @@ const compose = (...funcs) => (initialValue) => { const add2 = (x) => x + 2; const multiply3 = (x) => x * 3; const composed = compose(multiply3, add2); -console.log(composed(5)); // Output: 21 ((5 + 2) * 3) +composed(5); // Returns: 17 ((5 * 3) + 2) ``` diff --git a/snippets/javascript/function-utilities/curry-function.md b/snippets/javascript/function-utilities/curry-function.md index aa74ab60..a16bb16b 100644 --- a/snippets/javascript/function-utilities/curry-function.md +++ b/snippets/javascript/function-utilities/curry-function.md @@ -2,7 +2,7 @@ title: Curry Function description: Transforms a function into its curried form. author: axorax -tags: javascript,curry,function,utility +tags: curry,function --- ```js @@ -19,6 +19,6 @@ const curry = (func) => { // Usage: const add = (a, b, c) => a + b + c; const curriedAdd = curry(add); -console.log(curriedAdd(1)(2)(3)); // Output: 6 -console.log(curriedAdd(1, 2)(3)); // Output: 6 +curriedAdd(1)(2)(3); // Returns: 6 +curriedAdd(1, 2)(3); // Returns: 6 ``` diff --git a/snippets/javascript/function-utilities/debounce-function.md b/snippets/javascript/function-utilities/debounce-function.md index fc3674d4..0967eb01 100644 --- a/snippets/javascript/function-utilities/debounce-function.md +++ b/snippets/javascript/function-utilities/debounce-function.md @@ -2,7 +2,7 @@ title: Debounce Function description: Delays a function execution until after a specified time. author: dostonnabotov -tags: javascript,utility,debounce,performance +tags: debounce,performance --- ```js @@ -16,5 +16,8 @@ const debounce = (func, delay) => { }; // Usage: -window.addEventListener('resize', debounce(() => console.log('Resized!'), 500)); +window.addEventListener( + 'resize', + debounce(() => console.log('Resized!'), 500), // Will only output after resizing has stopped for 500ms +); ``` diff --git a/snippets/javascript/function-utilities/get-contrast-color.md b/snippets/javascript/function-utilities/get-contrast-color.md index 2dd5862b..4f07dbe7 100644 --- a/snippets/javascript/function-utilities/get-contrast-color.md +++ b/snippets/javascript/function-utilities/get-contrast-color.md @@ -2,7 +2,7 @@ title: Get Contrast Color description: Returns either black or white text color based on the brightness of the provided hex color. author: yaya12085 -tags: javascript,color,hex,contrast,brightness,utility +tags: color,hex,contrast,brightness --- ```js @@ -19,8 +19,8 @@ const getContrastColor = (hexColor) => { }; // Usage: -console.log(getContrastColor('#fff')); // Output: #000000 (black) -console.log(getContrastColor('#123456')); // Output: #FFFFFF (white) -console.log(getContrastColor('#ff6347')); // Output: #000000 (black) -console.log(getContrastColor('#f4f')); // Output: #000000 (black) +getContrastColor('#fff'); // Returns: #000000 (black) +getContrastColor('#123456'); // Returns: #FFFFFF (white) +getContrastColor('#ff6347'); // Returns: #000000 (black) +getContrastColor('#f4f'); // Returns: #000000 (black) ``` diff --git a/snippets/javascript/function-utilities/memoize-function.md b/snippets/javascript/function-utilities/memoize-function.md index dcde72bf..8902e100 100644 --- a/snippets/javascript/function-utilities/memoize-function.md +++ b/snippets/javascript/function-utilities/memoize-function.md @@ -2,7 +2,7 @@ title: Memoize Function description: Caches the result of a function based on its arguments to improve performance. author: axorax -tags: javascript,memoization,optimization,utility +tags: memoization,optimization --- ```js @@ -21,6 +21,6 @@ const memoize = (func) => { // Usage: const factorial = memoize((n) => (n <= 1 ? 1 : n * factorial(n - 1))); -console.log(factorial(5)); // Output: 120 -console.log(factorial(5)); // Output: 120 (retrieved from cache) +factorial(5); // Returns: 120 +factorial(5); // Returns: 120 (retrieved from cache) ``` diff --git a/snippets/javascript/function-utilities/once-function.md b/snippets/javascript/function-utilities/once-function.md index 62db4b46..59be4260 100644 --- a/snippets/javascript/function-utilities/once-function.md +++ b/snippets/javascript/function-utilities/once-function.md @@ -2,7 +2,7 @@ title: Once Function description: Ensures a function is only called once. author: axorax -tags: javascript,function,once,utility +tags: function,once --- ```js diff --git a/snippets/javascript/function-utilities/rate-limit-function.md b/snippets/javascript/function-utilities/rate-limit-function.md index d6dc81b2..fb1e19ed 100644 --- a/snippets/javascript/function-utilities/rate-limit-function.md +++ b/snippets/javascript/function-utilities/rate-limit-function.md @@ -2,7 +2,7 @@ title: Rate Limit Function description: Limits how often a function can be executed within a given time window. author: axorax -tags: javascript,function,rate-limiting,utility +tags: function,rate-limiting --- ```js @@ -24,5 +24,5 @@ const rateLimit = (func, limit, timeWindow) => { // Usage: const fetchData = () => console.log('Fetching data...'); const rateLimitedFetch = rateLimit(fetchData, 2, 1000); -setInterval(() => rateLimitedFetch(), 200); // Only calls fetchData twice every second +setInterval(() => rateLimitedFetch(), 200); // Limits fetchData calls to twice a seconds ``` diff --git a/snippets/javascript/function-utilities/repeat-function-invocation.md b/snippets/javascript/function-utilities/repeat-function-invocation.md index a425a995..908ab4aa 100644 --- a/snippets/javascript/function-utilities/repeat-function-invocation.md +++ b/snippets/javascript/function-utilities/repeat-function-invocation.md @@ -2,7 +2,7 @@ title: Repeat Function Invocation description: Invokes a function a specified number of times. author: dostonnabotov -tags: javascript,function,repeat,utility +tags: function,repeat --- ```js diff --git a/snippets/javascript/function-utilities/sleep-function.md b/snippets/javascript/function-utilities/sleep-function.md index 991390ea..a84ca69c 100644 --- a/snippets/javascript/function-utilities/sleep-function.md +++ b/snippets/javascript/function-utilities/sleep-function.md @@ -9,11 +9,7 @@ tags: javascript,sleep,delay,utility,promises const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); // Usage: -async function main() { - console.log('Hello'); - await sleep(2000); // Waits for 2 seconds - console.log('World!'); -} - -main(); +console.log('Hello'); +await sleep(2000); // Waits for 2 seconds +console.log('World!'); ``` diff --git a/snippets/javascript/function-utilities/throttle-function.md b/snippets/javascript/function-utilities/throttle-function.md deleted file mode 100644 index a425479f..00000000 --- a/snippets/javascript/function-utilities/throttle-function.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Throttle Function -description: Limits a function execution to once every specified time interval. -author: dostonnabotov -tags: javascript,utility,throttle,performance ---- - -```js -const throttle = (func, limit) => { - let lastFunc; - let lastRan; - return (...args) => { - const context = this; - if (!lastRan) { - func.apply(context, args); - lastRan = Date.now(); - } else { - clearTimeout(lastFunc); - lastFunc = setTimeout(() => { - if (Date.now() - lastRan >= limit) { - func.apply(context, args); - lastRan = Date.now(); - } - }, limit - (Date.now() - lastRan)); - } - }; -}; - -// Usage: -document.addEventListener('scroll', throttle(() => console.log('Scrolled!'), 1000)); -``` diff --git a/snippets/javascript/local-storage/add-item-to-localstorage.md b/snippets/javascript/local-storage/add-item-to-localstorage.md index 853f2949..1d12cb06 100644 --- a/snippets/javascript/local-storage/add-item-to-localstorage.md +++ b/snippets/javascript/local-storage/add-item-to-localstorage.md @@ -2,7 +2,7 @@ title: Add Item to localStorage description: Stores a value in localStorage under the given key. author: dostonnabotov -tags: javascript,localStorage,storage,utility +tags: localStorage,storage --- ```js diff --git a/snippets/javascript/local-storage/check-if-item-exists-in-localstorage.md b/snippets/javascript/local-storage/check-if-item-exists-in-localstorage.md index 77fbe5d5..077234f3 100644 --- a/snippets/javascript/local-storage/check-if-item-exists-in-localstorage.md +++ b/snippets/javascript/local-storage/check-if-item-exists-in-localstorage.md @@ -2,7 +2,7 @@ title: Check if Item Exists in localStorage description: Checks if a specific item exists in localStorage. author: axorax -tags: javascript,localStorage,storage,utility +tags: localStorage,storage --- ```js diff --git a/snippets/javascript/local-storage/clear-all-localstorage.md b/snippets/javascript/local-storage/clear-all-localstorage.md deleted file mode 100644 index f5f9a6d8..00000000 --- a/snippets/javascript/local-storage/clear-all-localstorage.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -title: Clear All localStorage -description: Clears all data from localStorage. -author: dostonnabotov -tags: javascript,localStorage,storage,utility ---- - -```js -const clearLocalStorage = () => { - localStorage.clear(); -}; - -// Usage: -clearLocalStorage(); // Removes all items from localStorage -``` diff --git a/snippets/javascript/local-storage/retrieve-item-from-localstorage.md b/snippets/javascript/local-storage/retrieve-item-from-localstorage.md index e6dba542..90ec3e63 100644 --- a/snippets/javascript/local-storage/retrieve-item-from-localstorage.md +++ b/snippets/javascript/local-storage/retrieve-item-from-localstorage.md @@ -2,7 +2,7 @@ title: Retrieve Item from localStorage description: Retrieves a value from localStorage by key and parses it. author: dostonnabotov -tags: javascript,localStorage,storage,utility +tags: localStorage,storage --- ```js @@ -12,6 +12,5 @@ const getFromLocalStorage = (key) => { }; // Usage: -const user = getFromLocalStorage('user'); -console.log(user); // Output: { name: 'John', age: 30 } +getFromLocalStorage('user'); // Returns: { name: 'John', age: 30 } ``` diff --git a/snippets/javascript/number-formatting/convert-number-to-currency.md b/snippets/javascript/number-formatting/convert-number-to-currency.md index 2600cfd5..8ec168cc 100644 --- a/snippets/javascript/number-formatting/convert-number-to-currency.md +++ b/snippets/javascript/number-formatting/convert-number-to-currency.md @@ -2,7 +2,7 @@ title: Convert Number to Currency description: Converts a number to a currency format with a specific locale. author: axorax -tags: javascript,number,currency,utility +tags: number,currency --- ```js @@ -14,6 +14,6 @@ const convertToCurrency = (num, locale = 'en-US', currency = 'USD') => { }; // Usage: -console.log(convertToCurrency(1234567.89)); // Output: '$1,234,567.89' -console.log(convertToCurrency(987654.32, 'de-DE', 'EUR')); // Output: '987.654,32 €' +convertToCurrency(1234567.89); // Returns: '$1,234,567.89' +convertToCurrency(987654.32, 'de-DE', 'EUR'); // Returns: '987.654,32 €' ``` diff --git a/snippets/javascript/number-formatting/convert-number-to-roman-numerals.md b/snippets/javascript/number-formatting/convert-number-to-roman-numerals.md index 7830174a..21fa4c96 100644 --- a/snippets/javascript/number-formatting/convert-number-to-roman-numerals.md +++ b/snippets/javascript/number-formatting/convert-number-to-roman-numerals.md @@ -2,7 +2,7 @@ title: Convert Number to Roman Numerals description: Converts a number to Roman numeral representation. author: axorax -tags: javascript,number,roman,utility +tags: number,roman --- ```js @@ -22,6 +22,6 @@ const numberToRoman = (num) => { }; // Usage: -console.log(numberToRoman(1994)); // Output: 'MCMXCIV' -console.log(numberToRoman(58)); // Output: 'LVIII' +numberToRoman(1994); // Returns: 'MCMXCIV' +numberToRoman(58); // Returns: 'LVIII' ``` diff --git a/snippets/javascript/number-formatting/convert-to-scientific-notation.md b/snippets/javascript/number-formatting/convert-to-scientific-notation.md index dc16282d..1d4a2f68 100644 --- a/snippets/javascript/number-formatting/convert-to-scientific-notation.md +++ b/snippets/javascript/number-formatting/convert-to-scientific-notation.md @@ -2,7 +2,7 @@ title: Convert to Scientific Notation description: Converts a number to scientific notation. author: axorax -tags: javascript,number,scientific,utility +tags: number,scientific --- ```js @@ -19,9 +19,9 @@ const toScientificNotation = (num) => { }; // Usage: -console.log(toScientificNotation(12345)); // Output: '1.23e+4' -console.log(toScientificNotation(0.0005678)); // Output: '5.68e-4' -console.log(toScientificNotation(1000)); // Output: '1.00e+3' -console.log(toScientificNotation(0)); // Output: '0e+0' -console.log(toScientificNotation(-54321)); // Output: '-5.43e+4' +toScientificNotation(12345); // Returns: '1.23e+4' +toScientificNotation(0.0005678); // Returns: '5.68e-4' +toScientificNotation(1000); // Returns: '1.00e+3' +toScientificNotation(0); // Returns: '0e+0' +toScientificNotation(-54321); // Returns: '-5.43e+4' ``` diff --git a/snippets/javascript/number-formatting/format-number-with-commas.md b/snippets/javascript/number-formatting/format-number-with-commas.md index 27bd7175..5275e833 100644 --- a/snippets/javascript/number-formatting/format-number-with-commas.md +++ b/snippets/javascript/number-formatting/format-number-with-commas.md @@ -2,7 +2,7 @@ title: Format Number with Commas description: Formats a number with commas for better readability (e.g., 1000 -> 1,000). author: axorax -tags: javascript,number,format,utility +tags: number,format --- ```js @@ -11,7 +11,7 @@ const formatNumberWithCommas = (num) => { }; // Usage: -console.log(formatNumberWithCommas(1000)); // Output: '1,000' -console.log(formatNumberWithCommas(1234567)); // Output: '1,234,567' -console.log(formatNumberWithCommas(987654321)); // Output: '987,654,321' +formatNumberWithCommas(1000); // Returns: '1,000' +formatNumberWithCommas(1234567); // Returns: '1,234,567' +formatNumberWithCommas(987654321); // Returns: '987,654,321' ``` diff --git a/snippets/javascript/number-formatting/number-formatter.md b/snippets/javascript/number-formatting/number-formatter.md index 83996903..8633ade3 100644 --- a/snippets/javascript/number-formatting/number-formatter.md +++ b/snippets/javascript/number-formatting/number-formatter.md @@ -2,7 +2,7 @@ title: Number Formatter description: Formats a number with suffixes (K, M, B, etc.). author: realvishalrana -tags: javascript,number,format,utility +tags: number,format --- ```js @@ -19,5 +19,5 @@ const nFormatter = (num) => { }; // Usage: -console.log(nFormatter(1234567)); // Output: '1.23M' +nFormatter(1234567); // Returns: '1.23M' ``` diff --git a/snippets/javascript/number-formatting/number-to-words-converter.md b/snippets/javascript/number-formatting/number-to-words-converter.md index cdac597d..7878d12a 100644 --- a/snippets/javascript/number-formatting/number-to-words-converter.md +++ b/snippets/javascript/number-formatting/number-to-words-converter.md @@ -2,7 +2,7 @@ title: Number to Words Converter description: Converts a number to its word representation in English. author: axorax -tags: javascript,number,words,utility +tags: number,words --- ```js @@ -25,6 +25,6 @@ const numberToWords = (num) => { }; // Usage: -console.log(numberToWords(123)); // Output: 'One Hundred Twenty Three' -console.log(numberToWords(2045)); // Output: 'Two Thousand Forty Five' +numberToWords(123); // Returns: 'One Hundred Twenty Three' +numberToWords(2045); // Returns: 'Two Thousand Forty Five' ``` diff --git a/snippets/javascript/object-manipulation/check-if-object-is-empty.md b/snippets/javascript/object-manipulation/check-if-object-is-empty.md index bb0dfde9..f89b5087 100644 --- a/snippets/javascript/object-manipulation/check-if-object-is-empty.md +++ b/snippets/javascript/object-manipulation/check-if-object-is-empty.md @@ -2,7 +2,7 @@ title: Check if Object is Empty description: Checks whether an object has no own enumerable properties. author: axorax -tags: javascript,object,check,empty +tags: object,check,empty --- ```js @@ -11,6 +11,6 @@ function isEmptyObject(obj) { } // Usage: -console.log(isEmptyObject({})); // Output: true -console.log(isEmptyObject({ a: 1 })); // Output: false +isEmptyObject({}); // Returns: true +isEmptyObject({ a: 1 }); // Returns: false ``` diff --git a/snippets/javascript/object-manipulation/clone-object-shallowly.md b/snippets/javascript/object-manipulation/clone-object-shallowly.md deleted file mode 100644 index 546ad090..00000000 --- a/snippets/javascript/object-manipulation/clone-object-shallowly.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: Clone Object Shallowly -description: Creates a shallow copy of an object. -author: axorax -tags: javascript,object,clone,shallow ---- - -```js -function shallowClone(obj) { - return { ...obj }; -} - -// Usage: -const obj = { a: 1, b: 2 }; -const clone = shallowClone(obj); -console.log(clone); // Output: { a: 1, b: 2 } -``` diff --git a/snippets/javascript/object-manipulation/compare-two-objects-shallowly.md b/snippets/javascript/object-manipulation/compare-two-objects-shallowly.md index 6d3d3eaf..03dd41f6 100644 --- a/snippets/javascript/object-manipulation/compare-two-objects-shallowly.md +++ b/snippets/javascript/object-manipulation/compare-two-objects-shallowly.md @@ -2,7 +2,7 @@ title: Compare Two Objects Shallowly description: Compares two objects shallowly and returns whether they are equal. author: axorax -tags: javascript,object,compare,shallow +tags: object,compare,shallow --- ```js @@ -17,6 +17,6 @@ function shallowEqual(obj1, obj2) { const obj1 = { a: 1, b: 2 }; const obj2 = { a: 1, b: 2 }; const obj3 = { a: 1, b: 3 }; -console.log(shallowEqual(obj1, obj2)); // Output: true -console.log(shallowEqual(obj1, obj3)); // Output: false +shallowEqual(obj1, obj2); // Returns: true +shallowEqual(obj1, obj3); // Returns: false ``` diff --git a/snippets/javascript/object-manipulation/convert-object-to-query-string.md b/snippets/javascript/object-manipulation/convert-object-to-query-string.md index 568057f4..31abe05d 100644 --- a/snippets/javascript/object-manipulation/convert-object-to-query-string.md +++ b/snippets/javascript/object-manipulation/convert-object-to-query-string.md @@ -2,7 +2,7 @@ title: Convert Object to Query String description: Converts an object to a query string for use in URLs. author: axorax -tags: javascript,object,query string,url +tags: object,query string,url --- ```js @@ -14,5 +14,5 @@ function toQueryString(obj) { // Usage: const params = { search: 'test', page: 1 }; -console.log(toQueryString(params)); // Output: 'search=test&page=1' +toQueryString(params); // Returns: 'search=test&page=1' ``` diff --git a/snippets/javascript/object-manipulation/count-properties-in-object.md b/snippets/javascript/object-manipulation/count-properties-in-object.md index 67aa9227..577eb30e 100644 --- a/snippets/javascript/object-manipulation/count-properties-in-object.md +++ b/snippets/javascript/object-manipulation/count-properties-in-object.md @@ -2,7 +2,7 @@ title: Count Properties in Object description: Counts the number of own properties in an object. author: axorax -tags: javascript,object,count,properties +tags: object,count,properties --- ```js @@ -12,5 +12,5 @@ function countProperties(obj) { // Usage: const obj = { a: 1, b: 2, c: 3 }; -console.log(countProperties(obj)); // Output: 3 +countProperties(obj); // Returns: 3 ``` diff --git a/snippets/javascript/object-manipulation/filter-object.md b/snippets/javascript/object-manipulation/filter-object.md index 889387a6..ee24f7d2 100644 --- a/snippets/javascript/object-manipulation/filter-object.md +++ b/snippets/javascript/object-manipulation/filter-object.md @@ -2,7 +2,7 @@ title: Filter Object description: Filter out entries in an object where the value is falsy, including empty strings, empty objects, null, and undefined. author: realvishalrana -tags: javascript,object,filter,utility +tags: object,filter --- ```js @@ -14,14 +14,14 @@ export const filterObject = (object = {}) => // Usage: const obj1 = { a: 1, b: null, c: undefined, d: 4, e: '', f: {} }; -console.log(filterObject(obj1)); // Output: { a: 1, d: 4 } +filterObject(obj1); // Returns: { a: 1, d: 4 } const obj2 = { x: 0, y: false, z: 'Hello', w: [] }; -console.log(filterObject(obj2)); // Output: { z: 'Hello' } +filterObject(obj2); // Returns: { z: 'Hello' } const obj3 = { name: 'John', age: null, address: { city: 'New York' }, phone: '' }; -console.log(filterObject(obj3)); // Output: { name: 'John', address: { city: 'New York' } } +filterObject(obj3); // Returns: { name: 'John', address: { city: 'New York' } } const obj4 = { a: 0, b: '', c: false, d: {}, e: 'Valid' }; -console.log(filterObject(obj4)); // Output: { e: 'Valid' } +filterObject(obj4); // Returns: { e: 'Valid' } ``` diff --git a/snippets/javascript/object-manipulation/flatten-nested-object.md b/snippets/javascript/object-manipulation/flatten-nested-object.md index d30219d1..8e1726d8 100644 --- a/snippets/javascript/object-manipulation/flatten-nested-object.md +++ b/snippets/javascript/object-manipulation/flatten-nested-object.md @@ -2,7 +2,7 @@ title: Flatten Nested Object description: Flattens a nested object into a single-level object with dot notation for keys. author: axorax -tags: javascript,object,flatten,utility +tags: object,flatten --- ```js @@ -20,5 +20,5 @@ function flattenObject(obj, prefix = '') { // Usage: const nestedObj = { a: { b: { c: 1 }, d: 2 }, e: 3 }; -console.log(flattenObject(nestedObj)); // Output: { 'a.b.c': 1, 'a.d': 2, e: 3 } +flattenObject(nestedObj); // Returns: { 'a.b.c': 1, 'a.d': 2, e: 3 } ``` diff --git a/snippets/javascript/object-manipulation/freeze-object.md b/snippets/javascript/object-manipulation/freeze-object.md index b933019f..dbdd481a 100644 --- a/snippets/javascript/object-manipulation/freeze-object.md +++ b/snippets/javascript/object-manipulation/freeze-object.md @@ -2,7 +2,7 @@ title: Freeze Object description: Freezes an object to make it immutable. author: axorax -tags: javascript,object,freeze,immutable +tags: object,freeze,immutable --- ```js @@ -14,5 +14,5 @@ function freezeObject(obj) { const obj = { a: 1, b: 2 }; const frozenObj = freezeObject(obj); frozenObj.a = 42; // This will fail silently in strict mode. -console.log(frozenObj.a); // Output: 1 +frozenObj.a; // Returns: 1 ``` diff --git a/snippets/javascript/object-manipulation/get-nested-value.md b/snippets/javascript/object-manipulation/get-nested-value.md index 398ca88f..d0d87149 100644 --- a/snippets/javascript/object-manipulation/get-nested-value.md +++ b/snippets/javascript/object-manipulation/get-nested-value.md @@ -2,7 +2,7 @@ title: Get Nested Value description: Retrieves the value at a given path in a nested object. author: realvishalrana -tags: javascript,object,nested,utility +tags: object,nested --- ```js @@ -15,5 +15,5 @@ const getNestedValue = (obj, path) => { // Usage: const obj = { a: { b: { c: 42 } } }; -console.log(getNestedValue(obj, 'a.b.c')); // Output: 42 +getNestedValue(obj, 'a.b.c'); // Returns: 42 ``` diff --git a/snippets/javascript/object-manipulation/invert-object-keys-and-values.md b/snippets/javascript/object-manipulation/invert-object-keys-and-values.md index 14f1c4d4..91441360 100644 --- a/snippets/javascript/object-manipulation/invert-object-keys-and-values.md +++ b/snippets/javascript/object-manipulation/invert-object-keys-and-values.md @@ -2,7 +2,7 @@ title: Invert Object Keys and Values description: Creates a new object by swapping keys and values of the given object. author: axorax -tags: javascript,object,invert,utility +tags: object,invert --- ```js @@ -14,5 +14,5 @@ function invertObject(obj) { // Usage: const obj = { a: 1, b: 2, c: 3 }; -console.log(invertObject(obj)); // Output: { '1': 'a', '2': 'b', '3': 'c' } +invertObject(obj); // Returns: { '1': 'a', '2': 'b', '3': 'c' } ``` diff --git a/snippets/javascript/object-manipulation/merge-objects-deeply.md b/snippets/javascript/object-manipulation/merge-objects-deeply.md index e7dadbad..6e6e92e3 100644 --- a/snippets/javascript/object-manipulation/merge-objects-deeply.md +++ b/snippets/javascript/object-manipulation/merge-objects-deeply.md @@ -2,7 +2,7 @@ title: Merge Objects Deeply description: Deeply merges two or more objects, including nested properties. author: axorax -tags: javascript,object,merge,deep +tags: object,merge,deep --- ```js @@ -22,5 +22,5 @@ function deepMerge(...objects) { // Usage: const obj1 = { a: 1, b: { c: 2 } }; const obj2 = { b: { d: 3 }, e: 4 }; -console.log(deepMerge(obj1, obj2)); // Output: { a: 1, b: { c: 2, d: 3 }, e: 4 } +deepMerge(obj1, obj2); // Returns: { a: 1, b: { c: 2, d: 3 }, e: 4 } ``` diff --git a/snippets/javascript/object-manipulation/omit-keys-from-object.md b/snippets/javascript/object-manipulation/omit-keys-from-object.md index 4487e332..846ce038 100644 --- a/snippets/javascript/object-manipulation/omit-keys-from-object.md +++ b/snippets/javascript/object-manipulation/omit-keys-from-object.md @@ -2,7 +2,7 @@ title: Omit Keys from Object description: Creates a new object with specific keys omitted. author: axorax -tags: javascript,object,omit,utility +tags: object,omit --- ```js @@ -14,5 +14,5 @@ function omitKeys(obj, keys) { // Usage: const obj = { a: 1, b: 2, c: 3 }; -console.log(omitKeys(obj, ['b', 'c'])); // Output: { a: 1 } +omitKeys(obj, ['b', 'c']); // Returns: { a: 1 } ``` diff --git a/snippets/javascript/object-manipulation/pick-keys-from-object.md b/snippets/javascript/object-manipulation/pick-keys-from-object.md index ae900203..36e3e67e 100644 --- a/snippets/javascript/object-manipulation/pick-keys-from-object.md +++ b/snippets/javascript/object-manipulation/pick-keys-from-object.md @@ -2,7 +2,7 @@ title: Pick Keys from Object description: Creates a new object with only the specified keys. author: axorax -tags: javascript,object,pick,utility +tags: object,pick --- ```js @@ -14,5 +14,5 @@ function pickKeys(obj, keys) { // Usage: const obj = { a: 1, b: 2, c: 3 }; -console.log(pickKeys(obj, ['a', 'c'])); // Output: { a: 1, c: 3 } +pickKeys(obj, ['a', 'c']); // Returns: { a: 1, c: 3 } ``` diff --git a/snippets/javascript/object-manipulation/unique-by-key.md b/snippets/javascript/object-manipulation/unique-by-key.md index 3a9e9fe1..07d2fc07 100644 --- a/snippets/javascript/object-manipulation/unique-by-key.md +++ b/snippets/javascript/object-manipulation/unique-by-key.md @@ -2,7 +2,7 @@ title: Unique By Key description: Filters an array of objects to only include unique objects by a specified key. author: realvishalrana -tags: javascript,array,unique,utility +tags: array,unique --- ```js @@ -15,5 +15,5 @@ const arr = [ { id: 2, name: 'Jane' }, { id: 1, name: 'John' } ]; -console.log(uniqueByKey('id', arr)); // Output: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }] +uniqueByKey('id', arr); // Returns: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }] ``` diff --git a/snippets/javascript/regular-expression/regex-match-utility-function.md b/snippets/javascript/regular-expression/regex-match-utility-function.md deleted file mode 100644 index 266d6ec4..00000000 --- a/snippets/javascript/regular-expression/regex-match-utility-function.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -title: Regex Match Utility Function -description: Enhanced regular expression matching utility. -author: aumirza -tags: javascript,regex ---- - -```js -/** -* @param {string | number} input -* The input string to match -* @param {regex | string} expression -* Regular expression -* @param {string} flags -* Optional Flags -* -* @returns {array} -* [{ -* match: '...', -* matchAtIndex: 0, -* capturedGroups: [ '...', '...' ] -* }] -*/ -function regexMatch(input, expression, flags = 'g') { - let regex = - expression instanceof RegExp - ? expression - : new RegExp(expression, flags); - let matches = input.matchAll(regex); - matches = [...matches]; - return matches.map((item) => { - return { - match: item[0], - matchAtIndex: item.index, - capturedGroups: item.length > 1 ? item.slice(1) : undefined, - }; - }); -} -``` diff --git a/snippets/javascript/string-manipulation/capitalize-string.md b/snippets/javascript/string-manipulation/capitalize-string.md index 1b515664..590ee798 100644 --- a/snippets/javascript/string-manipulation/capitalize-string.md +++ b/snippets/javascript/string-manipulation/capitalize-string.md @@ -2,12 +2,14 @@ title: Capitalize String description: Capitalizes the first letter of a string. author: dostonnabotov -tags: javascript,string,capitalize,utility +tags: string,capitalize --- ```js -const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1); +function capitalize(str) { + return str.charAt(0).toUpperCase() + str.slice(1); +} // Usage: -console.log(capitalize('hello')); // Output: 'Hello' +capitalize('hello'); // Returns: 'Hello' ``` diff --git a/snippets/javascript/string-manipulation/check-if-string-is-a-palindrome.md b/snippets/javascript/string-manipulation/check-if-string-is-a-palindrome.md index 5cd487ee..51845254 100644 --- a/snippets/javascript/string-manipulation/check-if-string-is-a-palindrome.md +++ b/snippets/javascript/string-manipulation/check-if-string-is-a-palindrome.md @@ -2,7 +2,7 @@ title: Check if String is a Palindrome description: Checks whether a given string is a palindrome. author: axorax -tags: javascript,check,palindrome,string +tags: check,palindrome,string --- ```js @@ -12,5 +12,5 @@ function isPalindrome(str) { } // Example usage: -console.log(isPalindrome('A man, a plan, a canal, Panama')); // Output: true +isPalindrome('A man, a plan, a canal, Panama'); // Returns: true ``` diff --git a/snippets/javascript/string-manipulation/convert-string-to-camel-case.md b/snippets/javascript/string-manipulation/convert-string-to-camel-case.md index d58026de..b282fd74 100644 --- a/snippets/javascript/string-manipulation/convert-string-to-camel-case.md +++ b/snippets/javascript/string-manipulation/convert-string-to-camel-case.md @@ -10,6 +10,6 @@ function toCamelCase(str) { return str.replace(/\W+(.)/g, (match, chr) => chr.toUpperCase()); } -// Example usage: -console.log(toCamelCase('hello world test')); // Output: 'helloWorldTest' +// Usage: +toCamelCase('hello world test'); // Returns: 'helloWorldTest' ``` diff --git a/snippets/javascript/string-manipulation/convert-string-to-param-case.md b/snippets/javascript/string-manipulation/convert-string-to-param-case.md index 9d2617bc..31e023ed 100644 --- a/snippets/javascript/string-manipulation/convert-string-to-param-case.md +++ b/snippets/javascript/string-manipulation/convert-string-to-param-case.md @@ -10,6 +10,6 @@ function toParamCase(str) { return str.toLowerCase().replace(/\s+/g, '-'); } -// Example usage: -console.log(toParamCase('Hello World Test')); // Output: 'hello-world-test' +// Usage: +toParamCase('Hello World Test'); // Returns: 'hello-world-test' ``` diff --git a/snippets/javascript/string-manipulation/convert-string-to-pascal-case.md b/snippets/javascript/string-manipulation/convert-string-to-pascal-case.md index ece7cc10..baa71de5 100644 --- a/snippets/javascript/string-manipulation/convert-string-to-pascal-case.md +++ b/snippets/javascript/string-manipulation/convert-string-to-pascal-case.md @@ -10,6 +10,6 @@ function toPascalCase(str) { return str.replace(/\b\w/g, (s) => s.toUpperCase()).replace(/\W+(.)/g, (match, chr) => chr.toUpperCase()); } -// Example usage: -console.log(toPascalCase('hello world test')); // Output: 'HelloWorldTest' +// Usage: +toPascalCase('hello world test'); // Returns: 'HelloWorldTest' ``` diff --git a/snippets/javascript/string-manipulation/convert-string-to-snake-case.md b/snippets/javascript/string-manipulation/convert-string-to-snake-case.md index 67a30e33..ed42eec0 100644 --- a/snippets/javascript/string-manipulation/convert-string-to-snake-case.md +++ b/snippets/javascript/string-manipulation/convert-string-to-snake-case.md @@ -12,6 +12,6 @@ function toSnakeCase(str) { .toLowerCase(); } -// Example usage: -console.log(toSnakeCase('Hello World Test')); // Output: 'hello_world_test' +// Usage: +toSnakeCase('Hello World Test'); // Returns: 'hello_world_test' ``` diff --git a/snippets/javascript/string-manipulation/convert-string-to-title-case.md b/snippets/javascript/string-manipulation/convert-string-to-title-case.md index cbea3521..32bdaf72 100644 --- a/snippets/javascript/string-manipulation/convert-string-to-title-case.md +++ b/snippets/javascript/string-manipulation/convert-string-to-title-case.md @@ -10,6 +10,6 @@ function toTitleCase(str) { return str.toLowerCase().replace(/\b\w/g, (s) => s.toUpperCase()); } -// Example usage: -console.log(toTitleCase('hello world test')); // Output: 'Hello World Test' +// Usage: +toTitleCase('hello world test'); // Returns: 'Hello World Test' ``` diff --git a/snippets/javascript/string-manipulation/convert-tabs-to-spaces.md b/snippets/javascript/string-manipulation/convert-tabs-to-spaces.md index fbeb9816..b6ae634a 100644 --- a/snippets/javascript/string-manipulation/convert-tabs-to-spaces.md +++ b/snippets/javascript/string-manipulation/convert-tabs-to-spaces.md @@ -10,6 +10,6 @@ function tabsToSpaces(str, spacesPerTab = 4) { return str.replace(/\t/g, ' '.repeat(spacesPerTab)); } -// Example usage: -console.log(tabsToSpaces('Hello\tWorld', 2)); // Output: 'Hello World' +// Usage: +tabsToSpaces('Hello\tWorld', 2); // Returns: 'Hello World' ``` diff --git a/snippets/javascript/string-manipulation/count-words-in-a-string.md b/snippets/javascript/string-manipulation/count-words-in-a-string.md index 036457a5..1816cec6 100644 --- a/snippets/javascript/string-manipulation/count-words-in-a-string.md +++ b/snippets/javascript/string-manipulation/count-words-in-a-string.md @@ -2,7 +2,7 @@ title: Count Words in a String description: Counts the number of words in a string. author: axorax -tags: javascript,string,manipulation,word count,count +tags: string,manipulation,word count,count --- ```js @@ -10,6 +10,6 @@ function countWords(str) { return str.trim().split(/\s+/).length; } -// Example usage: -console.log(countWords('Hello world! This is a test.')); // Output: 6 +// Usage: +countWords('Hello world! This is a test.'); // Returns: 6 ``` diff --git a/snippets/javascript/string-manipulation/data-with-prefix.md b/snippets/javascript/string-manipulation/data-with-prefix.md index d9a916c7..04fd1f47 100644 --- a/snippets/javascript/string-manipulation/data-with-prefix.md +++ b/snippets/javascript/string-manipulation/data-with-prefix.md @@ -2,7 +2,7 @@ title: Data with Prefix description: Adds a prefix and postfix to data, with a fallback value. author: realvishalrana -tags: javascript,data,utility +tags: data,prefix,postfix,format --- ```js @@ -11,8 +11,8 @@ const dataWithPrefix = (data, fallback = '-', prefix = '', postfix = '') => { }; // Usage: -console.log(dataWithPrefix('123', '-', '(', ')')); // Output: '(123)' -console.log(dataWithPrefix('', '-', '(', ')')); // Output: '-' -console.log(dataWithPrefix('Hello', 'N/A', 'Mr. ', '')); // Output: 'Mr. Hello' -console.log(dataWithPrefix(null, 'N/A', 'Mr. ', '')); // Output: 'N/A' +dataWithPrefix('123', '-', '(', ')'); // Returns: '(123)' +dataWithPrefix('', '-', '(', ')'); // Returns: '-' +dataWithPrefix('Hello', 'N/A', 'Mr. ', ''); // Returns: 'Mr. Hello' +dataWithPrefix(null, 'N/A', 'Mr. ', ''); // Returns: 'N/A' ``` diff --git a/snippets/javascript/string-manipulation/extract-initials-from-name.md b/snippets/javascript/string-manipulation/extract-initials-from-name.md index d782a152..da3a09e2 100644 --- a/snippets/javascript/string-manipulation/extract-initials-from-name.md +++ b/snippets/javascript/string-manipulation/extract-initials-from-name.md @@ -10,6 +10,6 @@ function getInitials(name) { return name.split(' ').map(part => part.charAt(0).toUpperCase()).join(''); } -// Example usage: -console.log(getInitials('John Doe')); // Output: 'JD' +// Usage: +getInitials('John Doe'); // Returns: 'JD' ``` diff --git a/snippets/javascript/string-manipulation/mask-sensitive-information.md b/snippets/javascript/string-manipulation/mask-sensitive-information.md index 28123404..bd0e2dde 100644 --- a/snippets/javascript/string-manipulation/mask-sensitive-information.md +++ b/snippets/javascript/string-manipulation/mask-sensitive-information.md @@ -10,7 +10,7 @@ function maskSensitiveInfo(str, visibleCount = 4, maskChar = '*') { return str.slice(0, visibleCount) + maskChar.repeat(Math.max(0, str.length - visibleCount)); } -// Example usage: -console.log(maskSensitiveInfo('123456789', 4)); // Output: '1234*****' -console.log(maskSensitiveInfo('example@mail.com', 2, '#')); // Output: 'ex#############' +// Usage: +maskSensitiveInfo('123456789', 4); // Returns: '1234*****' +maskSensitiveInfo('example@mail.com', 2, '#'); // Returns: 'ex#############' ``` diff --git a/snippets/javascript/string-manipulation/pad-string-on-both-sides.md b/snippets/javascript/string-manipulation/pad-string-on-both-sides.md index a8c4e359..2be57616 100644 --- a/snippets/javascript/string-manipulation/pad-string-on-both-sides.md +++ b/snippets/javascript/string-manipulation/pad-string-on-both-sides.md @@ -13,6 +13,6 @@ function padString(str, length, char = ' ') { return char.repeat(padStart) + str + char.repeat(padEnd); } -// Example usage: -console.log(padString('hello', 10, '*')); // Output: '**hello***' +// Usage: +padString('hello', 10, '*'); // Returns: '**hello***' ``` diff --git a/snippets/javascript/string-manipulation/random-string.md b/snippets/javascript/string-manipulation/random-string.md index 3512f04c..9c3a5cc1 100644 --- a/snippets/javascript/string-manipulation/random-string.md +++ b/snippets/javascript/string-manipulation/random-string.md @@ -2,7 +2,7 @@ title: Random string description: Generates a random string of characters of a certain length author: kruimol -tags: javascript,function,random +tags: function,random --- ```js @@ -10,5 +10,6 @@ function makeid(length, characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnop return Array.from({ length }, () => characters.charAt(Math.floor(Math.random() * characters.length))).join(''); } -console.log(makeid(5, "1234" /* (optional) */)); +makeid(3); // Returns: gDs (Random) +makeid(5, "1234" /* (optional) */); // Returns: "35453" (Random) ``` diff --git a/snippets/javascript/string-manipulation/remove-all-whitespace.md b/snippets/javascript/string-manipulation/remove-all-whitespace.md index 6c5c8f23..a24b6deb 100644 --- a/snippets/javascript/string-manipulation/remove-all-whitespace.md +++ b/snippets/javascript/string-manipulation/remove-all-whitespace.md @@ -2,7 +2,7 @@ title: Remove All Whitespace description: Removes all whitespace from a string. author: axorax -tags: javascript,string,whitespace +tags: string,whitespace --- ```js @@ -10,6 +10,6 @@ function removeWhitespace(str) { return str.replace(/\s+/g, ''); } -// Example usage: -console.log(removeWhitespace('Hello world!')); // Output: 'Helloworld!' +// Usage: +removeWhitespace('Hello world!'); // Returns: 'Helloworld!' ``` diff --git a/snippets/javascript/string-manipulation/remove-vowels-from-a-string.md b/snippets/javascript/string-manipulation/remove-vowels-from-a-string.md index 377017e6..49f15601 100644 --- a/snippets/javascript/string-manipulation/remove-vowels-from-a-string.md +++ b/snippets/javascript/string-manipulation/remove-vowels-from-a-string.md @@ -10,6 +10,6 @@ function removeVowels(str) { return str.replace(/[aeiouAEIOU]/g, ''); } -// Example usage: -console.log(removeVowels('Hello World')); // Output: 'Hll Wrld' +// Usage: +removeVowels('Hello World'); // Returns: 'Hll Wrld' ``` diff --git a/snippets/javascript/string-manipulation/reverse-string.md b/snippets/javascript/string-manipulation/reverse-string.md index 70a57428..73389b4b 100644 --- a/snippets/javascript/string-manipulation/reverse-string.md +++ b/snippets/javascript/string-manipulation/reverse-string.md @@ -2,12 +2,12 @@ title: Reverse String description: Reverses the characters in a string. author: dostonnabotov -tags: javascript,string,reverse,utility +tags: string,reverse --- ```js const reverseString = (str) => str.split('').reverse().join(''); // Usage: -console.log(reverseString('hello')); // Output: 'olleh' +reverseString('hello'); // Returns: 'olleh' ``` diff --git a/snippets/javascript/string-manipulation/slugify-string.md b/snippets/javascript/string-manipulation/slugify-string.md index 94471dc0..ddfcffa6 100644 --- a/snippets/javascript/string-manipulation/slugify-string.md +++ b/snippets/javascript/string-manipulation/slugify-string.md @@ -2,7 +2,7 @@ title: Slugify String description: Converts a string into a URL-friendly slug format. author: dostonnabotov -tags: javascript,string,slug,utility +tags: string,slug --- ```js @@ -20,6 +20,6 @@ const slugify = (string, separator = "-") => { // Usage: const title = "Hello, World! This is a Test."; -console.log(slugify(title)); // Output: 'hello-world-this-is-a-test' -console.log(slugify(title, "_")); // Output: 'hello_world_this_is_a_test' +slugify(title); // Returns: 'hello-world-this-is-a-test' +slugify(title, "_"); // Returns: 'hello_world_this_is_a_test' ``` diff --git a/snippets/javascript/string-manipulation/truncate-text.md b/snippets/javascript/string-manipulation/truncate-text.md index a216eb48..a66e6db3 100644 --- a/snippets/javascript/string-manipulation/truncate-text.md +++ b/snippets/javascript/string-manipulation/truncate-text.md @@ -2,7 +2,7 @@ title: Truncate Text description: Truncates the text to a maximum length and appends '...' if the text exceeds the maximum length. author: realvishalrana -tags: javascript,string,truncate,utility,text +tags: string,truncate,text --- ```js @@ -12,6 +12,6 @@ const truncateText = (text = '', maxLength = 50) => { // Usage: const title = "Hello, World! This is a Test."; -console.log(truncateText(title)); // Output: 'Hello, World! This is a Test.' -console.log(truncateText(title, 10)); // Output: 'Hello, Wor...' +truncateText(title); // Returns: 'Hello, World! This is a Test.' +truncateText(title, 10); // Returns: 'Hello, Wor...' ``` diff --git a/snippets/python/basics/hello-world.md b/snippets/python/basics/hello-world.md index 948370e3..0910bbb5 100644 --- a/snippets/python/basics/hello-world.md +++ b/snippets/python/basics/hello-world.md @@ -2,7 +2,7 @@ title: Hello, World! description: Prints Hello, World! to the terminal. author: James-Beans -tags: python,printing,hello-world,utility +tags: printing,hello-world --- ```py diff --git a/snippets/python/datetime-utilities/calculate-date-difference-in-milliseconds.md b/snippets/python/datetime-utilities/calculate-date-difference-in-milliseconds.md index 9daf08f3..a24139b5 100644 --- a/snippets/python/datetime-utilities/calculate-date-difference-in-milliseconds.md +++ b/snippets/python/datetime-utilities/calculate-date-difference-in-milliseconds.md @@ -2,7 +2,7 @@ title: Calculate Date Difference in Milliseconds description: Calculates the difference between two dates in milliseconds. author: e3nviction -tags: python,datetime,utility +tags: datetime,difference --- ```py @@ -15,5 +15,5 @@ def date_difference_in_millis(date1, date2): # Usage: d1 = datetime(2023, 1, 1, 12, 0, 0) d2 = datetime(2023, 1, 1, 12, 1, 0) -print(date_difference_in_millis(d1, d2)) +date_difference_in_millis(d1, d2) # Returns: 60000 ``` diff --git a/snippets/python/datetime-utilities/check-if-date-is-a-weekend.md b/snippets/python/datetime-utilities/check-if-date-is-a-weekend.md index 1e9fa63f..0bb1c80c 100644 --- a/snippets/python/datetime-utilities/check-if-date-is-a-weekend.md +++ b/snippets/python/datetime-utilities/check-if-date-is-a-weekend.md @@ -2,7 +2,7 @@ title: Check if Date is a Weekend description: Checks whether a given date falls on a weekend. author: axorax -tags: python,datetime,weekend,utility +tags: datetime,weekend --- ```py @@ -16,6 +16,5 @@ def is_weekend(date): # Usage: date = datetime(2023, 1, 1) -weekend = is_weekend(date) -print(weekend) # Output: True (Sunday) +is_weekend(date) # Returns: True (Sunday) ``` diff --git a/snippets/python/datetime-utilities/determine-day-of-the-week.md b/snippets/python/datetime-utilities/day-of-the-week-string.md similarity index 63% rename from snippets/python/datetime-utilities/determine-day-of-the-week.md rename to snippets/python/datetime-utilities/day-of-the-week-string.md index 4f1fa00d..3846602a 100644 --- a/snippets/python/datetime-utilities/determine-day-of-the-week.md +++ b/snippets/python/datetime-utilities/day-of-the-week-string.md @@ -1,8 +1,8 @@ --- -title: Determine Day of the Week -description: Calculates the day of the week for a given date. +title: Day of the Week String +description: Gets the string of the day of the week for a given date. author: axorax -tags: python,datetime,weekday,utility +tags: datetime,weekday --- ```py @@ -17,6 +17,5 @@ def get_day_of_week(date): # Usage: date = datetime(2023, 1, 1) -day = get_day_of_week(date) -print(day) # Output: 'Sunday' +get_day_of_week(date) # Returns: 'Sunday' ``` diff --git a/snippets/python/datetime-utilities/generate-date-range-list.md b/snippets/python/datetime-utilities/generate-date-range-list.md index 054591c8..2d92b00a 100644 --- a/snippets/python/datetime-utilities/generate-date-range-list.md +++ b/snippets/python/datetime-utilities/generate-date-range-list.md @@ -2,7 +2,7 @@ title: Generate Date Range List description: Generates a list of dates between two given dates. author: axorax -tags: python,datetime,range,utility +tags: datetime,range --- ```py @@ -26,5 +26,5 @@ end = datetime(2023, 1, 5) dates = generate_date_range(start, end) for d in dates: print(d.strftime('%Y-%m-%d')) -# Output: '2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05' +# Outputs: '2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05' ``` diff --git a/snippets/python/datetime-utilities/get-current-date-and-time-string.md b/snippets/python/datetime-utilities/get-current-date-and-time-as-string.md similarity index 63% rename from snippets/python/datetime-utilities/get-current-date-and-time-string.md rename to snippets/python/datetime-utilities/get-current-date-and-time-as-string.md index 683ece2d..6b56fe56 100644 --- a/snippets/python/datetime-utilities/get-current-date-and-time-string.md +++ b/snippets/python/datetime-utilities/get-current-date-and-time-as-string.md @@ -1,8 +1,8 @@ --- -title: Get Current Date and Time String +title: Get Current Date and Time as String description: Fetches the current date and time as a formatted string. author: e3nviction -tags: python,datetime,utility +tags: datetime,current,string --- ```py @@ -12,5 +12,5 @@ def get_current_datetime_string(): return datetime.now().strftime('%Y-%m-%d %H:%M:%S') # Usage: -print(get_current_datetime_string()) # Output: '2023-01-01 12:00:00' +get_current_datetime_string() # Returns: '2023-01-01 12:00:00' ``` diff --git a/snippets/python/datetime-utilities/get-number-of-days-in-a-month.md b/snippets/python/datetime-utilities/get-number-of-days-in-a-month.md index 85a0adf2..61fcb0f8 100644 --- a/snippets/python/datetime-utilities/get-number-of-days-in-a-month.md +++ b/snippets/python/datetime-utilities/get-number-of-days-in-a-month.md @@ -2,7 +2,7 @@ title: Get Number of Days in a Month description: Determines the number of days in a specific month and year. author: axorax -tags: python,datetime,calendar,utility +tags: datetime,calendar --- ```py @@ -16,6 +16,5 @@ def get_days_in_month(year, month): raise ValueError(f"Invalid month or year: {e}") # Usage: -days = get_days_in_month(2023, 2) -print(days) # Output: 28 (for non-leap year February) +get_days_in_month(2023, 2) # Returns: 28 (for non-leap year February) ``` diff --git a/snippets/python/utilities/measure-execution-time.md b/snippets/python/datetime-utilities/measure-execution-time.md similarity index 81% rename from snippets/python/utilities/measure-execution-time.md rename to snippets/python/datetime-utilities/measure-execution-time.md index 8ffdd291..d6301d34 100644 --- a/snippets/python/utilities/measure-execution-time.md +++ b/snippets/python/datetime-utilities/measure-execution-time.md @@ -2,7 +2,7 @@ title: Measure Execution Time description: Measures the execution time of a code block. author: dostonnabotov -tags: python,time,execution,utility +tags: time,execution --- ```py @@ -19,5 +19,5 @@ def measure_time(func, *args): def slow_function(): time.sleep(2) -measure_time(slow_function) +measure_time(slow_function) # Outputs an execution time of ~2s ``` diff --git a/snippets/python/error-handling/custom-exception-type.md b/snippets/python/error-handling/create-custom-exception-type.md similarity index 100% rename from snippets/python/error-handling/custom-exception-type.md rename to snippets/python/error-handling/create-custom-exception-type.md diff --git a/snippets/python/error-handling/handle-file-not-found-error.md b/snippets/python/error-handling/handle-file-not-found-error.md deleted file mode 100644 index f2cb9c6c..00000000 --- a/snippets/python/error-handling/handle-file-not-found-error.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: Handle File Not Found Error -description: Attempts to open a file and handles the case where the file does not exist. -author: axorax -tags: python,error-handling,file,utility ---- - -```py -def read_file_safe(filepath): - try: - with open(filepath, 'r') as file: - return file.read() - except FileNotFoundError: - return "File not found!" - -# Usage: -print(read_file_safe('nonexistent.txt')) # Output: 'File not found!' -``` diff --git a/snippets/python/error-handling/retry-function-execution-on-exception.md b/snippets/python/error-handling/retry-function-execution-on-exception.md index 47e60295..3dac2f56 100644 --- a/snippets/python/error-handling/retry-function-execution-on-exception.md +++ b/snippets/python/error-handling/retry-function-execution-on-exception.md @@ -2,7 +2,7 @@ title: Retry Function Execution on Exception description: Retries a function execution a specified number of times if it raises an exception. author: axorax -tags: python,error-handling,retry,utility +tags: error-handling,retry --- ```py diff --git a/snippets/python/error-handling/safe-division.md b/snippets/python/error-handling/safe-division.md deleted file mode 100644 index 256f6c97..00000000 --- a/snippets/python/error-handling/safe-division.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: Safe Division -description: Performs division with error handling. -author: e3nviction -tags: python,error-handling,division,utility ---- - -```py -def safe_divide(a, b): - try: - return a / b - except ZeroDivisionError: - return 'Cannot divide by zero!' - -# Usage: -print(safe_divide(10, 2)) # Output: 5.0 -print(safe_divide(10, 0)) # Output: 'Cannot divide by zero!' -``` diff --git a/snippets/python/error-handling/validate-input-with-exception-handling.md b/snippets/python/error-handling/validate-input-with-exception-handling.md deleted file mode 100644 index 19383917..00000000 --- a/snippets/python/error-handling/validate-input-with-exception-handling.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: Validate Input with Exception Handling -description: Validates user input and handles invalid input gracefully. -author: axorax -tags: python,error-handling,validation,utility ---- - -```py -def validate_positive_integer(input_value): - try: - value = int(input_value) - if value < 0: - raise ValueError("The number must be positive") - return value - except ValueError as e: - return f"Invalid input: {e}" - -# Usage: -print(validate_positive_integer('10')) # Output: 10 -print(validate_positive_integer('-5')) # Output: Invalid input: The number must be positive -print(validate_positive_integer('abc')) # Output: Invalid input: invalid literal for int() with base 10: 'abc' -``` diff --git a/snippets/python/file-handling/append-to-file.md b/snippets/python/file-handling/append-to-file.md deleted file mode 100644 index e370aed1..00000000 --- a/snippets/python/file-handling/append-to-file.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -title: Append to File -description: Appends content to the end of a file. -author: axorax -tags: python,file,append,utility ---- - -```py -def append_to_file(filepath, content): - with open(filepath, 'a') as file: - file.write(content + '\n') - -# Usage: -append_to_file('example.txt', 'This is an appended line.') -``` diff --git a/snippets/python/file-handling/check-if-file-exists.md b/snippets/python/file-handling/check-if-file-exists.md deleted file mode 100644 index c4ae48b9..00000000 --- a/snippets/python/file-handling/check-if-file-exists.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: Check if File Exists -description: Checks if a file exists at the specified path. -author: axorax -tags: python,file,exists,check,utility ---- - -```py -import os - -def file_exists(filepath): - return os.path.isfile(filepath) - -# Usage: -print(file_exists('example.txt')) # Output: True or False -``` diff --git a/snippets/python/file-handling/copy-file.md b/snippets/python/file-handling/copy-file.md deleted file mode 100644 index d2a8388f..00000000 --- a/snippets/python/file-handling/copy-file.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: Copy File -description: Copies a file from source to destination. -author: axorax -tags: python,file,copy,utility ---- - -```py -import shutil - -def copy_file(src, dest): - shutil.copy(src, dest) - -# Usage: -copy_file('example.txt', 'copy_of_example.txt') -``` diff --git a/snippets/python/file-handling/delete-file.md b/snippets/python/file-handling/delete-file.md deleted file mode 100644 index 7edb228c..00000000 --- a/snippets/python/file-handling/delete-file.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: Delete File -description: Deletes a file at the specified path. -author: axorax -tags: python,file,delete,utility ---- - -```py -import os - -def delete_file(filepath): - if os.path.exists(filepath): - os.remove(filepath) - print(f'File {filepath} deleted.') - else: - print(f'File {filepath} does not exist.') - -# Usage: -delete_file('example.txt') -``` diff --git a/snippets/python/file-handling/find-files.md b/snippets/python/file-handling/find-files.md index 3355c5cf..92b22972 100644 --- a/snippets/python/file-handling/find-files.md +++ b/snippets/python/file-handling/find-files.md @@ -2,7 +2,7 @@ title: Find Files description: Finds all files of the specified type within a given directory. author: Jackeastern -tags: python,os,filesystem,file_search +tags: os,filesystem,file_search --- ```py @@ -22,6 +22,5 @@ def find_files(directory, file_type): return found_files # Example Usage: -pdf_files = find_files('/path/to/your/directory', '.pdf') -print(pdf_files) +find_files('/path/to/your/directory', '.pdf') # Returns all .pdf in directory ``` diff --git a/snippets/python/file-handling/get-file-extension.md b/snippets/python/file-handling/get-file-extension.md index 84e1b849..2947eec2 100644 --- a/snippets/python/file-handling/get-file-extension.md +++ b/snippets/python/file-handling/get-file-extension.md @@ -2,7 +2,7 @@ title: Get File Extension description: Gets the extension of a file. author: axorax -tags: python,file,extension,utility +tags: file,extension --- ```py @@ -12,5 +12,5 @@ def get_file_extension(filepath): return os.path.splitext(filepath)[1] # Usage: -print(get_file_extension('example.txt')) # Output: '.txt' +get_file_extension('example.txt') # Returns: '.txt' ``` diff --git a/snippets/python/file-handling/list-files-in-directory.md b/snippets/python/file-handling/list-files-in-directory.md index 515a5ee0..40adf0ac 100644 --- a/snippets/python/file-handling/list-files-in-directory.md +++ b/snippets/python/file-handling/list-files-in-directory.md @@ -2,7 +2,7 @@ title: List Files in Directory description: Lists all files in a specified directory. author: axorax -tags: python,file,list,directory,utility +tags: file,list,directory --- ```py @@ -12,6 +12,5 @@ def list_files(directory): return [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))] # Usage: -files = list_files('/path/to/directory') -print(files) +list_files('/path/to/directory') # Returns: List of file in the directory ``` diff --git a/snippets/python/file-handling/read-file-in-chunks.md b/snippets/python/file-handling/read-file-in-chunks.md index ea876a23..44a8bd4f 100644 --- a/snippets/python/file-handling/read-file-in-chunks.md +++ b/snippets/python/file-handling/read-file-in-chunks.md @@ -2,7 +2,7 @@ title: Read File in Chunks description: Reads a file in chunks of a specified size. author: axorax -tags: python,file,read,chunks,utility +tags: file,read,chunks --- ```py @@ -13,5 +13,5 @@ def read_file_in_chunks(filepath, chunk_size): # Usage: for chunk in read_file_in_chunks('example.txt', 1024): - print(chunk) + print(chunk) # Outputs: Chucks of 1024 bytes ``` diff --git a/snippets/python/file-handling/read-file-lines.md b/snippets/python/file-handling/read-file-lines.md deleted file mode 100644 index 9ec68806..00000000 --- a/snippets/python/file-handling/read-file-lines.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: Read File Lines -description: Reads all lines from a file and returns them as a list. -author: dostonnabotov -tags: python,file,read,utility ---- - -```py -def read_file_lines(filepath): - with open(filepath, 'r') as file: - return file.readlines() - -# Usage: -lines = read_file_lines('example.txt') -print(lines) -``` diff --git a/snippets/python/file-handling/write-to-file.md b/snippets/python/file-handling/write-to-file.md deleted file mode 100644 index a9155260..00000000 --- a/snippets/python/file-handling/write-to-file.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -title: Write to File -description: Writes content to a file. -author: dostonnabotov -tags: python,file,write,utility ---- - -```py -def write_to_file(filepath, content): - with open(filepath, 'w') as file: - file.write(content) - -# Usage: -write_to_file('example.txt', 'Hello, World!') -``` diff --git a/snippets/python/json-manipulation/filter-json-data.md b/snippets/python/json-manipulation/filter-json-data.md index d087b762..79edafd6 100644 --- a/snippets/python/json-manipulation/filter-json-data.md +++ b/snippets/python/json-manipulation/filter-json-data.md @@ -2,7 +2,7 @@ title: Filter JSON Data description: Filters a JSON object based on a condition and returns the filtered data. author: axorax -tags: python,json,filter,data +tags: json,filter,data --- ```py @@ -19,6 +19,5 @@ def filter_json_data(filepath, condition): # Usage: condition = lambda x: x['age'] > 25 -filtered = filter_json_data('data.json', condition) -print(filtered) +filter_json_data('data.json', condition) # Returns: `data.json` filtered with `condition` ``` diff --git a/snippets/python/json-manipulation/flatten-nested-json.md b/snippets/python/json-manipulation/flatten-nested-json.md index 8cdb0dd6..3a1710ba 100644 --- a/snippets/python/json-manipulation/flatten-nested-json.md +++ b/snippets/python/json-manipulation/flatten-nested-json.md @@ -2,7 +2,7 @@ title: Flatten Nested JSON description: Flattens a nested JSON object into a flat dictionary. author: axorax -tags: python,json,flatten,nested +tags: json,flatten,nested --- ```py @@ -17,6 +17,5 @@ def flatten_json(nested_json, prefix=''): # Usage: nested_json = {'name': 'John', 'address': {'city': 'New York', 'zip': '10001'}} -flattened = flatten_json(nested_json) -print(flattened) # Output: {'name': 'John', 'address.city': 'New York', 'address.zip': '10001'} +flatten_json(nested_json) # Returns: {'name': 'John', 'address.city': 'New York', 'address.zip': '10001'} ``` diff --git a/snippets/python/json-manipulation/merge-multiple-json-files.md b/snippets/python/json-manipulation/merge-multiple-json-files.md index dc00e0e8..c32a3f46 100644 --- a/snippets/python/json-manipulation/merge-multiple-json-files.md +++ b/snippets/python/json-manipulation/merge-multiple-json-files.md @@ -2,7 +2,7 @@ title: Merge Multiple JSON Files description: Merges multiple JSON files into one and writes the merged data into a new file. author: axorax -tags: python,json,merge,file +tags: json,merge,file --- ```py diff --git a/snippets/python/json-manipulation/read-json-file.md b/snippets/python/json-manipulation/read-json-file.md index 8c9bf77c..e3db2285 100644 --- a/snippets/python/json-manipulation/read-json-file.md +++ b/snippets/python/json-manipulation/read-json-file.md @@ -2,7 +2,7 @@ title: Read JSON File description: Reads a JSON file and parses its content. author: e3nviction -tags: python,json,file,read +tags: json,file,read --- ```py @@ -13,6 +13,5 @@ def read_json(filepath): return json.load(file) # Usage: -data = read_json('data.json') -print(data) +read_json('data.json') # Returns: Content of file as dict ``` diff --git a/snippets/python/json-manipulation/update-json-file.md b/snippets/python/json-manipulation/update-json-file.md index 69a83672..c8b191a6 100644 --- a/snippets/python/json-manipulation/update-json-file.md +++ b/snippets/python/json-manipulation/update-json-file.md @@ -2,7 +2,7 @@ title: Update JSON File description: Updates an existing JSON file with new data or modifies the existing values. author: axorax -tags: python,json,update,file +tags: json,update,file --- ```py @@ -22,5 +22,5 @@ def update_json(filepath, new_data): # Usage: new_data = {'age': 31} -update_json('data.json', new_data) +update_json('data.json', new_data) # Updates `age` in `data.json` without modifying other keys ``` diff --git a/snippets/python/json-manipulation/validate-json-schema.md b/snippets/python/json-manipulation/validate-json-schema.md deleted file mode 100644 index d7dd4f7b..00000000 --- a/snippets/python/json-manipulation/validate-json-schema.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Validate JSON Schema -description: Validates a JSON object against a predefined schema. -author: axorax -tags: python,json,validation,schema ---- - -```py -import jsonschema -from jsonschema import validate - -def validate_json_schema(data, schema): - try: - validate(instance=data, schema=schema) - return True # Data is valid - except jsonschema.exceptions.ValidationError as err: - return False # Data is invalid - -# Usage: -schema = { - 'type': 'object', - 'properties': { - 'name': {'type': 'string'}, - 'age': {'type': 'integer'} - }, - 'required': ['name', 'age'] -} -data = {'name': 'John', 'age': 30} -is_valid = validate_json_schema(data, schema) -print(is_valid) # Output: True -``` diff --git a/snippets/python/json-manipulation/write-json-file.md b/snippets/python/json-manipulation/write-json-file.md index 624b856b..18a66b36 100644 --- a/snippets/python/json-manipulation/write-json-file.md +++ b/snippets/python/json-manipulation/write-json-file.md @@ -2,7 +2,7 @@ title: Write JSON File description: Writes a dictionary to a JSON file. author: e3nviction -tags: python,json,file,write +tags: json,file,write --- ```py diff --git a/snippets/python/list-manipulation/find-duplicates-in-a-list.md b/snippets/python/list-manipulation/find-duplicates-in-a-list.md index 9627fba8..3a38c97c 100644 --- a/snippets/python/list-manipulation/find-duplicates-in-a-list.md +++ b/snippets/python/list-manipulation/find-duplicates-in-a-list.md @@ -2,7 +2,7 @@ title: Find Duplicates in a List description: Identifies duplicate elements in a list. author: axorax -tags: python,list,duplicates,utility +tags: list,duplicates --- ```py @@ -18,5 +18,5 @@ def find_duplicates(lst): # Usage: data = [1, 2, 3, 2, 4, 5, 1] -print(find_duplicates(data)) # Output: [1, 2] +find_duplicates(data) # Returns: [1, 2] ``` diff --git a/snippets/python/list-manipulation/find-intersection-of-two-lists.md b/snippets/python/list-manipulation/find-intersection-of-two-lists.md index d3964090..1682db62 100644 --- a/snippets/python/list-manipulation/find-intersection-of-two-lists.md +++ b/snippets/python/list-manipulation/find-intersection-of-two-lists.md @@ -2,7 +2,7 @@ title: Find Intersection of Two Lists description: Finds the common elements between two lists. author: axorax -tags: python,list,intersection,utility +tags: list,intersection --- ```py @@ -12,5 +12,5 @@ def list_intersection(lst1, lst2): # Usage: list_a = [1, 2, 3, 4] list_b = [3, 4, 5, 6] -print(list_intersection(list_a, list_b)) # Output: [3, 4] +list_intersection(list_a, list_b) # Returns: [3, 4] ``` diff --git a/snippets/python/list-manipulation/find-maximum-difference-in-list.md b/snippets/python/list-manipulation/find-maximum-difference-in-list.md index 2173f3b9..776d6644 100644 --- a/snippets/python/list-manipulation/find-maximum-difference-in-list.md +++ b/snippets/python/list-manipulation/find-maximum-difference-in-list.md @@ -2,7 +2,7 @@ title: Find Maximum Difference in List description: Finds the maximum difference between any two elements in a list. author: axorax -tags: python,list,difference,utility +tags: list,difference --- ```py @@ -13,5 +13,5 @@ def max_difference(lst): # Usage: data = [10, 3, 5, 20, 7] -print(max_difference(data)) # Output: 17 +max_difference(data) # Returns: 17 ``` diff --git a/snippets/python/list-manipulation/flatten-nested-list.md b/snippets/python/list-manipulation/flatten-nested-list.md index 1cff2bec..b5d604d5 100644 --- a/snippets/python/list-manipulation/flatten-nested-list.md +++ b/snippets/python/list-manipulation/flatten-nested-list.md @@ -2,7 +2,7 @@ title: Flatten Nested List description: Flattens a multi-dimensional list into a single list. author: dostonnabotov -tags: python,list,flatten,utility +tags: list,flatten --- ```py @@ -11,5 +11,5 @@ def flatten_list(lst): # Usage: nested_list = [[1, 2], [3, 4], [5]] -print(flatten_list(nested_list)) # Output: [1, 2, 3, 4, 5] +flatten_list(nested_list) # Returns: [1, 2, 3, 4, 5] ``` diff --git a/snippets/python/list-manipulation/flatten-unevenly-nested-lists.md b/snippets/python/list-manipulation/flatten-unevenly-nested-lists.md index 87a13eb5..98bd1273 100644 --- a/snippets/python/list-manipulation/flatten-unevenly-nested-lists.md +++ b/snippets/python/list-manipulation/flatten-unevenly-nested-lists.md @@ -2,14 +2,11 @@ title: Flatten Unevenly Nested Lists description: Converts unevenly nested lists of any depth into a single flat list. author: agilarasu -tags: python,list,flattening,nested-lists,depth,utilities +tags: list,flattening,nested-lists,depth --- ```py def flatten(nested_list): - """ - Flattens unevenly nested lists of any depth into a single flat list. - """ for item in nested_list: if isinstance(item, list): yield from flatten(item) @@ -18,6 +15,5 @@ def flatten(nested_list): # Usage: nested_list = [1, [2, [3, 4]], 5] -flattened = list(flatten(nested_list)) -print(flattened) # Output: [1, 2, 3, 4, 5] +list(flatten(nested_list)) # Returns: [1, 2, 3, 4, 5] ``` diff --git a/snippets/python/list-manipulation/partition-list.md b/snippets/python/list-manipulation/partition-list.md index 5e4565b5..be2f832b 100644 --- a/snippets/python/list-manipulation/partition-list.md +++ b/snippets/python/list-manipulation/partition-list.md @@ -2,7 +2,7 @@ title: Partition List description: Partitions a list into sublists of a given size. author: axorax -tags: python,list,partition,utility +tags: list,partition --- ```py @@ -12,6 +12,5 @@ def partition_list(lst, size): # Usage: data = [1, 2, 3, 4, 5, 6, 7] -partitions = list(partition_list(data, 3)) -print(partitions) # Output: [[1, 2, 3], [4, 5, 6], [7]] +list(partition_list(data, 3)) # Returns: [[1, 2, 3], [4, 5, 6], [7]] ``` diff --git a/snippets/python/list-manipulation/remove-duplicates.md b/snippets/python/list-manipulation/remove-duplicates.md index 2b83961d..06ee4ebe 100644 --- a/snippets/python/list-manipulation/remove-duplicates.md +++ b/snippets/python/list-manipulation/remove-duplicates.md @@ -2,7 +2,7 @@ title: Remove Duplicates description: Removes duplicate elements from a list while maintaining order. author: dostonnabotov -tags: python,list,duplicates,utility +tags: list,duplicates,filter --- ```py @@ -10,5 +10,5 @@ def remove_duplicates(lst): return list(dict.fromkeys(lst)) # Usage: -print(remove_duplicates([1, 2, 2, 3, 4, 4, 5])) # Output: [1, 2, 3, 4, 5] +remove_duplicates([1, 2, 2, 3, 4, 4, 5]) # Returns: [1, 2, 3, 4, 5] ``` diff --git a/snippets/python/math-and-numbers/calculate-compound-interest.md b/snippets/python/math-and-numbers/calculate-compound-interest.md index 68df23b8..0685a678 100644 --- a/snippets/python/math-and-numbers/calculate-compound-interest.md +++ b/snippets/python/math-and-numbers/calculate-compound-interest.md @@ -10,6 +10,6 @@ def compound_interest(principal, rate, time, n=1): return principal * (1 + rate / n) ** (n * time) # Usage: -print(compound_interest(1000, 0.05, 5)) # Output: 1276.2815625000003 -print(compound_interest(1000, 0.05, 5, 12)) # Output: 1283.68 +compound_interest(1000, 0.05, 5) # Returns: 1276.2815625000003 +compound_interest(1000, 0.05, 5, 12) # Returns: 1283.68 ``` diff --git a/snippets/python/math-and-numbers/check-perfect-square.md b/snippets/python/math-and-numbers/check-perfect-square.md index 3cf91bc7..41395d71 100644 --- a/snippets/python/math-and-numbers/check-perfect-square.md +++ b/snippets/python/math-and-numbers/check-perfect-square.md @@ -2,7 +2,7 @@ title: Check Perfect Square description: Checks if a number is a perfect square. author: axorax -tags: python,math,perfect square,check +tags: math,perfect square,check --- ```py @@ -13,6 +13,6 @@ def is_perfect_square(n): return root * root == n # Usage: -print(is_perfect_square(16)) # Output: True -print(is_perfect_square(20)) # Output: False +is_perfect_square(16) # Returns: True +is_perfect_square(20) # Returns: False ``` diff --git a/snippets/python/math-and-numbers/check-prime-number.md b/snippets/python/math-and-numbers/check-prime-number.md index bbb4aa96..b0835bdd 100644 --- a/snippets/python/math-and-numbers/check-prime-number.md +++ b/snippets/python/math-and-numbers/check-prime-number.md @@ -2,7 +2,7 @@ title: Check Prime Number description: Checks if a number is a prime number. author: dostonnabotov -tags: python,math,prime,check +tags: math,prime,check --- ```py @@ -15,5 +15,5 @@ def is_prime(n): return True # Usage: -print(is_prime(17)) # Output: True +is_prime(17) # Returns: True ``` diff --git a/snippets/python/math-and-numbers/convert-binary-to-decimal.md b/snippets/python/math-and-numbers/convert-binary-to-decimal.md index 6abdfffa..6f1c4771 100644 --- a/snippets/python/math-and-numbers/convert-binary-to-decimal.md +++ b/snippets/python/math-and-numbers/convert-binary-to-decimal.md @@ -2,7 +2,7 @@ title: Convert Binary to Decimal description: Converts a binary string to its decimal equivalent. author: axorax -tags: python,math,binary,decimal,conversion +tags: math,binary,decimal,conversion --- ```py @@ -10,6 +10,6 @@ def binary_to_decimal(binary_str): return int(binary_str, 2) # Usage: -print(binary_to_decimal('1010')) # Output: 10 -print(binary_to_decimal('1101')) # Output: 13 +binary_to_decimal('1010') # Returns: 10 +binary_to_decimal('1101') # Returns: 13 ``` diff --git a/snippets/python/utilities/convert-bytes-to-human-readable-format.md b/snippets/python/math-and-numbers/convert-bytes-to-human-readable-format.md similarity index 76% rename from snippets/python/utilities/convert-bytes-to-human-readable-format.md rename to snippets/python/math-and-numbers/convert-bytes-to-human-readable-format.md index 08fc338e..96f5ddc7 100644 --- a/snippets/python/utilities/convert-bytes-to-human-readable-format.md +++ b/snippets/python/math-and-numbers/convert-bytes-to-human-readable-format.md @@ -2,7 +2,7 @@ title: Convert Bytes to Human-Readable Format description: Converts a size in bytes to a human-readable format. author: axorax -tags: python,bytes,format,utility +tags: bytes,format --- ```py @@ -13,5 +13,5 @@ def bytes_to_human_readable(num): num /= 1024 # Usage: -print(bytes_to_human_readable(123456789)) # Output: '117.74 MB' +bytes_to_human_readable(123456789) # Returns: '117.74 MB' ``` diff --git a/snippets/python/math-and-numbers/find-factorial.md b/snippets/python/math-and-numbers/find-factorial.md deleted file mode 100644 index 939e8fa6..00000000 --- a/snippets/python/math-and-numbers/find-factorial.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: Find Factorial -description: Calculates the factorial of a number. -author: dostonnabotov -tags: python,math,factorial,utility ---- - -```py -def factorial(n): - if n == 0: - return 1 - return n * factorial(n - 1) - -# Usage: -print(factorial(5)) # Output: 120 -``` diff --git a/snippets/python/math-and-numbers/find-lcm-least-common-multiple.md b/snippets/python/math-and-numbers/find-lcm-least-common-multiple.md index 31a44f5b..c749bf7f 100644 --- a/snippets/python/math-and-numbers/find-lcm-least-common-multiple.md +++ b/snippets/python/math-and-numbers/find-lcm-least-common-multiple.md @@ -10,6 +10,6 @@ def lcm(a, b): return abs(a * b) // gcd(a, b) # Usage: -print(lcm(12, 15)) # Output: 60 -print(lcm(7, 5)) # Output: 35 +lcm(12, 15) # Returns: 60 +lcm(7, 5) # Returns: 35 ``` diff --git a/snippets/python/math-and-numbers/solve-quadratic-equation.md b/snippets/python/math-and-numbers/solve-quadratic-equation.md index 2a66bf3e..e4d56263 100644 --- a/snippets/python/math-and-numbers/solve-quadratic-equation.md +++ b/snippets/python/math-and-numbers/solve-quadratic-equation.md @@ -2,7 +2,7 @@ title: Solve Quadratic Equation description: Solves a quadratic equation ax^2 + bx + c = 0 and returns the roots. author: axorax -tags: python,math,quadratic,equation,solver +tags: math,quadratic,equation,solver --- ```py @@ -15,6 +15,6 @@ def solve_quadratic(a, b, c): return root1, root2 # Usage: -print(solve_quadratic(1, -3, 2)) # Output: ((2+0j), (1+0j)) -print(solve_quadratic(1, 2, 5)) # Output: ((-1+2j), (-1-2j)) +solve_quadratic(1, -3, 2) # Returns: ((2+0j), (1+0j)) +solve_quadratic(1, 2, 5) # Returns: ((-1+2j), (-1-2j)) ``` diff --git a/snippets/python/sqlite-database/create-sqlite-database-table.md b/snippets/python/sqlite-database/create-sqlite-database-table.md index fef20041..be2da737 100644 --- a/snippets/python/sqlite-database/create-sqlite-database-table.md +++ b/snippets/python/sqlite-database/create-sqlite-database-table.md @@ -2,7 +2,7 @@ title: Create SQLite Database Table description: Creates a table in an SQLite database with a dynamic schema. author: e3nviction -tags: python,sqlite,database,table +tags: sqlite,database,table --- ```py diff --git a/snippets/python/sqlite-database/insert-data-into-sqlite-table.md b/snippets/python/sqlite-database/insert-data-into-sqlite-table.md index 3e8cb557..44c4e736 100644 --- a/snippets/python/sqlite-database/insert-data-into-sqlite-table.md +++ b/snippets/python/sqlite-database/insert-data-into-sqlite-table.md @@ -2,7 +2,7 @@ title: Insert Data into Sqlite Table description: Inserts a row into a specified SQLite table using a dictionary of fields and values. author: e3nviction -tags: python,sqlite,database,utility +tags: sqlite,database --- ```py diff --git a/snippets/python/sqlite-database/query-data-from-sqlite-table.md b/snippets/python/sqlite-database/query-data-from-sqlite-table.md index 95e4abab..4a06079e 100644 --- a/snippets/python/sqlite-database/query-data-from-sqlite-table.md +++ b/snippets/python/sqlite-database/query-data-from-sqlite-table.md @@ -2,7 +2,7 @@ title: Query Data from Sqlite Table description: Fetches data from a specified SQLite table, with options for selecting specific columns and applying a WHERE clause. author: pl44t -tags: python,sqlite,database,utility +tags: sqlite,database --- ```py diff --git a/snippets/python/sqlite-database/update-records-sqlite-table.md b/snippets/python/sqlite-database/update-records-in-sqlite-table.md similarity index 95% rename from snippets/python/sqlite-database/update-records-sqlite-table.md rename to snippets/python/sqlite-database/update-records-in-sqlite-table.md index 14104c8f..ffee4e87 100644 --- a/snippets/python/sqlite-database/update-records-sqlite-table.md +++ b/snippets/python/sqlite-database/update-records-in-sqlite-table.md @@ -2,7 +2,7 @@ title: Update Records in Sqlite Table description: Updates records in a specified SQLite table, allowing dynamic column updates and an optional WHERE clause. author: pl44t -tags: python,sqlite,database,utility +tags: sqlite,database --- ```py diff --git a/snippets/python/string-manipulation/capitalize-words.md b/snippets/python/string-manipulation/capitalize-words.md index e6acdcd4..ed55311d 100644 --- a/snippets/python/string-manipulation/capitalize-words.md +++ b/snippets/python/string-manipulation/capitalize-words.md @@ -2,7 +2,7 @@ title: Capitalize Words description: Capitalizes the first letter of each word in a string. author: axorax -tags: python,string,capitalize,utility +tags: string,capitalize --- ```py @@ -10,5 +10,5 @@ def capitalize_words(s): return ' '.join(word.capitalize() for word in s.split()) # Usage: -print(capitalize_words('hello world')) # Output: 'Hello World' +capitalize_words('hello world') # Returns: 'Hello World' ``` diff --git a/snippets/python/string-manipulation/check-anagram.md b/snippets/python/string-manipulation/check-anagram.md index 311c9c76..ddaa63b6 100644 --- a/snippets/python/string-manipulation/check-anagram.md +++ b/snippets/python/string-manipulation/check-anagram.md @@ -2,7 +2,7 @@ title: Check Anagram description: Checks if two strings are anagrams of each other. author: SteliosGee -tags: python,string,anagram,check,utility +tags: string,anagram,check --- ```py @@ -10,5 +10,5 @@ def is_anagram(s1, s2): return sorted(s1) == sorted(s2) # Usage: -print(is_anagram('listen', 'silent')) # Output: True +is_anagram('listen', 'silent') # Returns: True ``` diff --git a/snippets/python/string-manipulation/check-palindrome.md b/snippets/python/string-manipulation/check-palindrome.md index 08e30294..7cf1611e 100644 --- a/snippets/python/string-manipulation/check-palindrome.md +++ b/snippets/python/string-manipulation/check-palindrome.md @@ -2,7 +2,7 @@ title: Check Palindrome description: Checks if a string is a palindrome. author: dostonnabotov -tags: python,string,palindrome,utility +tags: string,palindrome --- ```py @@ -11,5 +11,5 @@ def is_palindrome(s): return s == s[::-1] # Usage: -print(is_palindrome('A man a plan a canal Panama')) # Output: True +is_palindrome('A man a plan a canal Panama') # Returns: True ``` diff --git a/snippets/python/string-manipulation/convert-snake-case-to-camel-case.md b/snippets/python/string-manipulation/convert-snake-case-to-camel-case.md index c3caf5e2..30956259 100644 --- a/snippets/python/string-manipulation/convert-snake-case-to-camel-case.md +++ b/snippets/python/string-manipulation/convert-snake-case-to-camel-case.md @@ -2,7 +2,7 @@ title: Convert Snake Case to Camel Case description: Converts a snake_case string to camelCase. author: axorax -tags: python,string,snake-case,camel-case,convert,utility +tags: string,snake-case,camel-case,convert --- ```py @@ -11,5 +11,5 @@ def snake_to_camel(s): return parts[0] + ''.join(word.capitalize() for word in parts[1:]) # Usage: -print(snake_to_camel('hello_world')) # Output: 'helloWorld' +snake_to_camel('hello_world') # Returns: 'helloWorld' ``` diff --git a/snippets/python/string-manipulation/convert-string-to-ascii.md b/snippets/python/string-manipulation/convert-string-to-ascii.md index 2af792d1..61e830ba 100644 --- a/snippets/python/string-manipulation/convert-string-to-ascii.md +++ b/snippets/python/string-manipulation/convert-string-to-ascii.md @@ -2,7 +2,7 @@ title: Convert String to ASCII description: Converts a string into its ASCII representation. author: axorax -tags: python,string,ascii,convert,utility +tags: string,ascii,convert --- ```py @@ -10,5 +10,5 @@ def string_to_ascii(s): return [ord(char) for char in s] # Usage: -print(string_to_ascii('hello')) # Output: [104, 101, 108, 108, 111] +string_to_ascii('hello') # Returns: [104, 101, 108, 108, 111] ``` diff --git a/snippets/python/string-manipulation/count-character-frequency.md b/snippets/python/string-manipulation/count-character-frequency.md index 8665eb67..ce8d8563 100644 --- a/snippets/python/string-manipulation/count-character-frequency.md +++ b/snippets/python/string-manipulation/count-character-frequency.md @@ -2,7 +2,7 @@ title: Count Character Frequency description: Counts the frequency of each character in a string. author: axorax -tags: python,string,character-frequency,utility +tags: string,character-frequency --- ```py @@ -12,5 +12,5 @@ def char_frequency(s): return dict(Counter(s)) # Usage: -print(char_frequency('hello')) # Output: {'h': 1, 'e': 1, 'l': 2, 'o': 1} +char_frequency('hello') # Returns: {'h': 1, 'e': 1, 'l': 2, 'o': 1} ``` diff --git a/snippets/python/string-manipulation/count-vowels.md b/snippets/python/string-manipulation/count-vowels.md index 3500ad6c..7dbcacab 100644 --- a/snippets/python/string-manipulation/count-vowels.md +++ b/snippets/python/string-manipulation/count-vowels.md @@ -2,7 +2,7 @@ title: Count Vowels description: Counts the number of vowels in a string. author: SteliosGee -tags: python,string,vowels,count,utility +tags: string,vowels,count --- ```py @@ -11,5 +11,5 @@ def count_vowels(s): return len([char for char in s.lower() if char in vowels]) # Usage: -print(count_vowels('hello')) # Output: 2 +count_vowels('hello') # Returns: 2 ``` diff --git a/snippets/python/string-manipulation/count-words.md b/snippets/python/string-manipulation/count-words.md index 301de052..60aeb369 100644 --- a/snippets/python/string-manipulation/count-words.md +++ b/snippets/python/string-manipulation/count-words.md @@ -2,7 +2,7 @@ title: Count Words description: Counts the number of words in a string. author: axorax -tags: python,string,word-count,utility +tags: string,word-count --- ```py @@ -10,5 +10,5 @@ def count_words(s): return len(s.split()) # Usage: -print(count_words('The quick brown fox')) # Output: 4 +count_words('The quick brown fox') # Returns: 4 ``` diff --git a/snippets/python/string-manipulation/find-all-substrings.md b/snippets/python/string-manipulation/find-all-substrings.md index be2c16ec..0148e356 100644 --- a/snippets/python/string-manipulation/find-all-substrings.md +++ b/snippets/python/string-manipulation/find-all-substrings.md @@ -2,7 +2,7 @@ title: Find All Substrings description: Finds all substrings of a given string. author: axorax -tags: python,string,substring,find,utility +tags: string,substring,find --- ```py @@ -14,5 +14,5 @@ def find_substrings(s): return substrings # Usage: -print(find_substrings('abc')) # Output: ['a', 'ab', 'abc', 'b', 'bc', 'c'] +find_substrings('abc') # Returns: ['a', 'ab', 'abc', 'b', 'bc', 'c'] ``` diff --git a/snippets/python/string-manipulation/find-longest-word.md b/snippets/python/string-manipulation/find-longest-word.md index aec61eea..2422b2c2 100644 --- a/snippets/python/string-manipulation/find-longest-word.md +++ b/snippets/python/string-manipulation/find-longest-word.md @@ -2,7 +2,7 @@ title: Find Longest Word description: Finds the longest word in a string. author: axorax -tags: python,string,longest-word,utility +tags: string,longest-word --- ```py @@ -11,5 +11,5 @@ def find_longest_word(s): return max(words, key=len) if words else '' # Usage: -print(find_longest_word('The quick brown fox')) # Output: 'quick' +find_longest_word('The quick brown fox') # Returns: 'quick' ``` diff --git a/snippets/python/string-manipulation/find-unique-characters.md b/snippets/python/string-manipulation/find-unique-characters.md index 8b6bd787..d6306254 100644 --- a/snippets/python/string-manipulation/find-unique-characters.md +++ b/snippets/python/string-manipulation/find-unique-characters.md @@ -2,7 +2,7 @@ title: Find Unique Characters description: Finds all unique characters in a string. author: axorax -tags: python,string,unique,characters,utility +tags: string,unique,characters --- ```py @@ -10,5 +10,5 @@ def find_unique_chars(s): return ''.join(sorted(set(s))) # Usage: -print(find_unique_chars('banana')) # Output: 'abn' +find_unique_chars('banana') # Results: 'abn' ``` diff --git a/snippets/python/utilities/generate-random-string.md b/snippets/python/string-manipulation/generate-random-string.md similarity index 77% rename from snippets/python/utilities/generate-random-string.md rename to snippets/python/string-manipulation/generate-random-string.md index b680cf49..a8dccdd5 100644 --- a/snippets/python/utilities/generate-random-string.md +++ b/snippets/python/string-manipulation/generate-random-string.md @@ -2,7 +2,7 @@ title: Generate Random String description: Generates a random alphanumeric string. author: dostonnabotov -tags: python,random,string,utility +tags: random,string --- ```py @@ -14,5 +14,5 @@ def random_string(length): return ''.join(random.choice(letters_and_digits) for _ in range(length)) # Usage: -print(random_string(10)) # Output: Random 10-character string +random_string(10) # Results: Random 10-character string ``` diff --git a/snippets/python/string-manipulation/remove-duplicate-characters.md b/snippets/python/string-manipulation/remove-duplicate-characters.md index 02ca422c..fda3d0a4 100644 --- a/snippets/python/string-manipulation/remove-duplicate-characters.md +++ b/snippets/python/string-manipulation/remove-duplicate-characters.md @@ -2,7 +2,7 @@ title: Remove Duplicate Characters description: Removes duplicate characters from a string while maintaining the order. author: axorax -tags: python,string,duplicates,remove,utility +tags: string,duplicates,remove --- ```py @@ -11,5 +11,5 @@ def remove_duplicate_chars(s): return ''.join(char for char in s if not (char in seen or seen.add(char))) # Usage: -print(remove_duplicate_chars('programming')) # Output: 'progamin' +remove_duplicate_chars('programming') # Returns: 'progamin' ``` diff --git a/snippets/python/string-manipulation/remove-punctuation.md b/snippets/python/string-manipulation/remove-punctuation.md index ad2616f5..301be4f7 100644 --- a/snippets/python/string-manipulation/remove-punctuation.md +++ b/snippets/python/string-manipulation/remove-punctuation.md @@ -2,7 +2,7 @@ title: Remove Punctuation description: Removes punctuation from a string. author: SteliosGee -tags: python,string,punctuation,remove,utility +tags: string,punctuation,remove --- ```py @@ -12,5 +12,5 @@ def remove_punctuation(s): return s.translate(str.maketrans('', '', string.punctuation)) # Usage: -print(remove_punctuation('Hello, World!')) # Output: 'Hello World' +remove_punctuation('Hello, World!') # Returns: 'Hello World' ``` diff --git a/snippets/python/string-manipulation/remove-specific-characters.md b/snippets/python/string-manipulation/remove-specific-characters.md index e686c299..3965ae9b 100644 --- a/snippets/python/string-manipulation/remove-specific-characters.md +++ b/snippets/python/string-manipulation/remove-specific-characters.md @@ -2,7 +2,7 @@ title: Remove Specific Characters description: Removes specific characters from a string. author: axorax -tags: python,string,remove,characters,utility +tags: string,remove,characters --- ```py @@ -10,5 +10,5 @@ def remove_chars(s, chars): return ''.join(c for c in s if c not in chars) # Usage: -print(remove_chars('hello world', 'eo')) # Output: 'hll wrld' +remove_chars('hello world', 'eo') # Returns: 'hll wrld' ``` diff --git a/snippets/python/string-manipulation/remove-whitespace.md b/snippets/python/string-manipulation/remove-whitespace.md index 34ed871d..c541a198 100644 --- a/snippets/python/string-manipulation/remove-whitespace.md +++ b/snippets/python/string-manipulation/remove-whitespace.md @@ -2,7 +2,7 @@ title: Remove Whitespace description: Removes all whitespace from a string. author: axorax -tags: python,string,whitespace,remove,utility +tags: string,whitespace,remove --- ```py @@ -10,5 +10,5 @@ def remove_whitespace(s): return ''.join(s.split()) # Usage: -print(remove_whitespace('hello world')) # Output: 'helloworld' +remove_whitespace('hello world') # Returns: 'helloworld' ``` diff --git a/snippets/python/string-manipulation/reverse-string.md b/snippets/python/string-manipulation/reverse-string.md index 2bfa2765..fa045607 100644 --- a/snippets/python/string-manipulation/reverse-string.md +++ b/snippets/python/string-manipulation/reverse-string.md @@ -2,7 +2,7 @@ title: Reverse String description: Reverses the characters in a string. author: dostonnabotov -tags: python,string,reverse,utility +tags: string,reverse --- ```py @@ -10,5 +10,5 @@ def reverse_string(s): return s[::-1] # Usage: -print(reverse_string('hello')) # Output: 'olleh' +reverse_string('hello') # Returns: 'olleh' ``` diff --git a/snippets/python/string-manipulation/split-camel-case.md b/snippets/python/string-manipulation/split-camel-case.md index b5561287..bb57c42d 100644 --- a/snippets/python/string-manipulation/split-camel-case.md +++ b/snippets/python/string-manipulation/split-camel-case.md @@ -2,7 +2,7 @@ title: Split Camel Case description: Splits a camel case string into separate words. author: axorax -tags: python,string,camel-case,split,utility +tags: string,camel-case,split --- ```py @@ -12,5 +12,5 @@ def split_camel_case(s): return ' '.join(re.findall(r'[A-Z][a-z]*|[a-z]+', s)) # Usage: -print(split_camel_case('camelCaseString')) # Output: 'camel Case String' +split_camel_case('camelCaseString') # Returns: 'camel Case String' ``` diff --git a/snippets/python/string-manipulation/truncate-string.md b/snippets/python/string-manipulation/truncate-string.md index e07b5f79..9788ac3e 100644 --- a/snippets/python/string-manipulation/truncate-string.md +++ b/snippets/python/string-manipulation/truncate-string.md @@ -2,7 +2,7 @@ title: Truncate String description: Truncates a string to a specified length and adds an ellipsis. author: axorax -tags: python,string,truncate,utility +tags: string,truncate --- ```py @@ -10,5 +10,5 @@ def truncate_string(s, length): return s[:length] + '...' if len(s) > length else s # Usage: -print(truncate_string('This is a long string', 10)) # Output: 'This is a ...' +truncate_string('This is a long string', 10) # Returns: 'This is a ...' ``` diff --git a/snippets/rust/basics/hello-world.md b/snippets/rust/basics/hello-world.md index da2502dd..334e93b6 100644 --- a/snippets/rust/basics/hello-world.md +++ b/snippets/rust/basics/hello-world.md @@ -2,7 +2,7 @@ title: Hello, World! description: Prints Hello, World! to the terminal. author: James-Beans -tags: rust,printing,hello-world,utility +tags: printing,hello-world --- ```rust diff --git a/snippets/rust/file-handling/find-files.md b/snippets/rust/file-handling/find-files.md index 2dfac208..1504d402 100644 --- a/snippets/rust/file-handling/find-files.md +++ b/snippets/rust/file-handling/find-files.md @@ -2,7 +2,7 @@ title: Find Files description: Finds all files of the specified extension within a given directory. author: Mathys-Gasnier -tags: rust,file,search +tags: file,search --- ```rust @@ -23,5 +23,5 @@ fn find_files(directory: &str, file_type: &str) -> std::io::Result std::io::Result> } // Usage: -let lines = read_lines("path/to/file.txt").expect("Failed to read lines from file") +read_lines("path/to/file.txt"); // Returns: If Ok(), a Vec of the lines of the file ``` diff --git a/snippets/rust/string-manipulation/capitalize-string.md b/snippets/rust/string-manipulation/capitalize-string.md index 1fc9a26b..d11431c4 100644 --- a/snippets/rust/string-manipulation/capitalize-string.md +++ b/snippets/rust/string-manipulation/capitalize-string.md @@ -2,7 +2,7 @@ title: Capitalize String description: Makes the first letter of a string uppercase. author: Mathys-Gasnier -tags: rust,string,capitalize,utility +tags: string,capitalize --- ```rust @@ -15,5 +15,5 @@ fn capitalized(str: &str) -> String { } // Usage: -assert_eq!(capitalized("lower_case"), "Lower_case") +capitalized("lower_case"); // Returns: Lower_case ``` diff --git a/snippets/scss/animations/fade-in-animation.md b/snippets/scss/animations/fade-in-animation.md index 029f6deb..a228653f 100644 --- a/snippets/scss/animations/fade-in-animation.md +++ b/snippets/scss/animations/fade-in-animation.md @@ -2,7 +2,7 @@ title: Fade In Animation description: Animates the fade-in effect. author: dostonnabotov -tags: scss,animation,fade,css +tags: animation,fade,css --- ```scss diff --git a/snippets/scss/animations/slide-in-from-left.md b/snippets/scss/animations/slide-in-from-left.md index decfc2dc..852d238c 100644 --- a/snippets/scss/animations/slide-in-from-left.md +++ b/snippets/scss/animations/slide-in-from-left.md @@ -2,7 +2,7 @@ title: Slide In From Left description: Animates content sliding in from the left. author: dostonnabotov -tags: scss,animation,slide,css +tags: animation,slide,css --- ```scss diff --git a/snippets/scss/borders-shadows/border-radius-helper.md b/snippets/scss/borders-shadows/border-radius-helper.md index a6cdcc2e..b90b8230 100644 --- a/snippets/scss/borders-shadows/border-radius-helper.md +++ b/snippets/scss/borders-shadows/border-radius-helper.md @@ -2,7 +2,7 @@ title: Border Radius Helper description: Applies a customizable border-radius. author: dostonnabotov -tags: scss,border,radius,css +tags: border,radius,css --- ```scss diff --git a/snippets/scss/borders-shadows/box-shadow-helper.md b/snippets/scss/borders-shadows/box-shadow-helper.md index dc33f1d5..c73ab292 100644 --- a/snippets/scss/borders-shadows/box-shadow-helper.md +++ b/snippets/scss/borders-shadows/box-shadow-helper.md @@ -2,7 +2,7 @@ title: Box Shadow Helper description: Generates a box shadow with customizable values. author: dostonnabotov -tags: scss,box-shadow,css,effects +tags: box-shadow,css,effects --- ```scss diff --git a/snippets/scss/components/primary-button.md b/snippets/scss/components/primary-button.md index 47dc6a4d..b945735d 100644 --- a/snippets/scss/components/primary-button.md +++ b/snippets/scss/components/primary-button.md @@ -2,7 +2,7 @@ title: Primary Button description: Generates a styled primary button. author: dostonnabotov -tags: scss,button,primary,css +tags: button,primary,css --- ```scss diff --git a/snippets/scss/layouts/aspect-ratio.md b/snippets/scss/layouts/aspect-ratio.md index ddd8d072..a99d14a2 100644 --- a/snippets/scss/layouts/aspect-ratio.md +++ b/snippets/scss/layouts/aspect-ratio.md @@ -2,7 +2,7 @@ title: Aspect Ratio description: Ensures that elements maintain a specific aspect ratio. author: dostonnabotov -tags: scss,aspect-ratio,layout,css +tags: aspect-ratio,layout,css --- ```scss diff --git a/snippets/scss/layouts/dark-theme.md b/snippets/scss/layouts/dark-theme.md index 418776c3..ecda0619 100644 --- a/snippets/scss/layouts/dark-theme.md +++ b/snippets/scss/layouts/dark-theme.md @@ -2,7 +2,7 @@ title: Dark Theme description: SCSS mixin to change styles for dark themes. author: gihanrangana -tags: scss, css, mixin, snippet, dark-theme, layout +tags: css, mixin, snippet, dark-theme, layout --- ```scss diff --git a/snippets/scss/layouts/flex-center.md b/snippets/scss/layouts/flex-center.md index c74908c6..a36ac106 100644 --- a/snippets/scss/layouts/flex-center.md +++ b/snippets/scss/layouts/flex-center.md @@ -2,7 +2,7 @@ title: Flex Center description: A mixin to center content using flexbox. author: dostonnabotov -tags: scss,flex,center,css +tags: flex,center,css --- ```scss diff --git a/snippets/scss/layouts/grid-container.md b/snippets/scss/layouts/grid-container.md index c11a4168..4febfe40 100644 --- a/snippets/scss/layouts/grid-container.md +++ b/snippets/scss/layouts/grid-container.md @@ -2,7 +2,7 @@ title: Grid Container description: Creates a responsive grid container with customizable column counts. author: dostonnabotov -tags: scss,grid,layout,css +tags: grid,layout,css --- ```scss diff --git a/snippets/scss/typography/font-import-helper.md b/snippets/scss/typography/font-import-helper.md index 4ad41181..fe10360e 100644 --- a/snippets/scss/typography/font-import-helper.md +++ b/snippets/scss/typography/font-import-helper.md @@ -2,7 +2,7 @@ title: Font Import Helper description: Simplifies importing custom fonts in Sass. author: dostonnabotov -tags: sass,mixin,fonts,css +tags: mixin,fonts,css --- ```scss diff --git a/snippets/scss/typography/line-clamp-mixin.md b/snippets/scss/typography/line-clamp-mixin.md index af48f1a8..fd0f2198 100644 --- a/snippets/scss/typography/line-clamp-mixin.md +++ b/snippets/scss/typography/line-clamp-mixin.md @@ -2,7 +2,7 @@ title: Line Clamp Mixin description: A Sass mixin to clamp text to a specific number of lines. author: dostonnabotov -tags: sass,mixin,typography,css +tags: mixin,typography,css --- ```scss diff --git a/snippets/scss/typography/text-gradient.md b/snippets/scss/typography/text-gradient.md index 91776580..f3369cb1 100644 --- a/snippets/scss/typography/text-gradient.md +++ b/snippets/scss/typography/text-gradient.md @@ -2,7 +2,7 @@ title: Text Gradient description: Adds a gradient color effect to text. author: dostonnabotov -tags: sass,mixin,gradient,text,css +tags: mixin,gradient,text,css --- ```scss diff --git a/snippets/scss/typography/text-overflow-ellipsis.md b/snippets/scss/typography/text-overflow-ellipsis.md index f5e75caf..bc47dc69 100644 --- a/snippets/scss/typography/text-overflow-ellipsis.md +++ b/snippets/scss/typography/text-overflow-ellipsis.md @@ -2,7 +2,7 @@ title: Text Overflow Ellipsis description: Ensures long text is truncated with an ellipsis. author: dostonnabotov -tags: sass,mixin,text,css +tags: mixin,text,css --- ```scss diff --git a/snippets/scss/utilities/clearfix.md b/snippets/scss/utilities/clearfix.md index 24285f82..32a599dd 100644 --- a/snippets/scss/utilities/clearfix.md +++ b/snippets/scss/utilities/clearfix.md @@ -2,7 +2,7 @@ title: Clearfix description: Provides a clearfix utility for floating elements. author: dostonnabotov -tags: scss,clearfix,utility,css +tags: clearfix,utility,css --- ```scss diff --git a/snippets/scss/utilities/responsive-breakpoints.md b/snippets/scss/utilities/responsive-breakpoints.md index 0a29e98e..dc0f2147 100644 --- a/snippets/scss/utilities/responsive-breakpoints.md +++ b/snippets/scss/utilities/responsive-breakpoints.md @@ -2,7 +2,7 @@ title: Responsive Breakpoints description: Generates media queries for responsive design. author: dostonnabotov -tags: scss,responsive,media-queries,css +tags: responsive,media-queries,css --- ```scss diff --git a/utils/snippetParser.js b/utils/snippetParser.js index e2ea33ad..0989ab5e 100644 --- a/utils/snippetParser.js +++ b/utils/snippetParser.js @@ -8,6 +8,17 @@ export function reverseSlugify(string, separator = "-") { .join(' ') .trim(); } +export function slugify(string, separator = "-") { + return string + .toString() // Cast to string (optional) + .toLowerCase() // Convert the string to lowercase letters + .trim() // Remove whitespace from both sides of a string (optional) + .replace(/\s+/g, separator) // Replace spaces with {separator} + .replace(/[^\w\-]+/g, "") // Remove all non-word chars + .replace(/\_/g, separator) // Replace _ with {separator} + .replace(/\-\-+/g, separator) // Replace multiple - with single {separator} + .replace(/\-$/g, ""); // Remove trailing - +} let errored = false; function raise(issue, snippet = '') { @@ -20,7 +31,7 @@ const crlfRegex = /\r\n/gm; const propertyRegex = /^\s+([a-zA-Z]+):\s*(.+)/; const headerEndCodeStartRegex = /^\s*---\s*```.*\n/; const codeRegex = /^(.+)```/s -function parseSnippet(snippetPath, text) { +function parseSnippet(snippetPath, name, text) { if(crlfRegex.exec(text) !== null) return raise('Found CRLF line endings instead of LF line endings', snippetPath); let cursor = 0; @@ -41,6 +52,8 @@ function parseSnippet(snippetPath, text) { if(!('author' in properties)) return raise(`Missing 'author' property`, snippetPath); if(!('tags' in properties)) return raise(`Missing 'tags' property`, snippetPath); + if(slugify(properties.title) !== name) return raise(`slugifyed 'title' property doesn't match snippet file name`, snippetPath); + match = headerEndCodeStartRegex.exec(fromCursor()); if(match === null) return raise('Missing header end \'---\' or code start \'```\'', snippetPath); cursor += match[0].length; @@ -82,8 +95,9 @@ export function parseAllSnippets() { for(const snippet of readdirSync(categoryPath)) { const snippetPath = join(categoryPath, snippet); const snippetContent = readFileSync(snippetPath).toString(); + const snippetFileName = snippet.slice(0, -3); - const snippetData = parseSnippet(snippetPath, snippetContent); + const snippetData = parseSnippet(snippetPath, snippetFileName, snippetContent); if(!snippetData) continue; categorySnippets.push(snippetData); }