From e41e1bcce576a43ed796ca435c7ba053dd88b933 Mon Sep 17 00:00:00 2001 From: Mathys-Gasnier Date: Wed, 1 Jan 2025 12:42:24 +0100 Subject: [PATCH 01/10] Adding scripts to migrate, check and consolidate snippets. --- public/icons/{html5.svg => html.svg} | 0 public/icons/{sass.svg => scss.svg} | 0 utils/checkSnippetFormatting.js | 6 ++ utils/consolidateSnippets.js | 28 ++++++++ utils/migrateSnippets.js | 57 ++++++++++++++++ utils/snippetParser.js | 97 ++++++++++++++++++++++++++++ 6 files changed, 188 insertions(+) rename public/icons/{html5.svg => html.svg} (100%) rename public/icons/{sass.svg => scss.svg} (100%) create mode 100644 utils/checkSnippetFormatting.js create mode 100644 utils/consolidateSnippets.js create mode 100644 utils/migrateSnippets.js create mode 100644 utils/snippetParser.js diff --git a/public/icons/html5.svg b/public/icons/html.svg similarity index 100% rename from public/icons/html5.svg rename to public/icons/html.svg diff --git a/public/icons/sass.svg b/public/icons/scss.svg similarity index 100% rename from public/icons/sass.svg rename to public/icons/scss.svg diff --git a/utils/checkSnippetFormatting.js b/utils/checkSnippetFormatting.js new file mode 100644 index 00000000..3aff9536 --- /dev/null +++ b/utils/checkSnippetFormatting.js @@ -0,0 +1,6 @@ +import { exit } from 'process'; +import { parseAllSnippets } from './snippetParser.js'; + +const [ errored ] = parseAllSnippets(); + +if(errored) exit(1); diff --git a/utils/consolidateSnippets.js b/utils/consolidateSnippets.js new file mode 100644 index 00000000..a55cf203 --- /dev/null +++ b/utils/consolidateSnippets.js @@ -0,0 +1,28 @@ +import { exit } from 'process'; +import { parseAllSnippets, reverseSlugify } from './snippetParser.js'; +import { join } from 'path'; +import { copyFileSync, writeFileSync } from 'fs'; + +const dataPath = 'public/data/'; +const indexPath = join(dataPath, '_index.json'); +const iconPath = 'public/icons/'; +const snippetsPath = 'snippets/'; + +const [ errored, snippets ] = parseAllSnippets(); + +if(errored) exit(1); + +const index = []; +for(const [language, categories] of Object.entries(snippets)) { + const languageIconPath = join(snippetsPath, language, 'icon.svg'); + + copyFileSync(languageIconPath, join(iconPath, `${language}.svg`)); + + index.push({ lang: reverseSlugify(language), icon: `/icons/${language}.svg` }); + + const languageFilePath = join(dataPath, `${language}.json`); + + writeFileSync(languageFilePath, JSON.stringify(categories, null, 4)); +} + +writeFileSync(indexPath, JSON.stringify(index, null, 4)); \ No newline at end of file diff --git a/utils/migrateSnippets.js b/utils/migrateSnippets.js new file mode 100644 index 00000000..8d43e1fb --- /dev/null +++ b/utils/migrateSnippets.js @@ -0,0 +1,57 @@ +import { copyFileSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'fs'; +import { join } from 'path'; + +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 - +} + +function formatSnippet(snippet) { + return `--- +Title: ${snippet.title} +Description: ${snippet.description} +Author: ${snippet.author} +Tags: ${snippet.tags} +--- + +\`\`\` +${snippet.code.join('\n')} +\`\`\` +`; +} + +const dataDir = "public/data"; +const iconsDir = "public/icons"; +const snippetDir = "snippets"; + +for (const file of readdirSync(dataDir)) { + if(!file.endsWith('.json') || file === '_index.json') continue; + + const languageName = file.slice(0, -5); + const content = JSON.parse(readFileSync(join(dataDir, file))); + const languagePath = join(snippetDir, languageName); + const iconPath = join(iconsDir, `${languageName}.svg`); + + mkdirSync(languagePath, { recursive: true }); + copyFileSync(iconPath, join(languagePath, 'icon.svg')); + + for (const category of content) { + if(category === 'icon.svg') continue; + const categoryPath = join(languagePath, slugify(category.categoryName)); + + mkdirSync(categoryPath, { recursive: true }); + + for(const snippet of category.snippets) { + const snippetPath = join(categoryPath, `${slugify(snippet.title)}.md`); + + writeFileSync(snippetPath, formatSnippet(snippet)); + } + } +} \ No newline at end of file diff --git a/utils/snippetParser.js b/utils/snippetParser.js new file mode 100644 index 00000000..0b704537 --- /dev/null +++ b/utils/snippetParser.js @@ -0,0 +1,97 @@ +import { existsSync, readdirSync, readFileSync } from 'fs'; +import { join } from 'path'; + +export function reverseSlugify(string, separator = "-") { + return string + .split(separator) + .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1)) + .join(' ') + .trim(); +} + +let errored = false; +function raise(issue, snippet = '') { + console.error(`${issue}${snippet ? ` in '${snippet}'` : ''}`); + errored = true; + return null; +} + +const propertyRegex = /^\s+([a-zA-Z]+): (.+)/; +const headerEndCodeStartRegex = /^\s+---\s+```.*\n/; +const codeRegex = /^(.+)```/s +function parseSnippet(snippetPath, text) { + let cursor = 0; + + const fromCursor = () => text.substring(cursor); + + if(!fromCursor().trim().startsWith('---')) return raise('Missing header start delimiter \'---\'', snippetPath); + cursor += 3; + + const properties = {}; + let match; + while((match = propertyRegex.exec(fromCursor())) !== null) { + cursor += match[0].length; + properties[match[1].toLowerCase()] = match[2]; + } + + if(!('title' in properties)) return raise(`Missing 'title' property`, snippetPath); + if(!('description' in properties)) return raise(`Missing 'description' property`, snippetPath); + if(!('author' in properties)) return raise(`Missing 'author' property`, snippetPath); + if(!('tags' in properties)) return raise(`Missing 'tags' property`, snippetPath); + + match = headerEndCodeStartRegex.exec(fromCursor()); + if(match === null) return raise('Missing header end \'---\' or code start \'```\'', snippetPath); + cursor += match[0].length; + + match = codeRegex.exec(fromCursor()); + if(match === null) return raise('Missing code block end \'```\'', snippetPath); + const code = match[1]; + + return { + title: properties.title, + description: properties.description, + author: properties.author, + tags: properties.tags.split(',').map((tag) => tag.trim()).filter((tag) => tag), + code: code, + } +} + +const snippetPath = "snippets/"; +export function parseAllSnippets() { + const snippets = {}; + + for(const language of readdirSync(snippetPath)) { + const languagePath = join(snippetPath, language); + + const languageIconPath = join(languagePath, 'icon.svg'); + + if(!existsSync(languageIconPath)) { + raise(`icon for '${language}' is missing`); + continue; + } + + const categories = []; + for(const category of readdirSync(languagePath)) { + if(category === 'icon.svg') continue; + const categoryPath = join(languagePath, category); + + const categorySnippets = []; + for(const snippet of readdirSync(categoryPath)) { + const snippetPath = join(categoryPath, snippet); + const snippetContent = readFileSync(snippetPath).toString(); + + const snippetData = parseSnippet(snippetPath, snippetContent); + if(!snippetData) continue; + categorySnippets.push(snippetData); + } + categories.push({ + categoryName: reverseSlugify(category), + snippets: categorySnippets, + }); + } + + snippets[language] = categories; + } + + return [ errored, snippets ]; +} From b1bcd0fe7aebb02f15367474a05886c81b235823 Mon Sep 17 00:00:00 2001 From: Mathys-Gasnier Date: Wed, 1 Jan 2025 12:43:03 +0100 Subject: [PATCH 02/10] Migrating snippets to the new format using `utils/migrateSnippets.js` --- snippets/c/basics/hello-world.md | 16 +++++ snippets/c/icon.svg | 15 +++++ .../factorial-function.md | 17 ++++++ .../mathematical-functions/power-function.md | 17 ++++++ snippets/cpp/basics/hello-world.md | 15 +++++ snippets/cpp/icon.svg | 10 +++ .../cpp/string-manipulation/reverse-string.md | 17 ++++++ .../cpp/string-manipulation/split-string.md | 23 +++++++ snippets/css/buttons/3d-button-effect.md | 23 +++++++ snippets/css/buttons/button-hover-effect.md | 22 +++++++ snippets/css/buttons/macos-button.md | 30 +++++++++ snippets/css/effects/blur-background.md | 13 ++++ snippets/css/effects/hover-glow-effect.md | 19 ++++++ snippets/css/icon.svg | 6 ++ snippets/css/layouts/css-reset.md | 14 +++++ snippets/css/layouts/equal-width-columns.md | 18 ++++++ snippets/css/layouts/grid-layout.md | 18 ++++++ snippets/css/layouts/responsive-design.md | 48 +++++++++++++++ snippets/css/layouts/sticky-footer.md | 18 ++++++ snippets/css/typography/letter-spacing.md | 12 ++++ .../css/typography/responsive-font-sizing.md | 12 ++++ .../grid-layout-with-navigation.md | 61 +++++++++++++++++++ .../sticky-header-footer-layout.md | 52 ++++++++++++++++ snippets/html/icon.svg | 8 +++ .../array-manipulation/flatten-array.md | 14 +++++ .../array-manipulation/remove-duplicates.md | 14 +++++ .../array-manipulation/shuffle-array.md | 15 +++++ .../array-manipulation/zip-arrays.md | 15 +++++ snippets/javascript/basics/hello-world.md | 10 +++ .../date-and-time/add-days-to-a-date.md | 18 ++++++ .../date-and-time/check-leap-year.md | 14 +++++ .../javascript/date-and-time/format-date.md | 13 ++++ .../date-and-time/get-current-timestamp.md | 13 ++++ .../date-and-time/get-day-of-the-year.md | 18 ++++++ .../date-and-time/get-days-in-month.md | 14 +++++ .../date-and-time/get-time-difference.md | 18 ++++++ .../date-and-time/relative-time-formatter.md | 36 +++++++++++ .../date-and-time/start-of-the-day.md | 14 +++++ .../dom-manipulation/change-element-style.md | 18 ++++++ .../dom-manipulation/get-element-position.md | 18 ++++++ .../dom-manipulation/remove-element.md | 18 ++++++ .../smooth-scroll-to-element.md | 16 +++++ .../dom-manipulation/toggle-class.md | 16 +++++ .../function-utilities/compose-functions.md | 18 ++++++ .../function-utilities/curry-function.md | 24 ++++++++ .../function-utilities/debounce-function.md | 20 ++++++ .../function-utilities/get-contrast-color.md | 26 ++++++++ .../function-utilities/memoize-function.md | 26 ++++++++ .../function-utilities/once-function.md | 23 +++++++ .../function-utilities/rate-limit-function.md | 28 +++++++++ .../repeat-function-invocation.md | 18 ++++++ .../function-utilities/sleep-function.md | 19 ++++++ .../function-utilities/throttle-function.md | 31 ++++++++++ snippets/javascript/icon.svg | 6 ++ .../local-storage/add-item-to-localstorage.md | 15 +++++ .../check-if-item-exists-in-localstorage.md | 15 +++++ .../local-storage/clear-all-localstorage.md | 15 +++++ .../retrieve-item-from-localstorage.md | 17 ++++++ .../convert-number-to-currency.md | 19 ++++++ .../convert-number-to-roman-numerals.md | 27 ++++++++ .../convert-to-scientific-notation.md | 27 ++++++++ .../format-number-with-commas.md | 17 ++++++ .../number-formatting/number-formatter.md | 23 +++++++ .../number-to-words-converter.md | 30 +++++++++ .../check-if-object-is-empty.md | 16 +++++ .../clone-object-shallowly.md | 17 ++++++ .../compare-two-objects-shallowly.md | 22 +++++++ .../convert-object-to-query-string.md | 18 ++++++ .../count-properties-in-object.md | 16 +++++ .../object-manipulation/filter-object.md | 27 ++++++++ .../flatten-nested-object.md | 24 ++++++++ .../object-manipulation/freeze-object.md | 18 ++++++ .../object-manipulation/get-nested-value.md | 19 ++++++ .../invert-object-keys-and-values.md | 18 ++++++ .../merge-objects-deeply.md | 26 ++++++++ .../omit-keys-from-object.md | 18 ++++++ .../pick-keys-from-object.md | 18 ++++++ .../object-manipulation/unique-by-key.md | 19 ++++++ .../regex-match-utility-function.md | 39 ++++++++++++ .../string-manipulation/capitalize-string.md | 13 ++++ .../check-if-string-is-a-palindrome.md | 16 +++++ .../convert-string-to-camel-case.md | 15 +++++ .../convert-string-to-param-case.md | 15 +++++ .../convert-string-to-pascal-case.md | 15 +++++ .../convert-string-to-snake-case.md | 17 ++++++ .../convert-string-to-title-case.md | 15 +++++ .../convert-tabs-to-spaces.md | 15 +++++ .../count-words-in-a-string.md | 15 +++++ .../string-manipulation/data-with-prefix.md | 18 ++++++ .../extract-initials-from-name.md | 15 +++++ .../mask-sensitive-information.md | 16 +++++ .../pad-string-on-both-sides.md | 18 ++++++ .../string-manipulation/random-string.md | 14 +++++ .../remove-all-whitespace.md | 15 +++++ .../remove-vowels-from-a-string.md | 15 +++++ .../string-manipulation/reverse-string.md | 13 ++++ .../string-manipulation/slugify-string.md | 25 ++++++++ .../string-manipulation/truncate-text.md | 17 ++++++ snippets/python/basics/hello-world.md | 10 +++ ...lculate-date-difference-in-milliseconds.md | 19 ++++++ .../check-if-date-is-a-weekend.md | 21 +++++++ .../determine-day-of-the-week.md | 22 +++++++ .../generate-date-range-list.md | 30 +++++++++ .../get-current-date-and-time-string.md | 16 +++++ .../get-number-of-days-in-a-month.md | 21 +++++++ .../handle-file-not-found-error.md | 18 ++++++ .../retry-function-execution-on-exception.md | 29 +++++++++ .../python/error-handling/safe-division.md | 18 ++++++ .../validate-input-with-exception-handling.md | 22 +++++++ .../python/file-handling/append-to-file.md | 15 +++++ .../file-handling/check-if-file-exists.md | 16 +++++ snippets/python/file-handling/copy-file.md | 16 +++++ snippets/python/file-handling/delete-file.md | 20 ++++++ snippets/python/file-handling/find-files.md | 27 ++++++++ .../file-handling/get-file-extension.md | 16 +++++ .../file-handling/list-files-in-directory.md | 17 ++++++ .../file-handling/read-file-in-chunks.md | 17 ++++++ .../python/file-handling/read-file-lines.md | 16 +++++ .../python/file-handling/write-to-file.md | 15 +++++ snippets/python/icon.svg | 21 +++++++ .../json-manipulation/filter-json-data.md | 24 ++++++++ .../json-manipulation/flatten-nested-json.md | 22 +++++++ .../merge-multiple-json-files.md | 27 ++++++++ .../json-manipulation/read-json-file.md | 18 ++++++ .../json-manipulation/update-json-file.md | 26 ++++++++ .../json-manipulation/validate-json-schema.md | 31 ++++++++++ .../json-manipulation/write-json-file.md | 18 ++++++ .../find-duplicates-in-a-list.md | 22 +++++++ .../find-intersection-of-two-lists.md | 16 +++++ .../find-maximum-difference-in-list.md | 17 ++++++ .../list-manipulation/flatten-nested-list.md | 15 +++++ .../flatten-unevenly-nested-lists.md | 23 +++++++ .../list-manipulation/partition-list.md | 17 ++++++ .../list-manipulation/remove-duplicates.md | 14 +++++ .../calculate-compound-interest.md | 15 +++++ .../math-and-numbers/check-perfect-square.md | 18 ++++++ .../math-and-numbers/check-prime-number.md | 19 ++++++ .../convert-binary-to-decimal.md | 15 +++++ .../python/math-and-numbers/find-factorial.md | 16 +++++ .../find-lcm-least-common-multiple.md | 15 +++++ .../solve-quadratic-equation.md | 20 ++++++ .../create-sqlite-database-table.md | 32 ++++++++++ .../insert-data-into-sqlite-table.md | 28 +++++++++ .../string-manipulation/capitalize-words.md | 14 +++++ .../string-manipulation/check-anagram.md | 14 +++++ .../string-manipulation/check-palindrome.md | 15 +++++ .../convert-snake-case-to-camel-case.md | 15 +++++ .../convert-string-to-ascii.md | 14 +++++ .../count-character-frequency.md | 16 +++++ .../string-manipulation/count-vowels.md | 15 +++++ .../python/string-manipulation/count-words.md | 14 +++++ .../find-all-substrings.md | 18 ++++++ .../string-manipulation/find-longest-word.md | 15 +++++ .../find-unique-characters.md | 14 +++++ .../remove-duplicate-characters.md | 15 +++++ .../string-manipulation/remove-punctuation.md | 16 +++++ .../remove-specific-characters.md | 14 +++++ .../string-manipulation/remove-whitespace.md | 14 +++++ .../string-manipulation/reverse-string.md | 14 +++++ .../string-manipulation/split-camel-case.md | 16 +++++ .../string-manipulation/truncate-string.md | 14 +++++ .../convert-bytes-to-human-readable-format.md | 17 ++++++ .../utilities/generate-random-string.md | 18 ++++++ .../utilities/measure-execution-time.md | 23 +++++++ snippets/rust/basics/hello-world.md | 12 ++++ snippets/rust/file-handling/find-files.md | 27 ++++++++ .../rust/file-handling/read-file-lines.md | 20 ++++++ snippets/rust/icon.svg | 9 +++ .../string-manipulation/capitalize-string.md | 19 ++++++ snippets/scss/animations/fade-in-animation.md | 21 +++++++ .../scss/animations/slide-in-from-left.md | 21 +++++++ .../borders-shadows/border-radius-helper.md | 12 ++++ .../scss/borders-shadows/box-shadow-helper.md | 12 ++++ snippets/scss/components/primary-button.md | 21 +++++++ snippets/scss/icon.svg | 5 ++ snippets/scss/layouts/aspect-ratio.md | 21 +++++++ snippets/scss/layouts/flex-center.md | 14 +++++ snippets/scss/layouts/grid-container.md | 14 +++++ .../scss/typography/font-import-helper.md | 18 ++++++ snippets/scss/typography/line-clamp-mixin.md | 15 +++++ snippets/scss/typography/text-gradient.md | 14 +++++ .../scss/typography/text-overflow-ellipsis.md | 14 +++++ snippets/scss/utilities/clearfix.md | 16 +++++ .../scss/utilities/responsive-breakpoints.md | 20 ++++++ 184 files changed, 3417 insertions(+) create mode 100644 snippets/c/basics/hello-world.md create mode 100644 snippets/c/icon.svg create mode 100644 snippets/c/mathematical-functions/factorial-function.md create mode 100644 snippets/c/mathematical-functions/power-function.md create mode 100644 snippets/cpp/basics/hello-world.md create mode 100644 snippets/cpp/icon.svg create mode 100644 snippets/cpp/string-manipulation/reverse-string.md create mode 100644 snippets/cpp/string-manipulation/split-string.md create mode 100644 snippets/css/buttons/3d-button-effect.md create mode 100644 snippets/css/buttons/button-hover-effect.md create mode 100644 snippets/css/buttons/macos-button.md create mode 100644 snippets/css/effects/blur-background.md create mode 100644 snippets/css/effects/hover-glow-effect.md create mode 100644 snippets/css/icon.svg create mode 100644 snippets/css/layouts/css-reset.md create mode 100644 snippets/css/layouts/equal-width-columns.md create mode 100644 snippets/css/layouts/grid-layout.md create mode 100644 snippets/css/layouts/responsive-design.md create mode 100644 snippets/css/layouts/sticky-footer.md create mode 100644 snippets/css/typography/letter-spacing.md create mode 100644 snippets/css/typography/responsive-font-sizing.md create mode 100644 snippets/html/basic-layouts/grid-layout-with-navigation.md create mode 100644 snippets/html/basic-layouts/sticky-header-footer-layout.md create mode 100644 snippets/html/icon.svg create mode 100644 snippets/javascript/array-manipulation/flatten-array.md create mode 100644 snippets/javascript/array-manipulation/remove-duplicates.md create mode 100644 snippets/javascript/array-manipulation/shuffle-array.md create mode 100644 snippets/javascript/array-manipulation/zip-arrays.md create mode 100644 snippets/javascript/basics/hello-world.md create mode 100644 snippets/javascript/date-and-time/add-days-to-a-date.md create mode 100644 snippets/javascript/date-and-time/check-leap-year.md create mode 100644 snippets/javascript/date-and-time/format-date.md create mode 100644 snippets/javascript/date-and-time/get-current-timestamp.md create mode 100644 snippets/javascript/date-and-time/get-day-of-the-year.md create mode 100644 snippets/javascript/date-and-time/get-days-in-month.md create mode 100644 snippets/javascript/date-and-time/get-time-difference.md create mode 100644 snippets/javascript/date-and-time/relative-time-formatter.md create mode 100644 snippets/javascript/date-and-time/start-of-the-day.md create mode 100644 snippets/javascript/dom-manipulation/change-element-style.md create mode 100644 snippets/javascript/dom-manipulation/get-element-position.md create mode 100644 snippets/javascript/dom-manipulation/remove-element.md create mode 100644 snippets/javascript/dom-manipulation/smooth-scroll-to-element.md create mode 100644 snippets/javascript/dom-manipulation/toggle-class.md create mode 100644 snippets/javascript/function-utilities/compose-functions.md create mode 100644 snippets/javascript/function-utilities/curry-function.md create mode 100644 snippets/javascript/function-utilities/debounce-function.md create mode 100644 snippets/javascript/function-utilities/get-contrast-color.md create mode 100644 snippets/javascript/function-utilities/memoize-function.md create mode 100644 snippets/javascript/function-utilities/once-function.md create mode 100644 snippets/javascript/function-utilities/rate-limit-function.md create mode 100644 snippets/javascript/function-utilities/repeat-function-invocation.md create mode 100644 snippets/javascript/function-utilities/sleep-function.md create mode 100644 snippets/javascript/function-utilities/throttle-function.md create mode 100644 snippets/javascript/icon.svg create mode 100644 snippets/javascript/local-storage/add-item-to-localstorage.md create mode 100644 snippets/javascript/local-storage/check-if-item-exists-in-localstorage.md create mode 100644 snippets/javascript/local-storage/clear-all-localstorage.md create mode 100644 snippets/javascript/local-storage/retrieve-item-from-localstorage.md create mode 100644 snippets/javascript/number-formatting/convert-number-to-currency.md create mode 100644 snippets/javascript/number-formatting/convert-number-to-roman-numerals.md create mode 100644 snippets/javascript/number-formatting/convert-to-scientific-notation.md create mode 100644 snippets/javascript/number-formatting/format-number-with-commas.md create mode 100644 snippets/javascript/number-formatting/number-formatter.md create mode 100644 snippets/javascript/number-formatting/number-to-words-converter.md create mode 100644 snippets/javascript/object-manipulation/check-if-object-is-empty.md create mode 100644 snippets/javascript/object-manipulation/clone-object-shallowly.md create mode 100644 snippets/javascript/object-manipulation/compare-two-objects-shallowly.md create mode 100644 snippets/javascript/object-manipulation/convert-object-to-query-string.md create mode 100644 snippets/javascript/object-manipulation/count-properties-in-object.md create mode 100644 snippets/javascript/object-manipulation/filter-object.md create mode 100644 snippets/javascript/object-manipulation/flatten-nested-object.md create mode 100644 snippets/javascript/object-manipulation/freeze-object.md create mode 100644 snippets/javascript/object-manipulation/get-nested-value.md create mode 100644 snippets/javascript/object-manipulation/invert-object-keys-and-values.md create mode 100644 snippets/javascript/object-manipulation/merge-objects-deeply.md create mode 100644 snippets/javascript/object-manipulation/omit-keys-from-object.md create mode 100644 snippets/javascript/object-manipulation/pick-keys-from-object.md create mode 100644 snippets/javascript/object-manipulation/unique-by-key.md create mode 100644 snippets/javascript/regular-expression/regex-match-utility-function.md create mode 100644 snippets/javascript/string-manipulation/capitalize-string.md create mode 100644 snippets/javascript/string-manipulation/check-if-string-is-a-palindrome.md create mode 100644 snippets/javascript/string-manipulation/convert-string-to-camel-case.md create mode 100644 snippets/javascript/string-manipulation/convert-string-to-param-case.md create mode 100644 snippets/javascript/string-manipulation/convert-string-to-pascal-case.md create mode 100644 snippets/javascript/string-manipulation/convert-string-to-snake-case.md create mode 100644 snippets/javascript/string-manipulation/convert-string-to-title-case.md create mode 100644 snippets/javascript/string-manipulation/convert-tabs-to-spaces.md create mode 100644 snippets/javascript/string-manipulation/count-words-in-a-string.md create mode 100644 snippets/javascript/string-manipulation/data-with-prefix.md create mode 100644 snippets/javascript/string-manipulation/extract-initials-from-name.md create mode 100644 snippets/javascript/string-manipulation/mask-sensitive-information.md create mode 100644 snippets/javascript/string-manipulation/pad-string-on-both-sides.md create mode 100644 snippets/javascript/string-manipulation/random-string.md create mode 100644 snippets/javascript/string-manipulation/remove-all-whitespace.md create mode 100644 snippets/javascript/string-manipulation/remove-vowels-from-a-string.md create mode 100644 snippets/javascript/string-manipulation/reverse-string.md create mode 100644 snippets/javascript/string-manipulation/slugify-string.md create mode 100644 snippets/javascript/string-manipulation/truncate-text.md create mode 100644 snippets/python/basics/hello-world.md create mode 100644 snippets/python/datetime-utilities/calculate-date-difference-in-milliseconds.md create mode 100644 snippets/python/datetime-utilities/check-if-date-is-a-weekend.md create mode 100644 snippets/python/datetime-utilities/determine-day-of-the-week.md create mode 100644 snippets/python/datetime-utilities/generate-date-range-list.md create mode 100644 snippets/python/datetime-utilities/get-current-date-and-time-string.md create mode 100644 snippets/python/datetime-utilities/get-number-of-days-in-a-month.md create mode 100644 snippets/python/error-handling/handle-file-not-found-error.md create mode 100644 snippets/python/error-handling/retry-function-execution-on-exception.md create mode 100644 snippets/python/error-handling/safe-division.md create mode 100644 snippets/python/error-handling/validate-input-with-exception-handling.md create mode 100644 snippets/python/file-handling/append-to-file.md create mode 100644 snippets/python/file-handling/check-if-file-exists.md create mode 100644 snippets/python/file-handling/copy-file.md create mode 100644 snippets/python/file-handling/delete-file.md create mode 100644 snippets/python/file-handling/find-files.md create mode 100644 snippets/python/file-handling/get-file-extension.md create mode 100644 snippets/python/file-handling/list-files-in-directory.md create mode 100644 snippets/python/file-handling/read-file-in-chunks.md create mode 100644 snippets/python/file-handling/read-file-lines.md create mode 100644 snippets/python/file-handling/write-to-file.md create mode 100644 snippets/python/icon.svg create mode 100644 snippets/python/json-manipulation/filter-json-data.md create mode 100644 snippets/python/json-manipulation/flatten-nested-json.md create mode 100644 snippets/python/json-manipulation/merge-multiple-json-files.md create mode 100644 snippets/python/json-manipulation/read-json-file.md create mode 100644 snippets/python/json-manipulation/update-json-file.md create mode 100644 snippets/python/json-manipulation/validate-json-schema.md create mode 100644 snippets/python/json-manipulation/write-json-file.md create mode 100644 snippets/python/list-manipulation/find-duplicates-in-a-list.md create mode 100644 snippets/python/list-manipulation/find-intersection-of-two-lists.md create mode 100644 snippets/python/list-manipulation/find-maximum-difference-in-list.md create mode 100644 snippets/python/list-manipulation/flatten-nested-list.md create mode 100644 snippets/python/list-manipulation/flatten-unevenly-nested-lists.md create mode 100644 snippets/python/list-manipulation/partition-list.md create mode 100644 snippets/python/list-manipulation/remove-duplicates.md create mode 100644 snippets/python/math-and-numbers/calculate-compound-interest.md create mode 100644 snippets/python/math-and-numbers/check-perfect-square.md create mode 100644 snippets/python/math-and-numbers/check-prime-number.md create mode 100644 snippets/python/math-and-numbers/convert-binary-to-decimal.md create mode 100644 snippets/python/math-and-numbers/find-factorial.md create mode 100644 snippets/python/math-and-numbers/find-lcm-least-common-multiple.md create mode 100644 snippets/python/math-and-numbers/solve-quadratic-equation.md create mode 100644 snippets/python/sqlite-database/create-sqlite-database-table.md create mode 100644 snippets/python/sqlite-database/insert-data-into-sqlite-table.md create mode 100644 snippets/python/string-manipulation/capitalize-words.md create mode 100644 snippets/python/string-manipulation/check-anagram.md create mode 100644 snippets/python/string-manipulation/check-palindrome.md create mode 100644 snippets/python/string-manipulation/convert-snake-case-to-camel-case.md create mode 100644 snippets/python/string-manipulation/convert-string-to-ascii.md create mode 100644 snippets/python/string-manipulation/count-character-frequency.md create mode 100644 snippets/python/string-manipulation/count-vowels.md create mode 100644 snippets/python/string-manipulation/count-words.md create mode 100644 snippets/python/string-manipulation/find-all-substrings.md create mode 100644 snippets/python/string-manipulation/find-longest-word.md create mode 100644 snippets/python/string-manipulation/find-unique-characters.md create mode 100644 snippets/python/string-manipulation/remove-duplicate-characters.md create mode 100644 snippets/python/string-manipulation/remove-punctuation.md create mode 100644 snippets/python/string-manipulation/remove-specific-characters.md create mode 100644 snippets/python/string-manipulation/remove-whitespace.md create mode 100644 snippets/python/string-manipulation/reverse-string.md create mode 100644 snippets/python/string-manipulation/split-camel-case.md create mode 100644 snippets/python/string-manipulation/truncate-string.md create mode 100644 snippets/python/utilities/convert-bytes-to-human-readable-format.md create mode 100644 snippets/python/utilities/generate-random-string.md create mode 100644 snippets/python/utilities/measure-execution-time.md create mode 100644 snippets/rust/basics/hello-world.md create mode 100644 snippets/rust/file-handling/find-files.md create mode 100644 snippets/rust/file-handling/read-file-lines.md create mode 100644 snippets/rust/icon.svg create mode 100644 snippets/rust/string-manipulation/capitalize-string.md create mode 100644 snippets/scss/animations/fade-in-animation.md create mode 100644 snippets/scss/animations/slide-in-from-left.md create mode 100644 snippets/scss/borders-shadows/border-radius-helper.md create mode 100644 snippets/scss/borders-shadows/box-shadow-helper.md create mode 100644 snippets/scss/components/primary-button.md create mode 100644 snippets/scss/icon.svg create mode 100644 snippets/scss/layouts/aspect-ratio.md create mode 100644 snippets/scss/layouts/flex-center.md create mode 100644 snippets/scss/layouts/grid-container.md create mode 100644 snippets/scss/typography/font-import-helper.md create mode 100644 snippets/scss/typography/line-clamp-mixin.md create mode 100644 snippets/scss/typography/text-gradient.md create mode 100644 snippets/scss/typography/text-overflow-ellipsis.md create mode 100644 snippets/scss/utilities/clearfix.md create mode 100644 snippets/scss/utilities/responsive-breakpoints.md diff --git a/snippets/c/basics/hello-world.md b/snippets/c/basics/hello-world.md new file mode 100644 index 00000000..59f95d6d --- /dev/null +++ b/snippets/c/basics/hello-world.md @@ -0,0 +1,16 @@ +--- +Title: Hello, World! +Description: Prints Hello, World! to the terminal. +Author: 0xHouss +Tags: c,printing,hello-world,utility +--- + +``` +#include // Includes the input/output library + +int main() { // Defines the main function + printf("Hello, World!\n") // Outputs Hello, World! and a newline + + return 0; // indicate the program executed successfully +} +``` diff --git a/snippets/c/icon.svg b/snippets/c/icon.svg new file mode 100644 index 00000000..94ebe6d9 --- /dev/null +++ b/snippets/c/icon.svg @@ -0,0 +1,15 @@ + + + + + + \ No newline at end of file diff --git a/snippets/c/mathematical-functions/factorial-function.md b/snippets/c/mathematical-functions/factorial-function.md new file mode 100644 index 00000000..c16b279a --- /dev/null +++ b/snippets/c/mathematical-functions/factorial-function.md @@ -0,0 +1,17 @@ +--- +Title: Factorial Function +Description: Calculates the factorial of a number. +Author: 0xHouss +Tags: c,math,factorial,utility +--- + +``` +int factorial(int x) { + int y = 1; + + for (int i = 2; i <= x; i++) + y *= i; + + return y; +} +``` diff --git a/snippets/c/mathematical-functions/power-function.md b/snippets/c/mathematical-functions/power-function.md new file mode 100644 index 00000000..d23f3224 --- /dev/null +++ b/snippets/c/mathematical-functions/power-function.md @@ -0,0 +1,17 @@ +--- +Title: Power Function +Description: Calculates the power of a number. +Author: 0xHouss +Tags: c,math,power,utility +--- + +``` +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 new file mode 100644 index 00000000..b44984d9 --- /dev/null +++ b/snippets/cpp/basics/hello-world.md @@ -0,0 +1,15 @@ +--- +Title: Hello, World! +Description: Prints Hello, World! to the terminal. +Author: James-Beans +Tags: cpp,printing,hello-world,utility +--- + +``` +#include // Includes the input/output stream library + +int main() { // Defines the main function + std::cout << "Hello, World!" << std::endl; // Outputs Hello, World! and a newline + return 0; // indicate the program executed successfully +} +``` diff --git a/snippets/cpp/icon.svg b/snippets/cpp/icon.svg new file mode 100644 index 00000000..7e75c38c --- /dev/null +++ b/snippets/cpp/icon.svg @@ -0,0 +1,10 @@ + +C++ logo +A two tone blue hexagon with the letters C++ inside in white + + + + + + + \ No newline at end of file diff --git a/snippets/cpp/string-manipulation/reverse-string.md b/snippets/cpp/string-manipulation/reverse-string.md new file mode 100644 index 00000000..e3fb1d95 --- /dev/null +++ b/snippets/cpp/string-manipulation/reverse-string.md @@ -0,0 +1,17 @@ +--- +Title: Reverse String +Description: Reverses the characters in a string. +Author: Vaibhav-kesarwani +Tags: cpp,array,reverse,utility +--- + +``` +#include +#include + +std::string reverseString(const std::string& input) { + std::string reversed = input; + std::reverse(reversed.begin(), reversed.end()); + return reversed; +} +``` diff --git a/snippets/cpp/string-manipulation/split-string.md b/snippets/cpp/string-manipulation/split-string.md new file mode 100644 index 00000000..c372b62c --- /dev/null +++ b/snippets/cpp/string-manipulation/split-string.md @@ -0,0 +1,23 @@ +--- +Title: Split String +Description: Splits a string by a delimiter +Author: saminjay +Tags: cpp,string,split,utility +--- + +``` +#include +#include + +std::vector split_string(std::string str, std::string delim) { + std::vector splits; + int i = 0, j; + int inc = delim.length(); + while (j != std::string::npos) { + j = str.find(delim, i); + splits.push_back(str.substr(i, j - i)); + i = j + inc; + } + return splits; +} +``` diff --git a/snippets/css/buttons/3d-button-effect.md b/snippets/css/buttons/3d-button-effect.md new file mode 100644 index 00000000..0d0e43cd --- /dev/null +++ b/snippets/css/buttons/3d-button-effect.md @@ -0,0 +1,23 @@ +--- +Title: 3D Button Effect +Description: Adds a 3D effect to a button when clicked. +Author: dostonnabotov +Tags: css,button,3D,effect +--- + +``` +.button { + background-color: #28a745; + color: white; + padding: 10px 20px; + border: none; + border-radius: 5px; + box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1); + transition: transform 0.1s; +} + +.button:active { + transform: translateY(2px); + box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1); +} +``` diff --git a/snippets/css/buttons/button-hover-effect.md b/snippets/css/buttons/button-hover-effect.md new file mode 100644 index 00000000..03757e30 --- /dev/null +++ b/snippets/css/buttons/button-hover-effect.md @@ -0,0 +1,22 @@ +--- +Title: Button Hover Effect +Description: Creates a hover effect with a color transition. +Author: dostonnabotov +Tags: css,button,hover,transition +--- + +``` +.button { + background-color: #007bff; + color: white; + padding: 10px 20px; + border: none; + border-radius: 5px; + cursor: pointer; + transition: background-color 0.3s ease; +} + +.button:hover { + background-color: #0056b3; +} +``` diff --git a/snippets/css/buttons/macos-button.md b/snippets/css/buttons/macos-button.md new file mode 100644 index 00000000..9e4b5d4c --- /dev/null +++ b/snippets/css/buttons/macos-button.md @@ -0,0 +1,30 @@ +--- +Title: MacOS Button +Description: A macOS-like button style, with hover and shading effects. +Author: e3nviction +Tags: css,button,macos,hover,transition +--- + +``` +.button { + font: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica,; + background: #0a85ff; + color: #fff; + padding: 8px 12px; + border: none; + margin: 4px; + border-radius: 10px; + cursor: pointer; + box-shadow: inset 0 1px 1px #fff2, 0px 2px 3px -2px rgba(0, 0, 0, 0.3) !important; /*This is really performance heavy*/ + font-size: 14px; + display: flex; + align-items: center; + justify-content: center; + text-decoration: none; + transition: all 150ms cubic-bezier(0.175, 0.885, 0.32, 1.275); +} +.button:hover { + background: #0974ee; + color: #fff +} +``` diff --git a/snippets/css/effects/blur-background.md b/snippets/css/effects/blur-background.md new file mode 100644 index 00000000..0a1567d0 --- /dev/null +++ b/snippets/css/effects/blur-background.md @@ -0,0 +1,13 @@ +--- +Title: Blur Background +Description: Applies a blur effect to the background of an element. +Author: dostonnabotov +Tags: css,blur,background,effects +--- + +``` +.blur-background { + backdrop-filter: blur(10px); + background: rgba(255, 255, 255, 0.5); +} +``` diff --git a/snippets/css/effects/hover-glow-effect.md b/snippets/css/effects/hover-glow-effect.md new file mode 100644 index 00000000..f07e7db9 --- /dev/null +++ b/snippets/css/effects/hover-glow-effect.md @@ -0,0 +1,19 @@ +--- +Title: Hover Glow Effect +Description: Adds a glowing effect on hover. +Author: dostonnabotov +Tags: css,hover,glow,effects +--- + +``` +.glow { + background-color: #f39c12; + padding: 10px 20px; + border-radius: 5px; + transition: box-shadow 0.3s ease; +} + +.glow:hover { + box-shadow: 0 0 15px rgba(243, 156, 18, 0.8); +} +``` diff --git a/snippets/css/icon.svg b/snippets/css/icon.svg new file mode 100644 index 00000000..c981c7ac --- /dev/null +++ b/snippets/css/icon.svg @@ -0,0 +1,6 @@ + +CSS Logo Square +A purple square with the letters CSS inside in white + + + \ No newline at end of file diff --git a/snippets/css/layouts/css-reset.md b/snippets/css/layouts/css-reset.md new file mode 100644 index 00000000..019a25b2 --- /dev/null +++ b/snippets/css/layouts/css-reset.md @@ -0,0 +1,14 @@ +--- +Title: CSS Reset +Description: Resets some default browser styles, ensuring consistency across browsers. +Author: AmeerMoustafa +Tags: css,reset,browser,layout +--- + +``` +* { + margin: 0; + padding: 0; + box-sizing: border-box +} +``` diff --git a/snippets/css/layouts/equal-width-columns.md b/snippets/css/layouts/equal-width-columns.md new file mode 100644 index 00000000..0d5c8d93 --- /dev/null +++ b/snippets/css/layouts/equal-width-columns.md @@ -0,0 +1,18 @@ +--- +Title: Equal-Width Columns +Description: Creates columns with equal widths using flexbox. +Author: dostonnabotov +Tags: css,flexbox,columns,layout +--- + +``` +.columns { + display: flex; + justify-content: space-between; +} + +.column { + flex: 1; + margin: 0 10px; +} +``` diff --git a/snippets/css/layouts/grid-layout.md b/snippets/css/layouts/grid-layout.md new file mode 100644 index 00000000..2b0d434d --- /dev/null +++ b/snippets/css/layouts/grid-layout.md @@ -0,0 +1,18 @@ +--- +Title: Grid layout +Description: Equal sized items in a responsive grid +Author: xshubhamg +Tags: css,layout,grid +--- + +``` +.grid-container { + display: grid + grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); +/* Explanation: +- `auto-fit`: Automatically fits as many columns as possible within the container. +- `minmax(250px, 1fr)`: Defines a minimum column size of 250px and a maximum size of 1fr (fraction of available space). +*/ +} + +``` diff --git a/snippets/css/layouts/responsive-design.md b/snippets/css/layouts/responsive-design.md new file mode 100644 index 00000000..b5ca5605 --- /dev/null +++ b/snippets/css/layouts/responsive-design.md @@ -0,0 +1,48 @@ +--- +Title: Responsive Design +Description: The different responsive breakpoints. +Author: kruimol +Tags: css,responsive +--- + +``` +/* Phone */ +.element { + margin: 0 10% +} + +/* Tablet */ +@media (min-width: 640px) { + .element { + margin: 0 20% + } +} + +/* Desktop base */ +@media (min-width: 768px) { + .element { + margin: 0 30% + } +} + +/* Desktop large */ +@media (min-width: 1024px) { + .element { + margin: 0 40% + } +} + +/* Desktop extra large */ +@media (min-width: 1280px) { + .element { + margin: 0 60% + } +} + +/* Desktop bige */ +@media (min-width: 1536px) { + .element { + margin: 0 80% + } +} +``` diff --git a/snippets/css/layouts/sticky-footer.md b/snippets/css/layouts/sticky-footer.md new file mode 100644 index 00000000..e387754c --- /dev/null +++ b/snippets/css/layouts/sticky-footer.md @@ -0,0 +1,18 @@ +--- +Title: Sticky Footer +Description: Ensures the footer always stays at the bottom of the page. +Author: dostonnabotov +Tags: css,layout,footer,sticky +--- + +``` +body { + display: flex; + flex-direction: column; + min-height: 100vh; +} + +footer { + margin-top: auto; +} +``` diff --git a/snippets/css/typography/letter-spacing.md b/snippets/css/typography/letter-spacing.md new file mode 100644 index 00000000..1a68eb6e --- /dev/null +++ b/snippets/css/typography/letter-spacing.md @@ -0,0 +1,12 @@ +--- +Title: Letter Spacing +Description: Adds space between letters for better readability. +Author: dostonnabotov +Tags: css,typography,spacing +--- + +``` +p { + letter-spacing: 0.05em; +} +``` diff --git a/snippets/css/typography/responsive-font-sizing.md b/snippets/css/typography/responsive-font-sizing.md new file mode 100644 index 00000000..e67bc53d --- /dev/null +++ b/snippets/css/typography/responsive-font-sizing.md @@ -0,0 +1,12 @@ +--- +Title: Responsive Font Sizing +Description: Adjusts font size based on viewport width. +Author: dostonnabotov +Tags: css,font,responsive,typography +--- + +``` +h1 { + font-size: calc(1.5rem + 2vw); +} +``` diff --git a/snippets/html/basic-layouts/grid-layout-with-navigation.md b/snippets/html/basic-layouts/grid-layout-with-navigation.md new file mode 100644 index 00000000..06568e25 --- /dev/null +++ b/snippets/html/basic-layouts/grid-layout-with-navigation.md @@ -0,0 +1,61 @@ +--- +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 +--- + +``` + + + + + + +
+ Header + +
+
Main Content
+ + + +``` diff --git a/snippets/html/basic-layouts/sticky-header-footer-layout.md b/snippets/html/basic-layouts/sticky-header-footer-layout.md new file mode 100644 index 00000000..4a9d1b87 --- /dev/null +++ b/snippets/html/basic-layouts/sticky-header-footer-layout.md @@ -0,0 +1,52 @@ +--- +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 +--- + +``` + + + + + + +
header
+
body/content
+ + + +``` diff --git a/snippets/html/icon.svg b/snippets/html/icon.svg new file mode 100644 index 00000000..59345ce4 --- /dev/null +++ b/snippets/html/icon.svg @@ -0,0 +1,8 @@ + +HTML5 Logo +A two tone orange shield with a white number 5 in it + + + + + \ No newline at end of file diff --git a/snippets/javascript/array-manipulation/flatten-array.md b/snippets/javascript/array-manipulation/flatten-array.md new file mode 100644 index 00000000..0845a975 --- /dev/null +++ b/snippets/javascript/array-manipulation/flatten-array.md @@ -0,0 +1,14 @@ +--- +Title: Flatten Array +Description: Flattens a multi-dimensional array. +Author: dostonnabotov +Tags: javascript,array,flatten,utility +--- + +``` +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/remove-duplicates.md b/snippets/javascript/array-manipulation/remove-duplicates.md new file mode 100644 index 00000000..91f28a99 --- /dev/null +++ b/snippets/javascript/array-manipulation/remove-duplicates.md @@ -0,0 +1,14 @@ +--- +Title: Remove Duplicates +Description: Removes duplicate values from an array. +Author: dostonnabotov +Tags: javascript,array,deduplicate,utility +--- + +``` +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] +``` diff --git a/snippets/javascript/array-manipulation/shuffle-array.md b/snippets/javascript/array-manipulation/shuffle-array.md new file mode 100644 index 00000000..aaeecc68 --- /dev/null +++ b/snippets/javascript/array-manipulation/shuffle-array.md @@ -0,0 +1,15 @@ +--- +Title: Shuffle Array +Description: Shuffles an Array. +Author: loxt-nixo +Tags: javascript,array,shuffle,utility +--- + +``` +function shuffleArray(array) { + for (let i = array.length - 1; i >= 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [array[i], array[j]] = [array[j], array[i]]; + } +} +``` diff --git a/snippets/javascript/array-manipulation/zip-arrays.md b/snippets/javascript/array-manipulation/zip-arrays.md new file mode 100644 index 00000000..0f3893e5 --- /dev/null +++ b/snippets/javascript/array-manipulation/zip-arrays.md @@ -0,0 +1,15 @@ +--- +Title: Zip Arrays +Description: Combines two arrays by pairing corresponding elements from each array. +Author: Swaraj-Singh-30 +Tags: javascript,array,utility,map +--- + +``` +const zip = (arr1, arr2) => arr1.map((value, index) => [value, arr2[index]]); + +// Usage: +const arr1 = ['a', 'b', 'c']; +const arr2 = [1, 2, 3]; +console.log(zip(arr1, arr2)); // Output: [['a', 1], ['b', 2], ['c', 3]] +``` diff --git a/snippets/javascript/basics/hello-world.md b/snippets/javascript/basics/hello-world.md new file mode 100644 index 00000000..b435818d --- /dev/null +++ b/snippets/javascript/basics/hello-world.md @@ -0,0 +1,10 @@ +--- +Title: Hello, World! +Description: Prints Hello, World! to the terminal. +Author: James-Beans +Tags: javascript,printing,hello-world,utility +--- + +``` +console.log("Hello, World!"); // Prints Hello, World! to the console +``` 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 new file mode 100644 index 00000000..12220ccd --- /dev/null +++ b/snippets/javascript/date-and-time/add-days-to-a-date.md @@ -0,0 +1,18 @@ +--- +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 +--- + +``` +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 new file mode 100644 index 00000000..cafcbaca --- /dev/null +++ b/snippets/javascript/date-and-time/check-leap-year.md @@ -0,0 +1,14 @@ +--- +Title: Check Leap Year +Description: Determines if a given year is a leap year. +Author: axorax +Tags: javascript,date,leap-year,utility +--- + +``` +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 +``` diff --git a/snippets/javascript/date-and-time/format-date.md b/snippets/javascript/date-and-time/format-date.md new file mode 100644 index 00000000..c7d2a76a --- /dev/null +++ b/snippets/javascript/date-and-time/format-date.md @@ -0,0 +1,13 @@ +--- +Title: Format Date +Description: Formats a date in 'YYYY-MM-DD' format. +Author: dostonnabotov +Tags: javascript,date,format,utility +--- + +``` +const formatDate = (date) => date.toISOString().split('T')[0]; + +// Usage: +console.log(formatDate(new Date())); // Output: '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 new file mode 100644 index 00000000..fcb627c0 --- /dev/null +++ b/snippets/javascript/date-and-time/get-current-timestamp.md @@ -0,0 +1,13 @@ +--- +Title: Get Current Timestamp +Description: Retrieves the current timestamp in milliseconds since January 1, 1970. +Author: axorax +Tags: javascript,date,timestamp,utility +--- + +``` +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 new file mode 100644 index 00000000..a3f7a86d --- /dev/null +++ b/snippets/javascript/date-and-time/get-day-of-the-year.md @@ -0,0 +1,18 @@ +--- +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 +--- + +``` +const getDayOfYear = (date) => { + const startOfYear = new Date(date.getFullYear(), 0, 0); + const diff = date - startOfYear + (startOfYear.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000; + return Math.floor(diff / (1000 * 60 * 60 * 24)); +}; + +// Usage: +const today = new Date('2024-12-31'); +console.log(getDayOfYear(today)); // Output: 366 (in a 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 new file mode 100644 index 00000000..096e5fec --- /dev/null +++ b/snippets/javascript/date-and-time/get-days-in-month.md @@ -0,0 +1,14 @@ +--- +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 +--- + +``` +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 +``` diff --git a/snippets/javascript/date-and-time/get-time-difference.md b/snippets/javascript/date-and-time/get-time-difference.md new file mode 100644 index 00000000..64b26192 --- /dev/null +++ b/snippets/javascript/date-and-time/get-time-difference.md @@ -0,0 +1,18 @@ +--- +Title: Get Time Difference +Description: Calculates the time difference in days between two dates. +Author: dostonnabotov +Tags: javascript,date,time-difference,utility +--- + +``` +const getTimeDifference = (date1, date2) => { + const diff = Math.abs(date2 - date1); + return Math.ceil(diff / (1000 * 60 * 60 * 24)); +}; + +// Usage: +const date1 = new Date('2024-01-01'); +const date2 = new Date('2024-12-31'); +console.log(getTimeDifference(date1, date2)); // Output: 365 +``` diff --git a/snippets/javascript/date-and-time/relative-time-formatter.md b/snippets/javascript/date-and-time/relative-time-formatter.md new file mode 100644 index 00000000..5a6b41b3 --- /dev/null +++ b/snippets/javascript/date-and-time/relative-time-formatter.md @@ -0,0 +1,36 @@ +--- +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 +--- + +``` +const getRelativeTime = (date) => { + const now = Date.now(); + const diff = date.getTime() - now; + const seconds = Math.abs(Math.floor(diff / 1000)); + const minutes = Math.abs(Math.floor(seconds / 60)); + const hours = Math.abs(Math.floor(minutes / 60)); + const days = Math.abs(Math.floor(hours / 24)); + const years = Math.abs(Math.floor(days / 365)); + + if (Math.abs(diff) < 1000) return 'just now'; + + const isFuture = diff > 0; + + if (years > 0) return `${isFuture ? 'in ' : ''}${years} ${years === 1 ? 'year' : 'years'}${isFuture ? '' : ' ago'}`; + if (days > 0) return `${isFuture ? 'in ' : ''}${days} ${days === 1 ? 'day' : 'days'}${isFuture ? '' : ' ago'}`; + if (hours > 0) return `${isFuture ? 'in ' : ''}${hours} ${hours === 1 ? 'hour' : 'hours'}${isFuture ? '' : ' ago'}`; + if (minutes > 0) return `${isFuture ? 'in ' : ''}${minutes} ${minutes === 1 ? 'minute' : 'minutes'}${isFuture ? '' : ' ago'}`; + + return `${isFuture ? 'in ' : ''}${seconds} ${seconds === 1 ? 'second' : 'seconds'}${isFuture ? '' : ' ago'}`; +} + +// 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 +``` diff --git a/snippets/javascript/date-and-time/start-of-the-day.md b/snippets/javascript/date-and-time/start-of-the-day.md new file mode 100644 index 00000000..157fc0f1 --- /dev/null +++ b/snippets/javascript/date-and-time/start-of-the-day.md @@ -0,0 +1,14 @@ +--- +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 +--- + +``` +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 +``` diff --git a/snippets/javascript/dom-manipulation/change-element-style.md b/snippets/javascript/dom-manipulation/change-element-style.md new file mode 100644 index 00000000..70759421 --- /dev/null +++ b/snippets/javascript/dom-manipulation/change-element-style.md @@ -0,0 +1,18 @@ +--- +Title: Change Element Style +Description: Changes the inline style of an element. +Author: axorax +Tags: javascript,dom,style,utility +--- + +``` +const changeElementStyle = (element, styleObj) => { + Object.entries(styleObj).forEach(([property, value]) => { + element.style[property] = value; + }); +}; + +// Usage: +const element = document.querySelector('.my-element'); +changeElementStyle(element, { color: 'red', backgroundColor: 'yellow' }); +``` diff --git a/snippets/javascript/dom-manipulation/get-element-position.md b/snippets/javascript/dom-manipulation/get-element-position.md new file mode 100644 index 00000000..23ae0b8c --- /dev/null +++ b/snippets/javascript/dom-manipulation/get-element-position.md @@ -0,0 +1,18 @@ +--- +Title: Get Element Position +Description: Gets the position of an element relative to the viewport. +Author: axorax +Tags: javascript,dom,position,utility +--- + +``` +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 new file mode 100644 index 00000000..d59f4dbe --- /dev/null +++ b/snippets/javascript/dom-manipulation/remove-element.md @@ -0,0 +1,18 @@ +--- +Title: Remove Element +Description: Removes a specified element from the DOM. +Author: axorax +Tags: javascript,dom,remove,utility +--- + +``` +const removeElement = (element) => { + if (element && element.parentNode) { + element.parentNode.removeChild(element); + } +}; + +// Usage: +const element = document.querySelector('.my-element'); +removeElement(element); +``` diff --git a/snippets/javascript/dom-manipulation/smooth-scroll-to-element.md b/snippets/javascript/dom-manipulation/smooth-scroll-to-element.md new file mode 100644 index 00000000..c66bbd84 --- /dev/null +++ b/snippets/javascript/dom-manipulation/smooth-scroll-to-element.md @@ -0,0 +1,16 @@ +--- +Title: Smooth Scroll to Element +Description: Scrolls smoothly to a specified element. +Author: dostonnabotov +Tags: javascript,dom,scroll,ui +--- + +``` +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 new file mode 100644 index 00000000..abb28985 --- /dev/null +++ b/snippets/javascript/dom-manipulation/toggle-class.md @@ -0,0 +1,16 @@ +--- +Title: Toggle Class +Description: Toggles a class on an element. +Author: dostonnabotov +Tags: javascript,dom,class,utility +--- + +``` +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 new file mode 100644 index 00000000..e061777c --- /dev/null +++ b/snippets/javascript/function-utilities/compose-functions.md @@ -0,0 +1,18 @@ +--- +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 +--- + +``` +const compose = (...funcs) => (initialValue) => { + return funcs.reduce((acc, func) => func(acc), initialValue); +}; + +// Usage: +const add2 = (x) => x + 2; +const multiply3 = (x) => x * 3; +const composed = compose(multiply3, add2); +console.log(composed(5)); // Output: 21 ((5 + 2) * 3) +``` diff --git a/snippets/javascript/function-utilities/curry-function.md b/snippets/javascript/function-utilities/curry-function.md new file mode 100644 index 00000000..762605dc --- /dev/null +++ b/snippets/javascript/function-utilities/curry-function.md @@ -0,0 +1,24 @@ +--- +Title: Curry Function +Description: Transforms a function into its curried form. +Author: axorax +Tags: javascript,curry,function,utility +--- + +``` +const curry = (func) => { + const curried = (...args) => { + if (args.length >= func.length) { + return func(...args); + } + return (...nextArgs) => curried(...args, ...nextArgs); + }; + return curried; +}; + +// 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 +``` diff --git a/snippets/javascript/function-utilities/debounce-function.md b/snippets/javascript/function-utilities/debounce-function.md new file mode 100644 index 00000000..361b4360 --- /dev/null +++ b/snippets/javascript/function-utilities/debounce-function.md @@ -0,0 +1,20 @@ +--- +Title: Debounce Function +Description: Delays a function execution until after a specified time. +Author: dostonnabotov +Tags: javascript,utility,debounce,performance +--- + +``` +const debounce = (func, delay) => { + let timeout; + + return (...args) => { + clearTimeout(timeout); + timeout = setTimeout(() => func(...args), delay); + }; +}; + +// Usage: +window.addEventListener('resize', debounce(() => console.log('Resized!'), 500)); +``` diff --git a/snippets/javascript/function-utilities/get-contrast-color.md b/snippets/javascript/function-utilities/get-contrast-color.md new file mode 100644 index 00000000..057ae383 --- /dev/null +++ b/snippets/javascript/function-utilities/get-contrast-color.md @@ -0,0 +1,26 @@ +--- +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 +--- + +``` +const getContrastColor = (hexColor) => { + // Expand short hex color to full format + if (hexColor.length === 4) { + hexColor = `#${hexColor[1]}${hexColor[1]}${hexColor[2]}${hexColor[2]}${hexColor[3]}${hexColor[3]}`; + } + const r = parseInt(hexColor.slice(1, 3), 16); + const g = parseInt(hexColor.slice(3, 5), 16); + const b = parseInt(hexColor.slice(5, 7), 16); + const brightness = (r * 299 + g * 587 + b * 114) / 1000; + return brightness >= 128 ? "#000000" : "#FFFFFF"; +}; + +// 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) +``` diff --git a/snippets/javascript/function-utilities/memoize-function.md b/snippets/javascript/function-utilities/memoize-function.md new file mode 100644 index 00000000..c30a5888 --- /dev/null +++ b/snippets/javascript/function-utilities/memoize-function.md @@ -0,0 +1,26 @@ +--- +Title: Memoize Function +Description: Caches the result of a function based on its arguments to improve performance. +Author: axorax +Tags: javascript,memoization,optimization,utility +--- + +``` +const memoize = (func) => { + const cache = new Map(); + return (...args) => { + const key = JSON.stringify(args); + if (cache.has(key)) { + return cache.get(key); + } + const result = func(...args); + cache.set(key, result); + return result; + }; +}; + +// 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) +``` diff --git a/snippets/javascript/function-utilities/once-function.md b/snippets/javascript/function-utilities/once-function.md new file mode 100644 index 00000000..2e2e6714 --- /dev/null +++ b/snippets/javascript/function-utilities/once-function.md @@ -0,0 +1,23 @@ +--- +Title: Once Function +Description: Ensures a function is only called once. +Author: axorax +Tags: javascript,function,once,utility +--- + +``` +const once = (func) => { + let called = false; + return (...args) => { + if (!called) { + called = true; + return func(...args); + } + }; +}; + +// Usage: +const initialize = once(() => console.log('Initialized!')); +initialize(); // Output: Initialized! +initialize(); // No output +``` diff --git a/snippets/javascript/function-utilities/rate-limit-function.md b/snippets/javascript/function-utilities/rate-limit-function.md new file mode 100644 index 00000000..2fc61d96 --- /dev/null +++ b/snippets/javascript/function-utilities/rate-limit-function.md @@ -0,0 +1,28 @@ +--- +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 +--- + +``` +const rateLimit = (func, limit, timeWindow) => { + let queue = []; + setInterval(() => { + if (queue.length) { + const next = queue.shift(); + func(...next.args); + } + }, timeWindow); + return (...args) => { + if (queue.length < limit) { + queue.push({ args }); + } + }; +}; + +// Usage: +const fetchData = () => console.log('Fetching data...'); +const rateLimitedFetch = rateLimit(fetchData, 2, 1000); +setInterval(() => rateLimitedFetch(), 200); // Only calls fetchData twice every second +``` diff --git a/snippets/javascript/function-utilities/repeat-function-invocation.md b/snippets/javascript/function-utilities/repeat-function-invocation.md new file mode 100644 index 00000000..36bb0e92 --- /dev/null +++ b/snippets/javascript/function-utilities/repeat-function-invocation.md @@ -0,0 +1,18 @@ +--- +Title: Repeat Function Invocation +Description: Invokes a function a specified number of times. +Author: dostonnabotov +Tags: javascript,function,repeat,utility +--- + +``` +const times = (func, n) => { + Array.from(Array(n)).forEach(() => { + func(); + }); +}; + +// Usage: +const randomFunction = () => console.log('Function called!'); +times(randomFunction, 3); // Logs 'Function called!' three times +``` diff --git a/snippets/javascript/function-utilities/sleep-function.md b/snippets/javascript/function-utilities/sleep-function.md new file mode 100644 index 00000000..120d2410 --- /dev/null +++ b/snippets/javascript/function-utilities/sleep-function.md @@ -0,0 +1,19 @@ +--- +Title: Sleep Function +Description: Waits for a specified amount of milliseconds before resolving. +Author: 0xHouss +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(); +``` diff --git a/snippets/javascript/function-utilities/throttle-function.md b/snippets/javascript/function-utilities/throttle-function.md new file mode 100644 index 00000000..37229cc7 --- /dev/null +++ b/snippets/javascript/function-utilities/throttle-function.md @@ -0,0 +1,31 @@ +--- +Title: Throttle Function +Description: Limits a function execution to once every specified time interval. +Author: dostonnabotov +Tags: javascript,utility,throttle,performance +--- + +``` +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/icon.svg b/snippets/javascript/icon.svg new file mode 100644 index 00000000..25ccdbaa --- /dev/null +++ b/snippets/javascript/icon.svg @@ -0,0 +1,6 @@ + +JS Logo Square +A yellow square with the letters JS inside in white + + + diff --git a/snippets/javascript/local-storage/add-item-to-localstorage.md b/snippets/javascript/local-storage/add-item-to-localstorage.md new file mode 100644 index 00000000..c0b9799e --- /dev/null +++ b/snippets/javascript/local-storage/add-item-to-localstorage.md @@ -0,0 +1,15 @@ +--- +Title: Add Item to localStorage +Description: Stores a value in localStorage under the given key. +Author: dostonnabotov +Tags: javascript,localStorage,storage,utility +--- + +``` +const addToLocalStorage = (key, value) => { + localStorage.setItem(key, JSON.stringify(value)); +}; + +// Usage: +addToLocalStorage('user', { name: 'John', age: 30 }); +``` 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 new file mode 100644 index 00000000..25dd1287 --- /dev/null +++ b/snippets/javascript/local-storage/check-if-item-exists-in-localstorage.md @@ -0,0 +1,15 @@ +--- +Title: Check if Item Exists in localStorage +Description: Checks if a specific item exists in localStorage. +Author: axorax +Tags: javascript,localStorage,storage,utility +--- + +``` +const isItemInLocalStorage = (key) => { + return localStorage.getItem(key) !== null; +}; + +// Usage: +console.log(isItemInLocalStorage('user')); // Output: true or false +``` diff --git a/snippets/javascript/local-storage/clear-all-localstorage.md b/snippets/javascript/local-storage/clear-all-localstorage.md new file mode 100644 index 00000000..bc884994 --- /dev/null +++ b/snippets/javascript/local-storage/clear-all-localstorage.md @@ -0,0 +1,15 @@ +--- +Title: Clear All localStorage +Description: Clears all data from localStorage. +Author: dostonnabotov +Tags: javascript,localStorage,storage,utility +--- + +``` +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 new file mode 100644 index 00000000..96da181b --- /dev/null +++ b/snippets/javascript/local-storage/retrieve-item-from-localstorage.md @@ -0,0 +1,17 @@ +--- +Title: Retrieve Item from localStorage +Description: Retrieves a value from localStorage by key and parses it. +Author: dostonnabotov +Tags: javascript,localStorage,storage,utility +--- + +``` +const getFromLocalStorage = (key) => { + const item = localStorage.getItem(key); + return item ? JSON.parse(item) : null; +}; + +// Usage: +const user = getFromLocalStorage('user'); +console.log(user); // Output: { 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 new file mode 100644 index 00000000..49df5e02 --- /dev/null +++ b/snippets/javascript/number-formatting/convert-number-to-currency.md @@ -0,0 +1,19 @@ +--- +Title: Convert Number to Currency +Description: Converts a number to a currency format with a specific locale. +Author: axorax +Tags: javascript,number,currency,utility +--- + +``` +const convertToCurrency = (num, locale = 'en-US', currency = 'USD') => { + return new Intl.NumberFormat(locale, { + style: 'currency', + currency: currency + }).format(num); +}; + +// Usage: +console.log(convertToCurrency(1234567.89)); // Output: '$1,234,567.89' +console.log(convertToCurrency(987654.32, 'de-DE', 'EUR')); // Output: '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 new file mode 100644 index 00000000..94ef8d16 --- /dev/null +++ b/snippets/javascript/number-formatting/convert-number-to-roman-numerals.md @@ -0,0 +1,27 @@ +--- +Title: Convert Number to Roman Numerals +Description: Converts a number to Roman numeral representation. +Author: axorax +Tags: javascript,number,roman,utility +--- + +``` +const numberToRoman = (num) => { + const romanNumerals = { + 1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L', + 90: 'XC', 100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M' + }; + let result = ''; + Object.keys(romanNumerals).reverse().forEach(value => { + while (num >= value) { + result += romanNumerals[value]; + num -= value; + } + }); + return result; +}; + +// Usage: +console.log(numberToRoman(1994)); // Output: 'MCMXCIV' +console.log(numberToRoman(58)); // Output: 'LVIII' +``` diff --git a/snippets/javascript/number-formatting/convert-to-scientific-notation.md b/snippets/javascript/number-formatting/convert-to-scientific-notation.md new file mode 100644 index 00000000..b65e922a --- /dev/null +++ b/snippets/javascript/number-formatting/convert-to-scientific-notation.md @@ -0,0 +1,27 @@ +--- +Title: Convert to Scientific Notation +Description: Converts a number to scientific notation. +Author: axorax +Tags: javascript,number,scientific,utility +--- + +``` +const toScientificNotation = (num) => { + if (isNaN(num)) { + throw new Error('Input must be a number'); + } + if (num === 0) { + return '0e+0'; + } + const exponent = Math.floor(Math.log10(Math.abs(num))); + const mantissa = num / Math.pow(10, exponent); + return `${mantissa.toFixed(2)}e${exponent >= 0 ? '+' : ''}${exponent}`; +}; + +// 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' +``` diff --git a/snippets/javascript/number-formatting/format-number-with-commas.md b/snippets/javascript/number-formatting/format-number-with-commas.md new file mode 100644 index 00000000..5851fa49 --- /dev/null +++ b/snippets/javascript/number-formatting/format-number-with-commas.md @@ -0,0 +1,17 @@ +--- +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 +--- + +``` +const formatNumberWithCommas = (num) => { + return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); +}; + +// Usage: +console.log(formatNumberWithCommas(1000)); // Output: '1,000' +console.log(formatNumberWithCommas(1234567)); // Output: '1,234,567' +console.log(formatNumberWithCommas(987654321)); // Output: '987,654,321' +``` diff --git a/snippets/javascript/number-formatting/number-formatter.md b/snippets/javascript/number-formatting/number-formatter.md new file mode 100644 index 00000000..ba7cfade --- /dev/null +++ b/snippets/javascript/number-formatting/number-formatter.md @@ -0,0 +1,23 @@ +--- +Title: Number Formatter +Description: Formats a number with suffixes (K, M, B, etc.). +Author: realvishalrana +Tags: javascript,number,format,utility +--- + +``` +const nFormatter = (num) => { + if (!num) return; + num = parseFloat(num.toString().replace(/[^0-9.]/g, '')); + const suffixes = ['', 'K', 'M', 'B', 'T', 'P', 'E']; + let index = 0; + while (num >= 1000 && index < suffixes.length - 1) { + num /= 1000; + index++; + } + return num.toFixed(2).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, '$1') + suffixes[index]; +}; + +// Usage: +console.log(nFormatter(1234567)); // Output: '1.23M' +``` diff --git a/snippets/javascript/number-formatting/number-to-words-converter.md b/snippets/javascript/number-formatting/number-to-words-converter.md new file mode 100644 index 00000000..9f08a5a8 --- /dev/null +++ b/snippets/javascript/number-formatting/number-to-words-converter.md @@ -0,0 +1,30 @@ +--- +Title: Number to Words Converter +Description: Converts a number to its word representation in English. +Author: axorax +Tags: javascript,number,words,utility +--- + +``` +const numberToWords = (num) => { + const below20 = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']; + const tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']; + const above1000 = ['Hundred', 'Thousand', 'Million', 'Billion']; + if (num < 20) return below20[num]; + let words = ''; + for (let i = 0; num > 0; i++) { + if (i > 0 && num % 1000 !== 0) words = above1000[i] + ' ' + words; + if (num % 100 >= 20) { + words = tens[Math.floor(num / 10)] + ' ' + words; + num %= 10; + } + if (num < 20) words = below20[num] + ' ' + words; + num = Math.floor(num / 100); + } + return words.trim(); +}; + +// Usage: +console.log(numberToWords(123)); // Output: 'One Hundred Twenty Three' +console.log(numberToWords(2045)); // Output: '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 new file mode 100644 index 00000000..7287b725 --- /dev/null +++ b/snippets/javascript/object-manipulation/check-if-object-is-empty.md @@ -0,0 +1,16 @@ +--- +Title: Check if Object is Empty +Description: Checks whether an object has no own enumerable properties. +Author: axorax +Tags: javascript,object,check,empty +--- + +``` +function isEmptyObject(obj) { + return Object.keys(obj).length === 0; +} + +// Usage: +console.log(isEmptyObject({})); // Output: true +console.log(isEmptyObject({ a: 1 })); // Output: false +``` diff --git a/snippets/javascript/object-manipulation/clone-object-shallowly.md b/snippets/javascript/object-manipulation/clone-object-shallowly.md new file mode 100644 index 00000000..20f70dac --- /dev/null +++ b/snippets/javascript/object-manipulation/clone-object-shallowly.md @@ -0,0 +1,17 @@ +--- +Title: Clone Object Shallowly +Description: Creates a shallow copy of an object. +Author: axorax +Tags: javascript,object,clone,shallow +--- + +``` +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 new file mode 100644 index 00000000..1d52af16 --- /dev/null +++ b/snippets/javascript/object-manipulation/compare-two-objects-shallowly.md @@ -0,0 +1,22 @@ +--- +Title: Compare Two Objects Shallowly +Description: Compares two objects shallowly and returns whether they are equal. +Author: axorax +Tags: javascript,object,compare,shallow +--- + +``` +function shallowEqual(obj1, obj2) { + const keys1 = Object.keys(obj1); + const keys2 = Object.keys(obj2); + if (keys1.length !== keys2.length) return false; + return keys1.every(key => obj1[key] === obj2[key]); +} + +// Usage: +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 +``` diff --git a/snippets/javascript/object-manipulation/convert-object-to-query-string.md b/snippets/javascript/object-manipulation/convert-object-to-query-string.md new file mode 100644 index 00000000..29667870 --- /dev/null +++ b/snippets/javascript/object-manipulation/convert-object-to-query-string.md @@ -0,0 +1,18 @@ +--- +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 +--- + +``` +function toQueryString(obj) { + return Object.entries(obj) + .map(([key, value]) => encodeURIComponent(key) + '=' + encodeURIComponent(value)) + .join('&'); +} + +// Usage: +const params = { search: 'test', page: 1 }; +console.log(toQueryString(params)); // Output: '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 new file mode 100644 index 00000000..b3b9a41d --- /dev/null +++ b/snippets/javascript/object-manipulation/count-properties-in-object.md @@ -0,0 +1,16 @@ +--- +Title: Count Properties in Object +Description: Counts the number of own properties in an object. +Author: axorax +Tags: javascript,object,count,properties +--- + +``` +function countProperties(obj) { + return Object.keys(obj).length; +} + +// Usage: +const obj = { a: 1, b: 2, c: 3 }; +console.log(countProperties(obj)); // Output: 3 +``` diff --git a/snippets/javascript/object-manipulation/filter-object.md b/snippets/javascript/object-manipulation/filter-object.md new file mode 100644 index 00000000..1acffb11 --- /dev/null +++ b/snippets/javascript/object-manipulation/filter-object.md @@ -0,0 +1,27 @@ +--- +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 +--- + +``` +export const filterObject = (object = {}) => + Object.fromEntries( + Object.entries(object) + .filter(([key, value]) => value !== null && value !== undefined && value !== '' && (typeof value !== 'object' || Object.keys(value).length > 0)) + ); + +// Usage: +const obj1 = { a: 1, b: null, c: undefined, d: 4, e: '', f: {} }; +console.log(filterObject(obj1)); // Output: { a: 1, d: 4 } + +const obj2 = { x: 0, y: false, z: 'Hello', w: [] }; +console.log(filterObject(obj2)); // Output: { z: 'Hello' } + +const obj3 = { name: 'John', age: null, address: { city: 'New York' }, phone: '' }; +console.log(filterObject(obj3)); // Output: { name: 'John', address: { city: 'New York' } } + +const obj4 = { a: 0, b: '', c: false, d: {}, e: 'Valid' }; +console.log(filterObject(obj4)); // Output: { e: 'Valid' } +``` diff --git a/snippets/javascript/object-manipulation/flatten-nested-object.md b/snippets/javascript/object-manipulation/flatten-nested-object.md new file mode 100644 index 00000000..84971c91 --- /dev/null +++ b/snippets/javascript/object-manipulation/flatten-nested-object.md @@ -0,0 +1,24 @@ +--- +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 +--- + +``` +function flattenObject(obj, prefix = '') { + return Object.keys(obj).reduce((acc, key) => { + const fullPath = prefix ? `${prefix}.${key}` : key; + if (typeof obj[key] === 'object' && obj[key] !== null) { + Object.assign(acc, flattenObject(obj[key], fullPath)); + } else { + acc[fullPath] = obj[key]; + } + return acc; + }, {}); +} + +// 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 } +``` diff --git a/snippets/javascript/object-manipulation/freeze-object.md b/snippets/javascript/object-manipulation/freeze-object.md new file mode 100644 index 00000000..1b846a07 --- /dev/null +++ b/snippets/javascript/object-manipulation/freeze-object.md @@ -0,0 +1,18 @@ +--- +Title: Freeze Object +Description: Freezes an object to make it immutable. +Author: axorax +Tags: javascript,object,freeze,immutable +--- + +``` +function freezeObject(obj) { + return Object.freeze(obj); +} + +// Usage: +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 +``` diff --git a/snippets/javascript/object-manipulation/get-nested-value.md b/snippets/javascript/object-manipulation/get-nested-value.md new file mode 100644 index 00000000..221d4c7b --- /dev/null +++ b/snippets/javascript/object-manipulation/get-nested-value.md @@ -0,0 +1,19 @@ +--- +Title: Get Nested Value +Description: Retrieves the value at a given path in a nested object. +Author: realvishalrana +Tags: javascript,object,nested,utility +--- + +``` +const getNestedValue = (obj, path) => { + const keys = path.split('.'); + return keys.reduce((currentObject, key) => { + return currentObject && typeof currentObject === 'object' ? currentObject[key] : undefined; + }, obj); +}; + +// Usage: +const obj = { a: { b: { c: 42 } } }; +console.log(getNestedValue(obj, 'a.b.c')); // Output: 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 new file mode 100644 index 00000000..da924034 --- /dev/null +++ b/snippets/javascript/object-manipulation/invert-object-keys-and-values.md @@ -0,0 +1,18 @@ +--- +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 +--- + +``` +function invertObject(obj) { + return Object.fromEntries( + Object.entries(obj).map(([key, value]) => [value, key]) + ); +} + +// Usage: +const obj = { a: 1, b: 2, c: 3 }; +console.log(invertObject(obj)); // Output: { '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 new file mode 100644 index 00000000..44a32963 --- /dev/null +++ b/snippets/javascript/object-manipulation/merge-objects-deeply.md @@ -0,0 +1,26 @@ +--- +Title: Merge Objects Deeply +Description: Deeply merges two or more objects, including nested properties. +Author: axorax +Tags: javascript,object,merge,deep +--- + +``` +function deepMerge(...objects) { + return objects.reduce((acc, obj) => { + Object.keys(obj).forEach(key => { + if (typeof obj[key] === 'object' && obj[key] !== null) { + acc[key] = deepMerge(acc[key] || {}, obj[key]); + } else { + acc[key] = obj[key]; + } + }); + return acc; + }, {}); +} + +// 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 } +``` diff --git a/snippets/javascript/object-manipulation/omit-keys-from-object.md b/snippets/javascript/object-manipulation/omit-keys-from-object.md new file mode 100644 index 00000000..075a4f9a --- /dev/null +++ b/snippets/javascript/object-manipulation/omit-keys-from-object.md @@ -0,0 +1,18 @@ +--- +Title: Omit Keys from Object +Description: Creates a new object with specific keys omitted. +Author: axorax +Tags: javascript,object,omit,utility +--- + +``` +function omitKeys(obj, keys) { + return Object.fromEntries( + Object.entries(obj).filter(([key]) => !keys.includes(key)) + ); +} + +// Usage: +const obj = { a: 1, b: 2, c: 3 }; +console.log(omitKeys(obj, ['b', 'c'])); // Output: { a: 1 } +``` diff --git a/snippets/javascript/object-manipulation/pick-keys-from-object.md b/snippets/javascript/object-manipulation/pick-keys-from-object.md new file mode 100644 index 00000000..aa00b191 --- /dev/null +++ b/snippets/javascript/object-manipulation/pick-keys-from-object.md @@ -0,0 +1,18 @@ +--- +Title: Pick Keys from Object +Description: Creates a new object with only the specified keys. +Author: axorax +Tags: javascript,object,pick,utility +--- + +``` +function pickKeys(obj, keys) { + return Object.fromEntries( + Object.entries(obj).filter(([key]) => keys.includes(key)) + ); +} + +// Usage: +const obj = { a: 1, b: 2, c: 3 }; +console.log(pickKeys(obj, ['a', 'c'])); // Output: { a: 1, c: 3 } +``` diff --git a/snippets/javascript/object-manipulation/unique-by-key.md b/snippets/javascript/object-manipulation/unique-by-key.md new file mode 100644 index 00000000..d8ed12fb --- /dev/null +++ b/snippets/javascript/object-manipulation/unique-by-key.md @@ -0,0 +1,19 @@ +--- +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 +--- + +``` +const uniqueByKey = (key, arr) => + arr.filter((obj, index, self) => index === self.findIndex((t) => t?.[key] === obj?.[key])); + +// Usage: +const arr = [ + { id: 1, name: 'John' }, + { id: 2, name: 'Jane' }, + { id: 1, name: 'John' } +]; +console.log(uniqueByKey('id', arr)); // Output: [{ 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 new file mode 100644 index 00000000..fd0778c3 --- /dev/null +++ b/snippets/javascript/regular-expression/regex-match-utility-function.md @@ -0,0 +1,39 @@ +--- +Title: Regex Match Utility Function +Description: Enhanced regular expression matching utility. +Author: aumirza +Tags: javascript,regex +--- + +``` +/** +* @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 new file mode 100644 index 00000000..367530a7 --- /dev/null +++ b/snippets/javascript/string-manipulation/capitalize-string.md @@ -0,0 +1,13 @@ +--- +Title: Capitalize String +Description: Capitalizes the first letter of a string. +Author: dostonnabotov +Tags: javascript,string,capitalize,utility +--- + +``` +const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1); + +// Usage: +console.log(capitalize('hello')); // Output: '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 new file mode 100644 index 00000000..924f4999 --- /dev/null +++ b/snippets/javascript/string-manipulation/check-if-string-is-a-palindrome.md @@ -0,0 +1,16 @@ +--- +Title: Check if String is a Palindrome +Description: Checks whether a given string is a palindrome. +Author: axorax +Tags: javascript,check,palindrome,string +--- + +``` +function isPalindrome(str) { + const cleanStr = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase(); + return cleanStr === cleanStr.split('').reverse().join(''); +} + +// Example usage: +console.log(isPalindrome('A man, a plan, a canal, Panama')); // Output: 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 new file mode 100644 index 00000000..3103c6c8 --- /dev/null +++ b/snippets/javascript/string-manipulation/convert-string-to-camel-case.md @@ -0,0 +1,15 @@ +--- +Title: Convert String to Camel Case +Description: Converts a given string into camelCase. +Author: aumirza +Tags: string,case,camelCase +--- + +``` +function toCamelCase(str) { + return str.replace(/\W+(.)/g, (match, chr) => chr.toUpperCase()); +} + +// Example usage: +console.log(toCamelCase('hello world test')); // Output: '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 new file mode 100644 index 00000000..369915ff --- /dev/null +++ b/snippets/javascript/string-manipulation/convert-string-to-param-case.md @@ -0,0 +1,15 @@ +--- +Title: Convert String to Param Case +Description: Converts a given string into param-case. +Author: aumirza +Tags: string,case,paramCase +--- + +``` +function toParamCase(str) { + return str.toLowerCase().replace(/\s+/g, '-'); +} + +// Example usage: +console.log(toParamCase('Hello World Test')); // Output: '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 new file mode 100644 index 00000000..d303a046 --- /dev/null +++ b/snippets/javascript/string-manipulation/convert-string-to-pascal-case.md @@ -0,0 +1,15 @@ +--- +Title: Convert String to Pascal Case +Description: Converts a given string into Pascal Case. +Author: aumirza +Tags: string,case,pascalCase +--- + +``` +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' +``` diff --git a/snippets/javascript/string-manipulation/convert-string-to-snake-case.md b/snippets/javascript/string-manipulation/convert-string-to-snake-case.md new file mode 100644 index 00000000..ce177a10 --- /dev/null +++ b/snippets/javascript/string-manipulation/convert-string-to-snake-case.md @@ -0,0 +1,17 @@ +--- +Title: Convert String to Snake Case +Description: Converts a given string into snake_case. +Author: axorax +Tags: string,case,snake_case +--- + +``` +function toSnakeCase(str) { + return str.replace(/([a-z])([A-Z])/g, '$1_$2') + .replace(/\s+/g, '_') + .toLowerCase(); +} + +// Example usage: +console.log(toSnakeCase('Hello World Test')); // Output: '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 new file mode 100644 index 00000000..56f1916a --- /dev/null +++ b/snippets/javascript/string-manipulation/convert-string-to-title-case.md @@ -0,0 +1,15 @@ +--- +Title: Convert String to Title Case +Description: Converts a given string into Title Case. +Author: aumirza +Tags: string,case,titleCase +--- + +``` +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' +``` diff --git a/snippets/javascript/string-manipulation/convert-tabs-to-spaces.md b/snippets/javascript/string-manipulation/convert-tabs-to-spaces.md new file mode 100644 index 00000000..2a5d97d7 --- /dev/null +++ b/snippets/javascript/string-manipulation/convert-tabs-to-spaces.md @@ -0,0 +1,15 @@ +--- +Title: Convert Tabs to Spaces +Description: Converts all tab characters in a string to spaces. +Author: axorax +Tags: string,tabs,spaces +--- + +``` +function tabsToSpaces(str, spacesPerTab = 4) { + return str.replace(/\t/g, ' '.repeat(spacesPerTab)); +} + +// Example usage: +console.log(tabsToSpaces('Hello\tWorld', 2)); // Output: '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 new file mode 100644 index 00000000..8a3429a3 --- /dev/null +++ b/snippets/javascript/string-manipulation/count-words-in-a-string.md @@ -0,0 +1,15 @@ +--- +Title: Count Words in a String +Description: Counts the number of words in a string. +Author: axorax +Tags: javascript,string,manipulation,word count,count +--- + +``` +function countWords(str) { + return str.trim().split(/\s+/).length; +} + +// Example usage: +console.log(countWords('Hello world! This is a test.')); // Output: 6 +``` diff --git a/snippets/javascript/string-manipulation/data-with-prefix.md b/snippets/javascript/string-manipulation/data-with-prefix.md new file mode 100644 index 00000000..99d71870 --- /dev/null +++ b/snippets/javascript/string-manipulation/data-with-prefix.md @@ -0,0 +1,18 @@ +--- +Title: Data with Prefix +Description: Adds a prefix and postfix to data, with a fallback value. +Author: realvishalrana +Tags: javascript,data,utility +--- + +``` +const dataWithPrefix = (data, fallback = '-', prefix = '', postfix = '') => { + return data ? `${prefix}${data}${postfix}` : fallback; +}; + +// 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' +``` diff --git a/snippets/javascript/string-manipulation/extract-initials-from-name.md b/snippets/javascript/string-manipulation/extract-initials-from-name.md new file mode 100644 index 00000000..33e9a98e --- /dev/null +++ b/snippets/javascript/string-manipulation/extract-initials-from-name.md @@ -0,0 +1,15 @@ +--- +Title: Extract Initials from Name +Description: Extracts and returns the initials from a full name. +Author: axorax +Tags: string,initials,name +--- + +``` +function getInitials(name) { + return name.split(' ').map(part => part.charAt(0).toUpperCase()).join(''); +} + +// Example usage: +console.log(getInitials('John Doe')); // Output: 'JD' +``` diff --git a/snippets/javascript/string-manipulation/mask-sensitive-information.md b/snippets/javascript/string-manipulation/mask-sensitive-information.md new file mode 100644 index 00000000..c9733859 --- /dev/null +++ b/snippets/javascript/string-manipulation/mask-sensitive-information.md @@ -0,0 +1,16 @@ +--- +Title: Mask Sensitive Information +Description: Masks parts of a sensitive string, like a credit card or email address. +Author: axorax +Tags: string,mask,sensitive +--- + +``` +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#############' +``` diff --git a/snippets/javascript/string-manipulation/pad-string-on-both-sides.md b/snippets/javascript/string-manipulation/pad-string-on-both-sides.md new file mode 100644 index 00000000..2763564a --- /dev/null +++ b/snippets/javascript/string-manipulation/pad-string-on-both-sides.md @@ -0,0 +1,18 @@ +--- +Title: Pad String on Both Sides +Description: Pads a string on both sides with a specified character until it reaches the desired length. +Author: axorax +Tags: string,pad,manipulation +--- + +``` +function padString(str, length, char = ' ') { + const totalPad = length - str.length; + const padStart = Math.floor(totalPad / 2); + const padEnd = totalPad - padStart; + return char.repeat(padStart) + str + char.repeat(padEnd); +} + +// Example usage: +console.log(padString('hello', 10, '*')); // Output: '**hello***' +``` diff --git a/snippets/javascript/string-manipulation/random-string.md b/snippets/javascript/string-manipulation/random-string.md new file mode 100644 index 00000000..b0c84161 --- /dev/null +++ b/snippets/javascript/string-manipulation/random-string.md @@ -0,0 +1,14 @@ +--- +Title: Random string +Description: Generates a random string of characters of a certain length +Author: kruimol +Tags: javascript,function,random +--- + +``` +function makeid(length, characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') { + return Array.from({ length }, () => characters.charAt(Math.floor(Math.random() * characters.length))).join(''); +} + +console.log(makeid(5, "1234" /* (optional) */)); +``` diff --git a/snippets/javascript/string-manipulation/remove-all-whitespace.md b/snippets/javascript/string-manipulation/remove-all-whitespace.md new file mode 100644 index 00000000..2b945f76 --- /dev/null +++ b/snippets/javascript/string-manipulation/remove-all-whitespace.md @@ -0,0 +1,15 @@ +--- +Title: Remove All Whitespace +Description: Removes all whitespace from a string. +Author: axorax +Tags: javascript,string,whitespace +--- + +``` +function removeWhitespace(str) { + return str.replace(/\s+/g, ''); +} + +// Example usage: +console.log(removeWhitespace('Hello world!')); // Output: '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 new file mode 100644 index 00000000..320fe24e --- /dev/null +++ b/snippets/javascript/string-manipulation/remove-vowels-from-a-string.md @@ -0,0 +1,15 @@ +--- +Title: Remove Vowels from a String +Description: Removes all vowels from a given string. +Author: axorax +Tags: string,remove,vowels +--- + +``` +function removeVowels(str) { + return str.replace(/[aeiouAEIOU]/g, ''); +} + +// Example usage: +console.log(removeVowels('Hello World')); // Output: 'Hll Wrld' +``` diff --git a/snippets/javascript/string-manipulation/reverse-string.md b/snippets/javascript/string-manipulation/reverse-string.md new file mode 100644 index 00000000..a7c1d9f1 --- /dev/null +++ b/snippets/javascript/string-manipulation/reverse-string.md @@ -0,0 +1,13 @@ +--- +Title: Reverse String +Description: Reverses the characters in a string. +Author: dostonnabotov +Tags: javascript,string,reverse,utility +--- + +``` +const reverseString = (str) => str.split('').reverse().join(''); + +// Usage: +console.log(reverseString('hello')); // Output: 'olleh' +``` diff --git a/snippets/javascript/string-manipulation/slugify-string.md b/snippets/javascript/string-manipulation/slugify-string.md new file mode 100644 index 00000000..b28c249d --- /dev/null +++ b/snippets/javascript/string-manipulation/slugify-string.md @@ -0,0 +1,25 @@ +--- +Title: Slugify String +Description: Converts a string into a URL-friendly slug format. +Author: dostonnabotov +Tags: javascript,string,slug,utility +--- + +``` +const 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 - +}; + +// 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' +``` diff --git a/snippets/javascript/string-manipulation/truncate-text.md b/snippets/javascript/string-manipulation/truncate-text.md new file mode 100644 index 00000000..eeffee54 --- /dev/null +++ b/snippets/javascript/string-manipulation/truncate-text.md @@ -0,0 +1,17 @@ +--- +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 +--- + +``` +const truncateText = (text = '', maxLength = 50) => { + return `${text.slice(0, maxLength)}${text.length >= maxLength ? '...' : ''}`; +}; + +// 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...' +``` diff --git a/snippets/python/basics/hello-world.md b/snippets/python/basics/hello-world.md new file mode 100644 index 00000000..25131882 --- /dev/null +++ b/snippets/python/basics/hello-world.md @@ -0,0 +1,10 @@ +--- +Title: Hello, World! +Description: Prints Hello, World! to the terminal. +Author: James-Beans +Tags: python,printing,hello-world,utility +--- + +``` +print("Hello, World!") # Prints Hello, World! to the terminal. +``` diff --git a/snippets/python/datetime-utilities/calculate-date-difference-in-milliseconds.md b/snippets/python/datetime-utilities/calculate-date-difference-in-milliseconds.md new file mode 100644 index 00000000..9550ee4e --- /dev/null +++ b/snippets/python/datetime-utilities/calculate-date-difference-in-milliseconds.md @@ -0,0 +1,19 @@ +--- +Title: Calculate Date Difference in Milliseconds +Description: Calculates the difference between two dates in milliseconds. +Author: e3nviction +Tags: python,datetime,utility +--- + +``` +from datetime import datetime + +def date_difference_in_millis(date1, date2): + delta = date2 - date1 + return delta.total_seconds() * 1000 + +# Usage: +d1 = datetime(2023, 1, 1, 12, 0, 0) +d2 = datetime(2023, 1, 1, 12, 1, 0) +print(date_difference_in_millis(d1, d2)) +``` 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 new file mode 100644 index 00000000..3aef4357 --- /dev/null +++ b/snippets/python/datetime-utilities/check-if-date-is-a-weekend.md @@ -0,0 +1,21 @@ +--- +Title: Check if Date is a Weekend +Description: Checks whether a given date falls on a weekend. +Author: axorax +Tags: python,datetime,weekend,utility +--- + +``` +from datetime import datetime + +def is_weekend(date): + try: + return date.weekday() >= 5 # Saturday = 5, Sunday = 6 + except AttributeError: + raise TypeError("Input must be a datetime object") + +# Usage: +date = datetime(2023, 1, 1) +weekend = is_weekend(date) +print(weekend) # Output: True (Sunday) +``` diff --git a/snippets/python/datetime-utilities/determine-day-of-the-week.md b/snippets/python/datetime-utilities/determine-day-of-the-week.md new file mode 100644 index 00000000..9e39e042 --- /dev/null +++ b/snippets/python/datetime-utilities/determine-day-of-the-week.md @@ -0,0 +1,22 @@ +--- +Title: Determine Day of the Week +Description: Calculates the day of the week for a given date. +Author: axorax +Tags: python,datetime,weekday,utility +--- + +``` +from datetime import datetime + +def get_day_of_week(date): + days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] + try: + return days[date.weekday()] + except IndexError: + raise ValueError("Invalid date") + +# Usage: +date = datetime(2023, 1, 1) +day = get_day_of_week(date) +print(day) # Output: 'Sunday' +``` diff --git a/snippets/python/datetime-utilities/generate-date-range-list.md b/snippets/python/datetime-utilities/generate-date-range-list.md new file mode 100644 index 00000000..a7cd5abe --- /dev/null +++ b/snippets/python/datetime-utilities/generate-date-range-list.md @@ -0,0 +1,30 @@ +--- +Title: Generate Date Range List +Description: Generates a list of dates between two given dates. +Author: axorax +Tags: python,datetime,range,utility +--- + +``` +from datetime import datetime, timedelta + +def generate_date_range(start_date, end_date): + if start_date > end_date: + raise ValueError("start_date must be before end_date") + + current_date = start_date + date_list = [] + while current_date <= end_date: + date_list.append(current_date) + current_date += timedelta(days=1) + + return date_list + +# Usage: +start = datetime(2023, 1, 1) +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' +``` diff --git a/snippets/python/datetime-utilities/get-current-date-and-time-string.md b/snippets/python/datetime-utilities/get-current-date-and-time-string.md new file mode 100644 index 00000000..feb9b5a0 --- /dev/null +++ b/snippets/python/datetime-utilities/get-current-date-and-time-string.md @@ -0,0 +1,16 @@ +--- +Title: Get Current Date and Time String +Description: Fetches the current date and time as a formatted string. +Author: e3nviction +Tags: python,datetime,utility +--- + +``` +from datetime import datetime + +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' +``` 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 new file mode 100644 index 00000000..579d96fa --- /dev/null +++ b/snippets/python/datetime-utilities/get-number-of-days-in-a-month.md @@ -0,0 +1,21 @@ +--- +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 +--- + +``` +from calendar import monthrange +from datetime import datetime + +def get_days_in_month(year, month): + try: + return monthrange(year, month)[1] + except ValueError as e: + 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) +``` diff --git a/snippets/python/error-handling/handle-file-not-found-error.md b/snippets/python/error-handling/handle-file-not-found-error.md new file mode 100644 index 00000000..a4bfbd0d --- /dev/null +++ b/snippets/python/error-handling/handle-file-not-found-error.md @@ -0,0 +1,18 @@ +--- +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 +--- + +``` +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 new file mode 100644 index 00000000..d0f2b642 --- /dev/null +++ b/snippets/python/error-handling/retry-function-execution-on-exception.md @@ -0,0 +1,29 @@ +--- +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 +--- + +``` +import time + +def retry(func, retries=3, delay=1): + for attempt in range(retries): + try: + return func() + except Exception as e: + print(f"Attempt {attempt + 1} failed: {e}") + time.sleep(delay) + raise Exception("All retry attempts failed") + +# Usage: +def unstable_function(): + raise ValueError("Simulated failure") + +# Retry 3 times with 2 seconds delay: +try: + retry(unstable_function, retries=3, delay=2) +except Exception as e: + print(e) # Output: All retry attempts failed +``` diff --git a/snippets/python/error-handling/safe-division.md b/snippets/python/error-handling/safe-division.md new file mode 100644 index 00000000..f86f6201 --- /dev/null +++ b/snippets/python/error-handling/safe-division.md @@ -0,0 +1,18 @@ +--- +Title: Safe Division +Description: Performs division with error handling. +Author: e3nviction +Tags: python,error-handling,division,utility +--- + +``` +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 new file mode 100644 index 00000000..6ce61e38 --- /dev/null +++ b/snippets/python/error-handling/validate-input-with-exception-handling.md @@ -0,0 +1,22 @@ +--- +Title: Validate Input with Exception Handling +Description: Validates user input and handles invalid input gracefully. +Author: axorax +Tags: python,error-handling,validation,utility +--- + +``` +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 new file mode 100644 index 00000000..0d9b1038 --- /dev/null +++ b/snippets/python/file-handling/append-to-file.md @@ -0,0 +1,15 @@ +--- +Title: Append to File +Description: Appends content to the end of a file. +Author: axorax +Tags: python,file,append,utility +--- + +``` +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 new file mode 100644 index 00000000..ac1a7c46 --- /dev/null +++ b/snippets/python/file-handling/check-if-file-exists.md @@ -0,0 +1,16 @@ +--- +Title: Check if File Exists +Description: Checks if a file exists at the specified path. +Author: axorax +Tags: python,file,exists,check,utility +--- + +``` +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 new file mode 100644 index 00000000..ff6ea68c --- /dev/null +++ b/snippets/python/file-handling/copy-file.md @@ -0,0 +1,16 @@ +--- +Title: Copy File +Description: Copies a file from source to destination. +Author: axorax +Tags: python,file,copy,utility +--- + +``` +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 new file mode 100644 index 00000000..c47e4074 --- /dev/null +++ b/snippets/python/file-handling/delete-file.md @@ -0,0 +1,20 @@ +--- +Title: Delete File +Description: Deletes a file at the specified path. +Author: axorax +Tags: python,file,delete,utility +--- + +``` +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 new file mode 100644 index 00000000..ab52a68b --- /dev/null +++ b/snippets/python/file-handling/find-files.md @@ -0,0 +1,27 @@ +--- +Title: Find Files +Description: Finds all files of the specified type within a given directory. +Author: Jackeastern +Tags: python,os,filesystem,file_search +--- + +``` +import os + +def find_files(directory, file_type): + file_type = file_type.lower() # Convert file_type to lowercase + found_files = [] + + for root, _, files in os.walk(directory): + for file in files: + file_ext = os.path.splitext(file)[1].lower() + if file_ext == file_type: + full_path = os.path.join(root, file) + found_files.append(full_path) + + return found_files + +# Example Usage: +pdf_files = find_files('/path/to/your/directory', '.pdf') +print(pdf_files) +``` diff --git a/snippets/python/file-handling/get-file-extension.md b/snippets/python/file-handling/get-file-extension.md new file mode 100644 index 00000000..238bc4b7 --- /dev/null +++ b/snippets/python/file-handling/get-file-extension.md @@ -0,0 +1,16 @@ +--- +Title: Get File Extension +Description: Gets the extension of a file. +Author: axorax +Tags: python,file,extension,utility +--- + +``` +import os + +def get_file_extension(filepath): + return os.path.splitext(filepath)[1] + +# Usage: +print(get_file_extension('example.txt')) # Output: '.txt' +``` diff --git a/snippets/python/file-handling/list-files-in-directory.md b/snippets/python/file-handling/list-files-in-directory.md new file mode 100644 index 00000000..d9b95326 --- /dev/null +++ b/snippets/python/file-handling/list-files-in-directory.md @@ -0,0 +1,17 @@ +--- +Title: List Files in Directory +Description: Lists all files in a specified directory. +Author: axorax +Tags: python,file,list,directory,utility +--- + +``` +import os + +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) +``` diff --git a/snippets/python/file-handling/read-file-in-chunks.md b/snippets/python/file-handling/read-file-in-chunks.md new file mode 100644 index 00000000..caf4c55f --- /dev/null +++ b/snippets/python/file-handling/read-file-in-chunks.md @@ -0,0 +1,17 @@ +--- +Title: Read File in Chunks +Description: Reads a file in chunks of a specified size. +Author: axorax +Tags: python,file,read,chunks,utility +--- + +``` +def read_file_in_chunks(filepath, chunk_size): + with open(filepath, 'r') as file: + while chunk := file.read(chunk_size): + yield chunk + +# Usage: +for chunk in read_file_in_chunks('example.txt', 1024): + print(chunk) +``` diff --git a/snippets/python/file-handling/read-file-lines.md b/snippets/python/file-handling/read-file-lines.md new file mode 100644 index 00000000..42baf72e --- /dev/null +++ b/snippets/python/file-handling/read-file-lines.md @@ -0,0 +1,16 @@ +--- +Title: Read File Lines +Description: Reads all lines from a file and returns them as a list. +Author: dostonnabotov +Tags: python,file,read,utility +--- + +``` +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 new file mode 100644 index 00000000..6c3cd3ca --- /dev/null +++ b/snippets/python/file-handling/write-to-file.md @@ -0,0 +1,15 @@ +--- +Title: Write to File +Description: Writes content to a file. +Author: dostonnabotov +Tags: python,file,write,utility +--- + +``` +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/icon.svg b/snippets/python/icon.svg new file mode 100644 index 00000000..3755e98e --- /dev/null +++ b/snippets/python/icon.svg @@ -0,0 +1,21 @@ + +Python Logo +A blue and yellow snake symbol forming a plus with a somewhat circular or rounded shape + + + + + + + + + + + + + + + + + + diff --git a/snippets/python/json-manipulation/filter-json-data.md b/snippets/python/json-manipulation/filter-json-data.md new file mode 100644 index 00000000..9b4423c3 --- /dev/null +++ b/snippets/python/json-manipulation/filter-json-data.md @@ -0,0 +1,24 @@ +--- +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 +--- + +``` +import json + +def filter_json_data(filepath, condition): + with open(filepath, 'r') as file: + data = json.load(file) + + # Filter data based on the provided condition + filtered_data = [item for item in data if condition(item)] + + return filtered_data + +# Usage: +condition = lambda x: x['age'] > 25 +filtered = filter_json_data('data.json', condition) +print(filtered) +``` diff --git a/snippets/python/json-manipulation/flatten-nested-json.md b/snippets/python/json-manipulation/flatten-nested-json.md new file mode 100644 index 00000000..9e3b4014 --- /dev/null +++ b/snippets/python/json-manipulation/flatten-nested-json.md @@ -0,0 +1,22 @@ +--- +Title: Flatten Nested JSON +Description: Flattens a nested JSON object into a flat dictionary. +Author: axorax +Tags: python,json,flatten,nested +--- + +``` +def flatten_json(nested_json, prefix=''): + flat_dict = {} + for key, value in nested_json.items(): + if isinstance(value, dict): + flat_dict.update(flatten_json(value, prefix + key + '.')) + else: + flat_dict[prefix + key] = value + return flat_dict + +# 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'} +``` diff --git a/snippets/python/json-manipulation/merge-multiple-json-files.md b/snippets/python/json-manipulation/merge-multiple-json-files.md new file mode 100644 index 00000000..62472fcf --- /dev/null +++ b/snippets/python/json-manipulation/merge-multiple-json-files.md @@ -0,0 +1,27 @@ +--- +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 +--- + +``` +import json + +def merge_json_files(filepaths, output_filepath): + merged_data = [] + + # Read each JSON file and merge their data + for filepath in filepaths: + with open(filepath, 'r') as file: + data = json.load(file) + merged_data.extend(data) + + # Write the merged data into a new file + with open(output_filepath, 'w') as file: + json.dump(merged_data, file, indent=4) + +# Usage: +files_to_merge = ['file1.json', 'file2.json'] +merge_json_files(files_to_merge, 'merged.json') +``` diff --git a/snippets/python/json-manipulation/read-json-file.md b/snippets/python/json-manipulation/read-json-file.md new file mode 100644 index 00000000..a5e95544 --- /dev/null +++ b/snippets/python/json-manipulation/read-json-file.md @@ -0,0 +1,18 @@ +--- +Title: Read JSON File +Description: Reads a JSON file and parses its content. +Author: e3nviction +Tags: python,json,file,read +--- + +``` +import json + +def read_json(filepath): + with open(filepath, 'r') as file: + return json.load(file) + +# Usage: +data = read_json('data.json') +print(data) +``` diff --git a/snippets/python/json-manipulation/update-json-file.md b/snippets/python/json-manipulation/update-json-file.md new file mode 100644 index 00000000..773e80e5 --- /dev/null +++ b/snippets/python/json-manipulation/update-json-file.md @@ -0,0 +1,26 @@ +--- +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 +--- + +``` +import json + +def update_json(filepath, new_data): + # Read the existing JSON data + with open(filepath, 'r') as file: + data = json.load(file) + + # Update the data with the new content + data.update(new_data) + + # Write the updated data back to the JSON file + with open(filepath, 'w') as file: + json.dump(data, file, indent=4) + +# Usage: +new_data = {'age': 31} +update_json('data.json', new_data) +``` diff --git a/snippets/python/json-manipulation/validate-json-schema.md b/snippets/python/json-manipulation/validate-json-schema.md new file mode 100644 index 00000000..9e6c7fb4 --- /dev/null +++ b/snippets/python/json-manipulation/validate-json-schema.md @@ -0,0 +1,31 @@ +--- +Title: Validate JSON Schema +Description: Validates a JSON object against a predefined schema. +Author: axorax +Tags: python,json,validation,schema +--- + +``` +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 new file mode 100644 index 00000000..77d59b02 --- /dev/null +++ b/snippets/python/json-manipulation/write-json-file.md @@ -0,0 +1,18 @@ +--- +Title: Write JSON File +Description: Writes a dictionary to a JSON file. +Author: e3nviction +Tags: python,json,file,write +--- + +``` +import json + +def write_json(filepath, data): + with open(filepath, 'w') as file: + json.dump(data, file, indent=4) + +# Usage: +data = {'name': 'John', 'age': 30} +write_json('data.json', data) +``` diff --git a/snippets/python/list-manipulation/find-duplicates-in-a-list.md b/snippets/python/list-manipulation/find-duplicates-in-a-list.md new file mode 100644 index 00000000..b25043e3 --- /dev/null +++ b/snippets/python/list-manipulation/find-duplicates-in-a-list.md @@ -0,0 +1,22 @@ +--- +Title: Find Duplicates in a List +Description: Identifies duplicate elements in a list. +Author: axorax +Tags: python,list,duplicates,utility +--- + +``` +def find_duplicates(lst): + seen = set() + duplicates = set() + for item in lst: + if item in seen: + duplicates.add(item) + else: + seen.add(item) + return list(duplicates) + +# Usage: +data = [1, 2, 3, 2, 4, 5, 1] +print(find_duplicates(data)) # Output: [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 new file mode 100644 index 00000000..32b27dd6 --- /dev/null +++ b/snippets/python/list-manipulation/find-intersection-of-two-lists.md @@ -0,0 +1,16 @@ +--- +Title: Find Intersection of Two Lists +Description: Finds the common elements between two lists. +Author: axorax +Tags: python,list,intersection,utility +--- + +``` +def list_intersection(lst1, lst2): + return [item for item in lst1 if item in lst2] + +# Usage: +list_a = [1, 2, 3, 4] +list_b = [3, 4, 5, 6] +print(list_intersection(list_a, list_b)) # Output: [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 new file mode 100644 index 00000000..b7a94dbe --- /dev/null +++ b/snippets/python/list-manipulation/find-maximum-difference-in-list.md @@ -0,0 +1,17 @@ +--- +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 +--- + +``` +def max_difference(lst): + if not lst or len(lst) < 2: + return 0 + return max(lst) - min(lst) + +# Usage: +data = [10, 3, 5, 20, 7] +print(max_difference(data)) # Output: 17 +``` diff --git a/snippets/python/list-manipulation/flatten-nested-list.md b/snippets/python/list-manipulation/flatten-nested-list.md new file mode 100644 index 00000000..3eba7908 --- /dev/null +++ b/snippets/python/list-manipulation/flatten-nested-list.md @@ -0,0 +1,15 @@ +--- +Title: Flatten Nested List +Description: Flattens a multi-dimensional list into a single list. +Author: dostonnabotov +Tags: python,list,flatten,utility +--- + +``` +def flatten_list(lst): + return [item for sublist in lst for item in sublist] + +# Usage: +nested_list = [[1, 2], [3, 4], [5]] +print(flatten_list(nested_list)) # Output: [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 new file mode 100644 index 00000000..e3f8d4d7 --- /dev/null +++ b/snippets/python/list-manipulation/flatten-unevenly-nested-lists.md @@ -0,0 +1,23 @@ +--- +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 +--- + +``` +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) + else: + yield item + +# Usage: +nested_list = [1, [2, [3, 4]], 5] +flattened = list(flatten(nested_list)) +print(flattened) # Output: [1, 2, 3, 4, 5] +``` diff --git a/snippets/python/list-manipulation/partition-list.md b/snippets/python/list-manipulation/partition-list.md new file mode 100644 index 00000000..75d5b277 --- /dev/null +++ b/snippets/python/list-manipulation/partition-list.md @@ -0,0 +1,17 @@ +--- +Title: Partition List +Description: Partitions a list into sublists of a given size. +Author: axorax +Tags: python,list,partition,utility +--- + +``` +def partition_list(lst, size): + for i in range(0, len(lst), size): + yield lst[i:i + 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]] +``` diff --git a/snippets/python/list-manipulation/remove-duplicates.md b/snippets/python/list-manipulation/remove-duplicates.md new file mode 100644 index 00000000..836879b2 --- /dev/null +++ b/snippets/python/list-manipulation/remove-duplicates.md @@ -0,0 +1,14 @@ +--- +Title: Remove Duplicates +Description: Removes duplicate elements from a list while maintaining order. +Author: dostonnabotov +Tags: python,list,duplicates,utility +--- + +``` +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] +``` diff --git a/snippets/python/math-and-numbers/calculate-compound-interest.md b/snippets/python/math-and-numbers/calculate-compound-interest.md new file mode 100644 index 00000000..dd358e93 --- /dev/null +++ b/snippets/python/math-and-numbers/calculate-compound-interest.md @@ -0,0 +1,15 @@ +--- +Title: Calculate Compound Interest +Description: Calculates compound interest for a given principal amount, rate, and time period. +Author: axorax +Tags: python,math,compound interest,finance +--- + +``` +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 +``` diff --git a/snippets/python/math-and-numbers/check-perfect-square.md b/snippets/python/math-and-numbers/check-perfect-square.md new file mode 100644 index 00000000..b76f1362 --- /dev/null +++ b/snippets/python/math-and-numbers/check-perfect-square.md @@ -0,0 +1,18 @@ +--- +Title: Check Perfect Square +Description: Checks if a number is a perfect square. +Author: axorax +Tags: python,math,perfect square,check +--- + +``` +def is_perfect_square(n): + if n < 0: + return False + root = int(n**0.5) + return root * root == n + +# Usage: +print(is_perfect_square(16)) # Output: True +print(is_perfect_square(20)) # Output: False +``` diff --git a/snippets/python/math-and-numbers/check-prime-number.md b/snippets/python/math-and-numbers/check-prime-number.md new file mode 100644 index 00000000..5519b3f6 --- /dev/null +++ b/snippets/python/math-and-numbers/check-prime-number.md @@ -0,0 +1,19 @@ +--- +Title: Check Prime Number +Description: Checks if a number is a prime number. +Author: dostonnabotov +Tags: python,math,prime,check +--- + +``` +def is_prime(n): + if n <= 1: + return False + for i in range(2, int(n**0.5) + 1): + if n % i == 0: + return False + return True + +# Usage: +print(is_prime(17)) # Output: 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 new file mode 100644 index 00000000..d860da03 --- /dev/null +++ b/snippets/python/math-and-numbers/convert-binary-to-decimal.md @@ -0,0 +1,15 @@ +--- +Title: Convert Binary to Decimal +Description: Converts a binary string to its decimal equivalent. +Author: axorax +Tags: python,math,binary,decimal,conversion +--- + +``` +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 +``` diff --git a/snippets/python/math-and-numbers/find-factorial.md b/snippets/python/math-and-numbers/find-factorial.md new file mode 100644 index 00000000..9161f2d8 --- /dev/null +++ b/snippets/python/math-and-numbers/find-factorial.md @@ -0,0 +1,16 @@ +--- +Title: Find Factorial +Description: Calculates the factorial of a number. +Author: dostonnabotov +Tags: python,math,factorial,utility +--- + +``` +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 new file mode 100644 index 00000000..73ce1088 --- /dev/null +++ b/snippets/python/math-and-numbers/find-lcm-least-common-multiple.md @@ -0,0 +1,15 @@ +--- +Title: Find LCM (Least Common Multiple) +Description: Calculates the least common multiple (LCM) of two numbers. +Author: axorax +Tags: python,math,lcm,gcd,utility +--- + +``` +def lcm(a, b): + return abs(a * b) // gcd(a, b) + +# Usage: +print(lcm(12, 15)) # Output: 60 +print(lcm(7, 5)) # Output: 35 +``` diff --git a/snippets/python/math-and-numbers/solve-quadratic-equation.md b/snippets/python/math-and-numbers/solve-quadratic-equation.md new file mode 100644 index 00000000..dd851041 --- /dev/null +++ b/snippets/python/math-and-numbers/solve-quadratic-equation.md @@ -0,0 +1,20 @@ +--- +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 +--- + +``` +import cmath + +def solve_quadratic(a, b, c): + discriminant = cmath.sqrt(b**2 - 4 * a * c) + root1 = (-b + discriminant) / (2 * a) + root2 = (-b - discriminant) / (2 * a) + 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)) +``` diff --git a/snippets/python/sqlite-database/create-sqlite-database-table.md b/snippets/python/sqlite-database/create-sqlite-database-table.md new file mode 100644 index 00000000..8064e867 --- /dev/null +++ b/snippets/python/sqlite-database/create-sqlite-database-table.md @@ -0,0 +1,32 @@ +--- +Title: Create SQLite Database Table +Description: Creates a table in an SQLite database with a dynamic schema. +Author: e3nviction +Tags: python,sqlite,database,table +--- + +``` +import sqlite3 + +def create_table(db_name, table_name, schema): + conn = sqlite3.connect(db_name) + cursor = conn.cursor() + schema_string = ', '.join([f'{col} {dtype}' for col, dtype in schema.items()]) + cursor.execute(f''' + CREATE TABLE IF NOT EXISTS {table_name} ( + {schema_string} + )''') + conn.commit() + conn.close() + +# Usage: +db_name = 'example.db' +table_name = 'users' +schema = { + 'id': 'INTEGER PRIMARY KEY', + 'name': 'TEXT', + 'age': 'INTEGER', + 'email': 'TEXT' +} +create_table(db_name, table_name, schema) +``` diff --git a/snippets/python/sqlite-database/insert-data-into-sqlite-table.md b/snippets/python/sqlite-database/insert-data-into-sqlite-table.md new file mode 100644 index 00000000..5957c382 --- /dev/null +++ b/snippets/python/sqlite-database/insert-data-into-sqlite-table.md @@ -0,0 +1,28 @@ +--- +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 +--- + +``` +import sqlite3 + +def insert_into_table(db_path, table_name, data): + with sqlite3.connect(db_path) as conn: + columns = ', '.join(data.keys()) + placeholders = ', '.join(['?'] * len(data)) + sql = f"INSERT INTO {table_name} ({columns}) VALUES ({placeholders})" + conn.execute(sql, tuple(data.values())) + conn.commit() + +# Usage: +db_path = 'example.db' +table_name = 'users' +data = { + 'name': 'John Doe', + 'email': 'john@example.com', + 'age': 30 +} +insert_into_table(db_path, table_name, data) +``` diff --git a/snippets/python/string-manipulation/capitalize-words.md b/snippets/python/string-manipulation/capitalize-words.md new file mode 100644 index 00000000..1849021f --- /dev/null +++ b/snippets/python/string-manipulation/capitalize-words.md @@ -0,0 +1,14 @@ +--- +Title: Capitalize Words +Description: Capitalizes the first letter of each word in a string. +Author: axorax +Tags: python,string,capitalize,utility +--- + +``` +def capitalize_words(s): + return ' '.join(word.capitalize() for word in s.split()) + +# Usage: +print(capitalize_words('hello world')) # Output: 'Hello World' +``` diff --git a/snippets/python/string-manipulation/check-anagram.md b/snippets/python/string-manipulation/check-anagram.md new file mode 100644 index 00000000..8f947baa --- /dev/null +++ b/snippets/python/string-manipulation/check-anagram.md @@ -0,0 +1,14 @@ +--- +Title: Check Anagram +Description: Checks if two strings are anagrams of each other. +Author: SteliosGee +Tags: python,string,anagram,check,utility +--- + +``` +def is_anagram(s1, s2): + return sorted(s1) == sorted(s2) + +# Usage: +print(is_anagram('listen', 'silent')) # Output: True +``` diff --git a/snippets/python/string-manipulation/check-palindrome.md b/snippets/python/string-manipulation/check-palindrome.md new file mode 100644 index 00000000..ebdf8be6 --- /dev/null +++ b/snippets/python/string-manipulation/check-palindrome.md @@ -0,0 +1,15 @@ +--- +Title: Check Palindrome +Description: Checks if a string is a palindrome. +Author: dostonnabotov +Tags: python,string,palindrome,utility +--- + +``` +def is_palindrome(s): + s = s.lower().replace(' ', '') + return s == s[::-1] + +# Usage: +print(is_palindrome('A man a plan a canal Panama')) # Output: 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 new file mode 100644 index 00000000..8fb96640 --- /dev/null +++ b/snippets/python/string-manipulation/convert-snake-case-to-camel-case.md @@ -0,0 +1,15 @@ +--- +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 +--- + +``` +def snake_to_camel(s): + parts = s.split('_') + return parts[0] + ''.join(word.capitalize() for word in parts[1:]) + +# Usage: +print(snake_to_camel('hello_world')) # Output: 'helloWorld' +``` diff --git a/snippets/python/string-manipulation/convert-string-to-ascii.md b/snippets/python/string-manipulation/convert-string-to-ascii.md new file mode 100644 index 00000000..444bf0d6 --- /dev/null +++ b/snippets/python/string-manipulation/convert-string-to-ascii.md @@ -0,0 +1,14 @@ +--- +Title: Convert String to ASCII +Description: Converts a string into its ASCII representation. +Author: axorax +Tags: python,string,ascii,convert,utility +--- + +``` +def string_to_ascii(s): + return [ord(char) for char in s] + +# Usage: +print(string_to_ascii('hello')) # Output: [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 new file mode 100644 index 00000000..a56b8568 --- /dev/null +++ b/snippets/python/string-manipulation/count-character-frequency.md @@ -0,0 +1,16 @@ +--- +Title: Count Character Frequency +Description: Counts the frequency of each character in a string. +Author: axorax +Tags: python,string,character-frequency,utility +--- + +``` +from collections import Counter + +def char_frequency(s): + return dict(Counter(s)) + +# Usage: +print(char_frequency('hello')) # Output: {'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 new file mode 100644 index 00000000..e18e0a3d --- /dev/null +++ b/snippets/python/string-manipulation/count-vowels.md @@ -0,0 +1,15 @@ +--- +Title: Count Vowels +Description: Counts the number of vowels in a string. +Author: SteliosGee +Tags: python,string,vowels,count,utility +--- + +``` +def count_vowels(s): + vowels = 'aeiou' + return len([char for char in s.lower() if char in vowels]) + +# Usage: +print(count_vowels('hello')) # Output: 2 +``` diff --git a/snippets/python/string-manipulation/count-words.md b/snippets/python/string-manipulation/count-words.md new file mode 100644 index 00000000..ec5e207d --- /dev/null +++ b/snippets/python/string-manipulation/count-words.md @@ -0,0 +1,14 @@ +--- +Title: Count Words +Description: Counts the number of words in a string. +Author: axorax +Tags: python,string,word-count,utility +--- + +``` +def count_words(s): + return len(s.split()) + +# Usage: +print(count_words('The quick brown fox')) # Output: 4 +``` diff --git a/snippets/python/string-manipulation/find-all-substrings.md b/snippets/python/string-manipulation/find-all-substrings.md new file mode 100644 index 00000000..105a7c68 --- /dev/null +++ b/snippets/python/string-manipulation/find-all-substrings.md @@ -0,0 +1,18 @@ +--- +Title: Find All Substrings +Description: Finds all substrings of a given string. +Author: axorax +Tags: python,string,substring,find,utility +--- + +``` +def find_substrings(s): + substrings = [] + for i in range(len(s)): + for j in range(i + 1, len(s) + 1): + substrings.append(s[i:j]) + return substrings + +# Usage: +print(find_substrings('abc')) # Output: ['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 new file mode 100644 index 00000000..e28b5355 --- /dev/null +++ b/snippets/python/string-manipulation/find-longest-word.md @@ -0,0 +1,15 @@ +--- +Title: Find Longest Word +Description: Finds the longest word in a string. +Author: axorax +Tags: python,string,longest-word,utility +--- + +``` +def find_longest_word(s): + words = s.split() + return max(words, key=len) if words else '' + +# Usage: +print(find_longest_word('The quick brown fox')) # Output: 'quick' +``` diff --git a/snippets/python/string-manipulation/find-unique-characters.md b/snippets/python/string-manipulation/find-unique-characters.md new file mode 100644 index 00000000..badc4c35 --- /dev/null +++ b/snippets/python/string-manipulation/find-unique-characters.md @@ -0,0 +1,14 @@ +--- +Title: Find Unique Characters +Description: Finds all unique characters in a string. +Author: axorax +Tags: python,string,unique,characters,utility +--- + +``` +def find_unique_chars(s): + return ''.join(sorted(set(s))) + +# Usage: +print(find_unique_chars('banana')) # Output: 'abn' +``` diff --git a/snippets/python/string-manipulation/remove-duplicate-characters.md b/snippets/python/string-manipulation/remove-duplicate-characters.md new file mode 100644 index 00000000..efd1cab4 --- /dev/null +++ b/snippets/python/string-manipulation/remove-duplicate-characters.md @@ -0,0 +1,15 @@ +--- +Title: Remove Duplicate Characters +Description: Removes duplicate characters from a string while maintaining the order. +Author: axorax +Tags: python,string,duplicates,remove,utility +--- + +``` +def remove_duplicate_chars(s): + seen = set() + return ''.join(char for char in s if not (char in seen or seen.add(char))) + +# Usage: +print(remove_duplicate_chars('programming')) # Output: 'progamin' +``` diff --git a/snippets/python/string-manipulation/remove-punctuation.md b/snippets/python/string-manipulation/remove-punctuation.md new file mode 100644 index 00000000..796ea3d0 --- /dev/null +++ b/snippets/python/string-manipulation/remove-punctuation.md @@ -0,0 +1,16 @@ +--- +Title: Remove Punctuation +Description: Removes punctuation from a string. +Author: SteliosGee +Tags: python,string,punctuation,remove,utility +--- + +``` +import string + +def remove_punctuation(s): + return s.translate(str.maketrans('', '', string.punctuation)) + +# Usage: +print(remove_punctuation('Hello, World!')) # Output: 'Hello World' +``` diff --git a/snippets/python/string-manipulation/remove-specific-characters.md b/snippets/python/string-manipulation/remove-specific-characters.md new file mode 100644 index 00000000..535f2668 --- /dev/null +++ b/snippets/python/string-manipulation/remove-specific-characters.md @@ -0,0 +1,14 @@ +--- +Title: Remove Specific Characters +Description: Removes specific characters from a string. +Author: axorax +Tags: python,string,remove,characters,utility +--- + +``` +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' +``` diff --git a/snippets/python/string-manipulation/remove-whitespace.md b/snippets/python/string-manipulation/remove-whitespace.md new file mode 100644 index 00000000..690c012f --- /dev/null +++ b/snippets/python/string-manipulation/remove-whitespace.md @@ -0,0 +1,14 @@ +--- +Title: Remove Whitespace +Description: Removes all whitespace from a string. +Author: axorax +Tags: python,string,whitespace,remove,utility +--- + +``` +def remove_whitespace(s): + return ''.join(s.split()) + +# Usage: +print(remove_whitespace('hello world')) # Output: 'helloworld' +``` diff --git a/snippets/python/string-manipulation/reverse-string.md b/snippets/python/string-manipulation/reverse-string.md new file mode 100644 index 00000000..2e5e74bb --- /dev/null +++ b/snippets/python/string-manipulation/reverse-string.md @@ -0,0 +1,14 @@ +--- +Title: Reverse String +Description: Reverses the characters in a string. +Author: dostonnabotov +Tags: python,string,reverse,utility +--- + +``` +def reverse_string(s): + return s[::-1] + +# Usage: +print(reverse_string('hello')) # Output: 'olleh' +``` diff --git a/snippets/python/string-manipulation/split-camel-case.md b/snippets/python/string-manipulation/split-camel-case.md new file mode 100644 index 00000000..70ca44c3 --- /dev/null +++ b/snippets/python/string-manipulation/split-camel-case.md @@ -0,0 +1,16 @@ +--- +Title: Split Camel Case +Description: Splits a camel case string into separate words. +Author: axorax +Tags: python,string,camel-case,split,utility +--- + +``` +import re + +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' +``` diff --git a/snippets/python/string-manipulation/truncate-string.md b/snippets/python/string-manipulation/truncate-string.md new file mode 100644 index 00000000..688daf45 --- /dev/null +++ b/snippets/python/string-manipulation/truncate-string.md @@ -0,0 +1,14 @@ +--- +Title: Truncate String +Description: Truncates a string to a specified length and adds an ellipsis. +Author: axorax +Tags: python,string,truncate,utility +--- + +``` +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 ...' +``` diff --git a/snippets/python/utilities/convert-bytes-to-human-readable-format.md b/snippets/python/utilities/convert-bytes-to-human-readable-format.md new file mode 100644 index 00000000..d92a51a9 --- /dev/null +++ b/snippets/python/utilities/convert-bytes-to-human-readable-format.md @@ -0,0 +1,17 @@ +--- +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 +--- + +``` +def bytes_to_human_readable(num): + for unit in ['B', 'KB', 'MB', 'GB', 'TB', 'PB']: + if num < 1024: + return f"{num:.2f} {unit}" + num /= 1024 + +# Usage: +print(bytes_to_human_readable(123456789)) # Output: '117.74 MB' +``` diff --git a/snippets/python/utilities/generate-random-string.md b/snippets/python/utilities/generate-random-string.md new file mode 100644 index 00000000..39c1d265 --- /dev/null +++ b/snippets/python/utilities/generate-random-string.md @@ -0,0 +1,18 @@ +--- +Title: Generate Random String +Description: Generates a random alphanumeric string. +Author: dostonnabotov +Tags: python,random,string,utility +--- + +``` +import random +import string + +def random_string(length): + letters_and_digits = string.ascii_letters + string.digits + return ''.join(random.choice(letters_and_digits) for _ in range(length)) + +# Usage: +print(random_string(10)) # Output: Random 10-character string +``` diff --git a/snippets/python/utilities/measure-execution-time.md b/snippets/python/utilities/measure-execution-time.md new file mode 100644 index 00000000..bb3c5276 --- /dev/null +++ b/snippets/python/utilities/measure-execution-time.md @@ -0,0 +1,23 @@ +--- +Title: Measure Execution Time +Description: Measures the execution time of a code block. +Author: dostonnabotov +Tags: python,time,execution,utility +--- + +``` +import time + +def measure_time(func, *args): + start = time.time() + result = func(*args) + end = time.time() + print(f'Execution time: {end - start:.6f} seconds') + return result + +# Usage: +def slow_function(): + time.sleep(2) + +measure_time(slow_function) +``` diff --git a/snippets/rust/basics/hello-world.md b/snippets/rust/basics/hello-world.md new file mode 100644 index 00000000..e41568c1 --- /dev/null +++ b/snippets/rust/basics/hello-world.md @@ -0,0 +1,12 @@ +--- +Title: Hello, World! +Description: Prints Hello, World! to the terminal. +Author: James-Beans +Tags: rust,printing,hello-world,utility +--- + +``` +fn main() { // Defines the main running function + println!("Hello, World!"); // Prints Hello, World! to the terminal. +} +``` diff --git a/snippets/rust/file-handling/find-files.md b/snippets/rust/file-handling/find-files.md new file mode 100644 index 00000000..00b0a443 --- /dev/null +++ b/snippets/rust/file-handling/find-files.md @@ -0,0 +1,27 @@ +--- +Title: Find Files +Description: Finds all files of the specified extension within a given directory. +Author: Mathys-Gasnier +Tags: rust,file,search +--- + +``` +fn find_files(directory: &str, file_type: &str) -> std::io::Result> { + let mut result = vec![]; + + for entry in std::fs::read_dir(directory)? { + let dir = entry?; + let path = dir.path(); + if dir.file_type().is_ok_and(|t| !t.is_file()) && + path.extension().is_some_and(|ext| ext != file_type) { + continue; + } + result.push(path) + } + + Ok(result) +} + +// Usage: +let files = find_files("/path/to/your/directory", ".pdf") +``` diff --git a/snippets/rust/file-handling/read-file-lines.md b/snippets/rust/file-handling/read-file-lines.md new file mode 100644 index 00000000..9fedf481 --- /dev/null +++ b/snippets/rust/file-handling/read-file-lines.md @@ -0,0 +1,20 @@ +--- +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 +--- + +``` +fn read_lines(file_name: &str) -> std::io::Result> + Ok( + std::fs::read_to_string(file_name)? + .lines() + .map(String::from) + .collect() + ) +} + +// Usage: +let lines = read_lines("path/to/file.txt").expect("Failed to read lines from file") +``` diff --git a/snippets/rust/icon.svg b/snippets/rust/icon.svg new file mode 100644 index 00000000..3f62b3c2 --- /dev/null +++ b/snippets/rust/icon.svg @@ -0,0 +1,9 @@ + + +Rust Logo +A black gear with the letter R in the center + + + + + diff --git a/snippets/rust/string-manipulation/capitalize-string.md b/snippets/rust/string-manipulation/capitalize-string.md new file mode 100644 index 00000000..93d23947 --- /dev/null +++ b/snippets/rust/string-manipulation/capitalize-string.md @@ -0,0 +1,19 @@ +--- +Title: Capitalize String +Description: Makes the first letter of a string uppercase. +Author: Mathys-Gasnier +Tags: rust,string,capitalize,utility +--- + +``` +fn capitalized(str: &str) -> String { + let mut chars = str.chars(); + match chars.next() { + None => String::new(), + Some(f) => f.to_uppercase().chain(chars).collect(), + } +} + +// Usage: +assert_eq!(capitalized("lower_case"), "Lower_case") +``` diff --git a/snippets/scss/animations/fade-in-animation.md b/snippets/scss/animations/fade-in-animation.md new file mode 100644 index 00000000..26d6eb4f --- /dev/null +++ b/snippets/scss/animations/fade-in-animation.md @@ -0,0 +1,21 @@ +--- +Title: Fade In Animation +Description: Animates the fade-in effect. +Author: dostonnabotov +Tags: scss,animation,fade,css +--- + +``` +@keyframes fade-in { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +@mixin fade-in($duration: 1s, $easing: ease-in-out) { + animation: fade-in $duration $easing; +} +``` diff --git a/snippets/scss/animations/slide-in-from-left.md b/snippets/scss/animations/slide-in-from-left.md new file mode 100644 index 00000000..c9fe9936 --- /dev/null +++ b/snippets/scss/animations/slide-in-from-left.md @@ -0,0 +1,21 @@ +--- +Title: Slide In From Left +Description: Animates content sliding in from the left. +Author: dostonnabotov +Tags: scss,animation,slide,css +--- + +``` +@keyframes slide-in-left { + from { + transform: translateX(-100%); + } + to { + transform: translateX(0); + } +} + +@mixin slide-in-left($duration: 0.5s, $easing: ease-out) { + animation: slide-in-left $duration $easing; +} +``` diff --git a/snippets/scss/borders-shadows/border-radius-helper.md b/snippets/scss/borders-shadows/border-radius-helper.md new file mode 100644 index 00000000..567ae887 --- /dev/null +++ b/snippets/scss/borders-shadows/border-radius-helper.md @@ -0,0 +1,12 @@ +--- +Title: Border Radius Helper +Description: Applies a customizable border-radius. +Author: dostonnabotov +Tags: scss,border,radius,css +--- + +``` +@mixin border-radius($radius: 4px) { + border-radius: $radius; +} +``` diff --git a/snippets/scss/borders-shadows/box-shadow-helper.md b/snippets/scss/borders-shadows/box-shadow-helper.md new file mode 100644 index 00000000..4a752254 --- /dev/null +++ b/snippets/scss/borders-shadows/box-shadow-helper.md @@ -0,0 +1,12 @@ +--- +Title: Box Shadow Helper +Description: Generates a box shadow with customizable values. +Author: dostonnabotov +Tags: scss,box-shadow,css,effects +--- + +``` +@mixin box-shadow($x: 0px, $y: 4px, $blur: 10px, $spread: 0px, $color: rgba(0, 0, 0, 0.1)) { + box-shadow: $x $y $blur $spread $color; +} +``` diff --git a/snippets/scss/components/primary-button.md b/snippets/scss/components/primary-button.md new file mode 100644 index 00000000..b57d6341 --- /dev/null +++ b/snippets/scss/components/primary-button.md @@ -0,0 +1,21 @@ +--- +Title: Primary Button +Description: Generates a styled primary button. +Author: dostonnabotov +Tags: scss,button,primary,css +--- + +``` +@mixin primary-button($bg: #007bff, $color: #fff) { + background-color: $bg; + color: $color; + padding: 0.5rem 1rem; + border: none; + border-radius: 4px; + cursor: pointer; + + &:hover { + background-color: darken($bg, 10%); + } +} +``` diff --git a/snippets/scss/icon.svg b/snippets/scss/icon.svg new file mode 100644 index 00000000..e68fea23 --- /dev/null +++ b/snippets/scss/icon.svg @@ -0,0 +1,5 @@ + +Sass or SCSS Logo +The word Sass in pink cursive font + + diff --git a/snippets/scss/layouts/aspect-ratio.md b/snippets/scss/layouts/aspect-ratio.md new file mode 100644 index 00000000..bf742681 --- /dev/null +++ b/snippets/scss/layouts/aspect-ratio.md @@ -0,0 +1,21 @@ +--- +Title: Aspect Ratio +Description: Ensures that elements maintain a specific aspect ratio. +Author: dostonnabotov +Tags: scss,aspect-ratio,layout,css +--- + +``` +@mixin aspect-ratio($width, $height) { + position: relative; + width: 100%; + padding-top: ($height / $width) * 100%; + > * { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + } +} +``` diff --git a/snippets/scss/layouts/flex-center.md b/snippets/scss/layouts/flex-center.md new file mode 100644 index 00000000..b0538d81 --- /dev/null +++ b/snippets/scss/layouts/flex-center.md @@ -0,0 +1,14 @@ +--- +Title: Flex Center +Description: A mixin to center content using flexbox. +Author: dostonnabotov +Tags: scss,flex,center,css +--- + +``` +@mixin flex-center { + display: flex; + justify-content: center; + align-items: center; +} +``` diff --git a/snippets/scss/layouts/grid-container.md b/snippets/scss/layouts/grid-container.md new file mode 100644 index 00000000..09772ee0 --- /dev/null +++ b/snippets/scss/layouts/grid-container.md @@ -0,0 +1,14 @@ +--- +Title: Grid Container +Description: Creates a responsive grid container with customizable column counts. +Author: dostonnabotov +Tags: scss,grid,layout,css +--- + +``` +@mixin grid-container($columns: 12, $gap: 1rem) { + display: grid; + grid-template-columns: repeat($columns, 1fr); + gap: $gap; +} +``` diff --git a/snippets/scss/typography/font-import-helper.md b/snippets/scss/typography/font-import-helper.md new file mode 100644 index 00000000..ccbb99f5 --- /dev/null +++ b/snippets/scss/typography/font-import-helper.md @@ -0,0 +1,18 @@ +--- +Title: Font Import Helper +Description: Simplifies importing custom fonts in Sass. +Author: dostonnabotov +Tags: sass,mixin,fonts,css +--- + +``` +@mixin import-font($family, $weight: 400, $style: normal) { + @font-face { + font-family: #{$family}; + font-weight: #{$weight}; + font-style: #{$style}; + src: url('/fonts/#{$family}-#{$weight}.woff2') format('woff2'), + url('/fonts/#{$family}-#{$weight}.woff') format('woff'); + } +} +``` diff --git a/snippets/scss/typography/line-clamp-mixin.md b/snippets/scss/typography/line-clamp-mixin.md new file mode 100644 index 00000000..837129c7 --- /dev/null +++ b/snippets/scss/typography/line-clamp-mixin.md @@ -0,0 +1,15 @@ +--- +Title: Line Clamp Mixin +Description: A Sass mixin to clamp text to a specific number of lines. +Author: dostonnabotov +Tags: sass,mixin,typography,css +--- + +``` +@mixin line-clamp($number) { + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: $number; + overflow: hidden; +} +``` diff --git a/snippets/scss/typography/text-gradient.md b/snippets/scss/typography/text-gradient.md new file mode 100644 index 00000000..616684cb --- /dev/null +++ b/snippets/scss/typography/text-gradient.md @@ -0,0 +1,14 @@ +--- +Title: Text Gradient +Description: Adds a gradient color effect to text. +Author: dostonnabotov +Tags: sass,mixin,gradient,text,css +--- + +``` +@mixin text-gradient($from, $to) { + background: linear-gradient(to right, $from, $to); + -webkit-background-clip: text; + -webkit-text-fill-color: transparent; +} +``` diff --git a/snippets/scss/typography/text-overflow-ellipsis.md b/snippets/scss/typography/text-overflow-ellipsis.md new file mode 100644 index 00000000..70138e20 --- /dev/null +++ b/snippets/scss/typography/text-overflow-ellipsis.md @@ -0,0 +1,14 @@ +--- +Title: Text Overflow Ellipsis +Description: Ensures long text is truncated with an ellipsis. +Author: dostonnabotov +Tags: sass,mixin,text,css +--- + +``` +@mixin text-ellipsis { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} +``` diff --git a/snippets/scss/utilities/clearfix.md b/snippets/scss/utilities/clearfix.md new file mode 100644 index 00000000..7a726296 --- /dev/null +++ b/snippets/scss/utilities/clearfix.md @@ -0,0 +1,16 @@ +--- +Title: Clearfix +Description: Provides a clearfix utility for floating elements. +Author: dostonnabotov +Tags: scss,clearfix,utility,css +--- + +``` +@mixin clearfix { + &::after { + content: ''; + display: block; + clear: both; + } +} +``` diff --git a/snippets/scss/utilities/responsive-breakpoints.md b/snippets/scss/utilities/responsive-breakpoints.md new file mode 100644 index 00000000..4b822dc9 --- /dev/null +++ b/snippets/scss/utilities/responsive-breakpoints.md @@ -0,0 +1,20 @@ +--- +Title: Responsive Breakpoints +Description: Generates media queries for responsive design. +Author: dostonnabotov +Tags: scss,responsive,media-queries,css +--- + +``` +@mixin breakpoint($breakpoint) { + @if $breakpoint == sm { + @media (max-width: 576px) { @content; } + } @else if $breakpoint == md { + @media (max-width: 768px) { @content; } + } @else if $breakpoint == lg { + @media (max-width: 992px) { @content; } + } @else if $breakpoint == xl { + @media (max-width: 1200px) { @content; } + } +} +``` From 4bc52a61a50eb13b3e01007b11b2eee3007e6d6f Mon Sep 17 00:00:00 2001 From: Mathys-Gasnier Date: Wed, 1 Jan 2025 12:43:26 +0100 Subject: [PATCH 03/10] Consolidate new data using `utils/consolidateSnippets.js` --- public/data/_index.json | 66 +- public/data/c.json | 103 +- public/data/cpp.json | 110 +- public/data/css.json | 410 +++---- public/data/html.json | 152 +-- public/data/javascript.json | 2278 ++++++++++++++--------------------- public/data/python.json | 2036 +++++++++++++------------------ public/data/rust.json | 153 +-- public/data/scss.json | 450 +++---- 9 files changed, 2353 insertions(+), 3405 deletions(-) diff --git a/public/data/_index.json b/public/data/_index.json index 5dc86960..941d99f0 100644 --- a/public/data/_index.json +++ b/public/data/_index.json @@ -1,34 +1,34 @@ [ - { - "lang": "JavaScript", - "icon": "/icons/javascript.svg" - }, - { - "lang": "CSS", - "icon": "/icons/css.svg" - }, - { - "lang": "HTML", - "icon": "/icons/html5.svg" - }, - { - "lang": "Python", - "icon": "/icons/python.svg" - }, - { - "lang": "SCSS", - "icon": "/icons/sass.svg" - }, - { - "lang": "CPP", - "icon": "/icons/cpp.svg" - }, - { - "lang": "C", - "icon": "/icons/c.svg" - }, - { - "lang": "Rust", - "icon": "/icons/rust.svg" - } -] + { + "lang": "C", + "icon": "/icons/c.svg" + }, + { + "lang": "Cpp", + "icon": "/icons/cpp.svg" + }, + { + "lang": "Css", + "icon": "/icons/css.svg" + }, + { + "lang": "Html", + "icon": "/icons/html.svg" + }, + { + "lang": "Javascript", + "icon": "/icons/javascript.svg" + }, + { + "lang": "Python", + "icon": "/icons/python.svg" + }, + { + "lang": "Rust", + "icon": "/icons/rust.svg" + }, + { + "lang": "Scss", + "icon": "/icons/scss.svg" + } +] \ No newline at end of file diff --git a/public/data/c.json b/public/data/c.json index 1c2e98f9..af65b1fa 100644 --- a/public/data/c.json +++ b/public/data/c.json @@ -1,59 +1,48 @@ [ - { - "categoryName": "Basics", - "snippets": [ - { - "title": "Hello, World!", - "description": "Prints Hello, World! to the terminal.", - "code": [ - "#include // Includes the input/output library", - "", - "int main() { // Defines the main function", - " printf(\"Hello, World!\\n\") // Outputs Hello, World! and a newline", - "", - " return 0; // indicate the program executed successfully", - "}" - ], - "tags": ["c", "printing", "hello-world", "utility"], - "author": "0xHouss" - } - ] - }, - { - "categoryName": "Mathematical Functions", - "snippets": [ - { - "title": "Factorial Function", - "description": "Calculates the factorial of a number.", - "code": [ - "int factorial(int x) {", - " int y = 1;", - "", - " for (int i = 2; i <= x; i++)", - " y *= i;", - "", - " return y;", - "}" - ], - "tags": ["c", "math", "factorial", "utility"], - "author": "0xHouss" - }, - { - "title": "Power Function", - "description": "Calculates the power of a number.", - "code": [ - "int power(int x, int n) {", - " int y = 1;", - "", - " for (int i = 0; i < n; i++)", - " y *= x;", - "", - " return y;", - "}" - ], - "tags": ["c", "math", "power", "utility"], - "author": "0xHouss" - } - ] - } + { + "categoryName": "Basics", + "snippets": [ + { + "title": "Hello, World!", + "description": "Prints Hello, World! to the terminal.", + "author": "0xHouss", + "tags": [ + "c", + "printing", + "hello-world", + "utility" + ], + "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" + } + ] + }, + { + "categoryName": "Mathematical Functions", + "snippets": [ + { + "title": "Factorial Function", + "description": "Calculates the factorial of a number.", + "author": "0xHouss", + "tags": [ + "c", + "math", + "factorial", + "utility" + ], + "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" + ], + "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" + } + ] + } ] \ No newline at end of file diff --git a/public/data/cpp.json b/public/data/cpp.json index d1ff6b2d..69f6162f 100644 --- a/public/data/cpp.json +++ b/public/data/cpp.json @@ -1,64 +1,48 @@ [ - { - "categoryName": "Basics", - "snippets": [ - { - "title": "Hello, World!", - "description": "Prints Hello, World! to the terminal.", - "code": [ - "#include // Includes the input/output stream library", - "", - "int main() { // Defines the main function", - " std::cout << \"Hello, World!\" << std::endl; // Outputs Hello, World! and a newline", - " return 0; // indicate the program executed successfully", - "}" - ], - "tags": ["cpp", "printing", "hello-world", "utility"], - "author": "James-Beans" - } - ] - }, - { - "categoryName": "String Manipulation", - "snippets": [ - { - "title": "Reverse String", - "description": "Reverses the characters in a string.", - "code": [ - "#include ", - "#include ", - "", - "std::string reverseString(const std::string& input) {", - " std::string reversed = input;", - " std::reverse(reversed.begin(), reversed.end());", - " return reversed;", - "}" - ], - "tags": ["cpp", "array", "reverse", "utility"], - "author": "Vaibhav-kesarwani" - }, - { - "title": "Split String", - "description": "Splits a string by a delimiter", - "code": [ - "#include ", - "#include ", - "", - "std::vector split_string(std::string str, std::string delim) {", - " std::vector splits;", - " int i = 0, j;", - " int inc = delim.length();", - " while (j != std::string::npos) {", - " j = str.find(delim, i);", - " splits.push_back(str.substr(i, j - i));", - " i = j + inc;", - " }", - " return splits;", - "}" - ], - "tags": ["cpp", "string", "split", "utility"], - "author": "saminjay" - } - ] - } -] + { + "categoryName": "Basics", + "snippets": [ + { + "title": "Hello, World!", + "description": "Prints Hello, World! to the terminal.", + "author": "James-Beans", + "tags": [ + "cpp", + "printing", + "hello-world", + "utility" + ], + "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" + } + ] + }, + { + "categoryName": "String Manipulation", + "snippets": [ + { + "title": "Reverse String", + "description": "Reverses the characters in a string.", + "author": "Vaibhav-kesarwani", + "tags": [ + "cpp", + "array", + "reverse", + "utility" + ], + "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" + }, + { + "title": "Split String", + "description": "Splits a string by a delimiter", + "author": "saminjay", + "tags": [ + "cpp", + "string", + "split", + "utility" + ], + "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" + } + ] + } +] \ No newline at end of file diff --git a/public/data/css.json b/public/data/css.json index cf65a6a1..6d91f46b 100644 --- a/public/data/css.json +++ b/public/data/css.json @@ -1,249 +1,163 @@ [ - { - "categoryName": "Typography", - "snippets": [ - { - "title": "Responsive Font Sizing", - "description": "Adjusts font size based on viewport width.", - "code": ["h1 {", " font-size: calc(1.5rem + 2vw);", "}"], - "tags": ["css", "font", "responsive", "typography"], - "author": "dostonnabotov" - }, - { - "title": "Letter Spacing", - "description": "Adds space between letters for better readability.", - "code": ["p {", " letter-spacing: 0.05em;", "}"], - "tags": ["css", "typography", "spacing"], - "author": "dostonnabotov" - } - ] - }, - { - "categoryName": "Layouts", - "snippets": [ - { - "title": "Grid layout", - "description": "Equal sized items in a responsive grid", - "code": [ - ".grid-container {", - " display: grid", - " grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));", - "/* Explanation:", - "- `auto-fit`: Automatically fits as many columns as possible within the container.", - "- `minmax(250px, 1fr)`: Defines a minimum column size of 250px and a maximum size of 1fr (fraction of available space).", - "*/", - "}", - "" - ], - "tags": ["css", "layout", "grid"], - "author": "xshubhamg" - }, - { - "title": "Sticky Footer", - "description": "Ensures the footer always stays at the bottom of the page.", - "code": [ - "body {", - " display: flex;", - " flex-direction: column;", - " min-height: 100vh;", - "}", - "", - "footer {", - " margin-top: auto;", - "}" - ], - "tags": ["css", "layout", "footer", "sticky"], - "author": "dostonnabotov" - }, - { - "title": "Equal-Width Columns", - "description": "Creates columns with equal widths using flexbox.", - "code": [ - ".columns {", - " display: flex;", - " justify-content: space-between;", - "}", - "", - ".column {", - " flex: 1;", - " margin: 0 10px;", - "}" - ], - "tags": ["css", "flexbox", "columns", "layout"], - "author": "dostonnabotov" - }, - { - "title": "CSS Reset", - "description": "Resets some default browser styles, ensuring consistency across browsers.", - "code": [ - "* {", - " margin: 0;", - " padding: 0;", - " box-sizing: border-box", - "}" - ], - "tags": ["css", "reset", "browser", "layout"], - "author": "AmeerMoustafa" - }, - { - "title": "Responsive Design", - "description": "The different responsive breakpoints.", - "code": [ - "/* Phone */", - ".element {", - " margin: 0 10%", - "}", - "", - "/* Tablet */", - "@media (min-width: 640px) {", - " .element {", - " margin: 0 20%", - " }", - "}", - "", - "/* Desktop base */", - "@media (min-width: 768px) {", - " .element {", - " margin: 0 30%", - " }", - "}", - "", - "/* Desktop large */", - "@media (min-width: 1024px) {", - " .element {", - " margin: 0 40%", - " }", - "}", - "", - "/* Desktop extra large */", - "@media (min-width: 1280px) {", - " .element {", - " margin: 0 60%", - " }", - "}", - "", - "/* Desktop bige */", - "@media (min-width: 1536px) {", - " .element {", - " margin: 0 80%", - " }", - "}" - ], - "tags": ["css", "responsive"], - "author": "kruimol" - } - ] - }, - { - "categoryName": "Buttons", - "snippets": [ - { - "title": "Button Hover Effect", - "description": "Creates a hover effect with a color transition.", - "code": [ - ".button {", - " background-color: #007bff;", - " color: white;", - " padding: 10px 20px;", - " border: none;", - " border-radius: 5px;", - " cursor: pointer;", - " transition: background-color 0.3s ease;", - "}", - "", - ".button:hover {", - " background-color: #0056b3;", - "}" - ], - "tags": ["css", "button", "hover", "transition"], - "author": "dostonnabotov" - }, - { - "title": "3D Button Effect", - "description": "Adds a 3D effect to a button when clicked.", - "code": [ - ".button {", - " background-color: #28a745;", - " color: white;", - " padding: 10px 20px;", - " border: none;", - " border-radius: 5px;", - " box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);", - " transition: transform 0.1s;", - "}", - "", - ".button:active {", - " transform: translateY(2px);", - " box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);", - "}" - ], - "tags": ["css", "button", "3D", "effect"], - "author": "dostonnabotov" - }, - { - "title": "MacOS Button", - "description": "A macOS-like button style, with hover and shading effects.", - "code": [ - ".button {", - " font: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica,;", - " background: #0a85ff;", - " color: #fff;", - " padding: 8px 12px;", - " border: none;", - " margin: 4px;", - " border-radius: 10px;", - " cursor: pointer;", - " box-shadow: inset 0 1px 1px #fff2, 0px 2px 3px -2px rgba(0, 0, 0, 0.3) !important; /*This is really performance heavy*/", - " font-size: 14px;", - " display: flex;", - " align-items: center;", - " justify-content: center;", - " text-decoration: none;", - " transition: all 150ms cubic-bezier(0.175, 0.885, 0.32, 1.275);", - "}", - ".button:hover {", - " background: #0974ee;", - " color: #fff", - "}" - ], - "tags": ["css", "button", "macos", "hover", "transition"], - "author": "e3nviction" - } - ] - }, - { - "categoryName": "Effects", - "snippets": [ - { - "title": "Blur Background", - "description": "Applies a blur effect to the background of an element.", - "code": [ - ".blur-background {", - " backdrop-filter: blur(10px);", - " background: rgba(255, 255, 255, 0.5);", - "}" - ], - "tags": ["css", "blur", "background", "effects"], - "author": "dostonnabotov" - }, - { - "title": "Hover Glow Effect", - "description": "Adds a glowing effect on hover.", - "code": [ - ".glow {", - " background-color: #f39c12;", - " padding: 10px 20px;", - " border-radius: 5px;", - " transition: box-shadow 0.3s ease;", - "}", - "", - ".glow:hover {", - " box-shadow: 0 0 15px rgba(243, 156, 18, 0.8);", - "}" - ], - "tags": ["css", "hover", "glow", "effects"], - "author": "dostonnabotov" - } - ] - } -] + { + "categoryName": "Buttons", + "snippets": [ + { + "title": "3D Button Effect", + "description": "Adds a 3D effect to a button when clicked.", + "author": "dostonnabotov", + "tags": [ + "css", + "button", + "3D", + "effect" + ], + "code": ".button {\n background-color: #28a745;\n color: white;\n padding: 10px 20px;\n border: none;\n border-radius: 5px;\n box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);\n transition: transform 0.1s;\n}\n\n.button:active {\n transform: translateY(2px);\n box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);\n}\n" + }, + { + "title": "Button Hover Effect", + "description": "Creates a hover effect with a color transition.", + "author": "dostonnabotov", + "tags": [ + "css", + "button", + "hover", + "transition" + ], + "code": ".button {\n background-color: #007bff;\n color: white;\n padding: 10px 20px;\n border: none;\n border-radius: 5px;\n cursor: pointer;\n transition: background-color 0.3s ease;\n}\n\n.button:hover {\n background-color: #0056b3;\n}\n" + }, + { + "title": "MacOS Button", + "description": "A macOS-like button style, with hover and shading effects.", + "author": "e3nviction", + "tags": [ + "css", + "button", + "macos", + "hover", + "transition" + ], + "code": ".button {\n font: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica,;\n background: #0a85ff;\n color: #fff;\n padding: 8px 12px;\n border: none;\n margin: 4px;\n border-radius: 10px;\n cursor: pointer;\n box-shadow: inset 0 1px 1px #fff2, 0px 2px 3px -2px rgba(0, 0, 0, 0.3) !important; /*This is really performance heavy*/\n font-size: 14px;\n display: flex;\n align-items: center;\n justify-content: center;\n text-decoration: none;\n transition: all 150ms cubic-bezier(0.175, 0.885, 0.32, 1.275);\n}\n.button:hover {\n background: #0974ee;\n color: #fff\n}\n" + } + ] + }, + { + "categoryName": "Effects", + "snippets": [ + { + "title": "Blur Background", + "description": "Applies a blur effect to the background of an element.", + "author": "dostonnabotov", + "tags": [ + "css", + "blur", + "background", + "effects" + ], + "code": ".blur-background {\n backdrop-filter: blur(10px);\n background: rgba(255, 255, 255, 0.5);\n}\n" + }, + { + "title": "Hover Glow Effect", + "description": "Adds a glowing effect on hover.", + "author": "dostonnabotov", + "tags": [ + "css", + "hover", + "glow", + "effects" + ], + "code": ".glow {\n background-color: #f39c12;\n padding: 10px 20px;\n border-radius: 5px;\n transition: box-shadow 0.3s ease;\n}\n\n.glow:hover {\n box-shadow: 0 0 15px rgba(243, 156, 18, 0.8);\n}\n" + } + ] + }, + { + "categoryName": "Layouts", + "snippets": [ + { + "title": "CSS Reset", + "description": "Resets some default browser styles, ensuring consistency across browsers.", + "author": "AmeerMoustafa", + "tags": [ + "css", + "reset", + "browser", + "layout" + ], + "code": "* {\n margin: 0;\n padding: 0;\n box-sizing: border-box\n}\n" + }, + { + "title": "Equal-Width Columns", + "description": "Creates columns with equal widths using flexbox.", + "author": "dostonnabotov", + "tags": [ + "css", + "flexbox", + "columns", + "layout" + ], + "code": ".columns {\n display: flex;\n justify-content: space-between;\n}\n\n.column {\n flex: 1;\n margin: 0 10px;\n}\n" + }, + { + "title": "Grid layout", + "description": "Equal sized items in a responsive grid", + "author": "xshubhamg", + "tags": [ + "css", + "layout", + "grid" + ], + "code": ".grid-container {\n display: grid\n grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));\n/* Explanation:\n- `auto-fit`: Automatically fits as many columns as possible within the container.\n- `minmax(250px, 1fr)`: Defines a minimum column size of 250px and a maximum size of 1fr (fraction of available space).\n*/\n}\n\n" + }, + { + "title": "Responsive Design", + "description": "The different responsive breakpoints.", + "author": "kruimol", + "tags": [ + "css", + "responsive" + ], + "code": "/* Phone */\n.element {\n margin: 0 10%\n}\n\n/* Tablet */\n@media (min-width: 640px) {\n .element {\n margin: 0 20%\n }\n}\n\n/* Desktop base */\n@media (min-width: 768px) {\n .element {\n margin: 0 30%\n }\n}\n\n/* Desktop large */\n@media (min-width: 1024px) {\n .element {\n margin: 0 40%\n }\n}\n\n/* Desktop extra large */\n@media (min-width: 1280px) {\n .element {\n margin: 0 60%\n }\n}\n\n/* Desktop bige */\n@media (min-width: 1536px) {\n .element {\n margin: 0 80%\n }\n}\n" + }, + { + "title": "Sticky Footer", + "description": "Ensures the footer always stays at the bottom of the page.", + "author": "dostonnabotov", + "tags": [ + "css", + "layout", + "footer", + "sticky" + ], + "code": "body {\n display: flex;\n flex-direction: column;\n min-height: 100vh;\n}\n\nfooter {\n margin-top: auto;\n}\n" + } + ] + }, + { + "categoryName": "Typography", + "snippets": [ + { + "title": "Letter Spacing", + "description": "Adds space between letters for better readability.", + "author": "dostonnabotov", + "tags": [ + "css", + "typography", + "spacing" + ], + "code": "p {\n letter-spacing: 0.05em;\n}\n" + }, + { + "title": "Responsive Font Sizing", + "description": "Adjusts font size based on viewport width.", + "author": "dostonnabotov", + "tags": [ + "css", + "font", + "responsive", + "typography" + ], + "code": "h1 {\n font-size: calc(1.5rem + 2vw);\n}\n" + } + ] + } +] \ No newline at end of file diff --git a/public/data/html.json b/public/data/html.json index 298d0ec4..7ef58ba0 100644 --- a/public/data/html.json +++ b/public/data/html.json @@ -1,119 +1,35 @@ [ - { - "language": "html", - "categoryName": "Basic Layouts", - "snippets": [ - { - "title": "Sticky Header-Footer Layout", - "description": "Full-height layout with sticky header and footer, using modern viewport units and flexbox.", - "code": [ - "", - "", - " ", - " ", - " ", - " ", - "
header
", - "
body/content
", - "
footer
", - " ", - "" - ], - "tags": ["html", "css", "layout", "sticky", "flexbox", "viewport"], - "author": "GreenMan36" - }, - { - "title": "Grid Layout with Navigation", - "description": "Full-height grid layout with header navigation using nesting syntax.", - "code": [ - "", - "", - " ", - " ", - " ", - " ", - "
", - " Header", - " ", - "
", - "
Main Content
", - "
Footer
", - " ", - "" - ], - "tags": ["html", "css", "layout", "sticky", "grid", "full-height"], - "author": "GreenMan36" - } - ] - } -] + { + "categoryName": "Basic Layouts", + "snippets": [ + { + "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" + ], + "code": "\n\n \n \n \n \n
\n Header\n \n
\n
Main Content
\n
Footer
\n \n\n" + }, + { + "title": "Sticky Header-Footer Layout", + "description": "Full-height layout with sticky header and footer, using modern viewport units and flexbox.", + "author": "GreenMan36", + "tags": [ + "html", + "css", + "layout", + "sticky", + "flexbox", + "viewport" + ], + "code": "\n\n \n \n \n \n
header
\n
body/content
\n
footer
\n \n\n" + } + ] + } +] \ No newline at end of file diff --git a/public/data/javascript.json b/public/data/javascript.json index 583c6e13..5134f797 100644 --- a/public/data/javascript.json +++ b/public/data/javascript.json @@ -1,1361 +1,921 @@ [ - { - "categoryName": "Basics", - "snippets": [ - { - "title": "Hello, World!", - "description": "Prints Hello, World! to the terminal.", - "code": [ - "console.log(\"Hello, World!\"); // Prints Hello, World! to the console" - ], - "tags": ["javascript", "printing", "hello-world", "utility"], - "author": "James-Beans" - } - ] - }, - { - "categoryName": "Array Manipulation", - "snippets": [ - { - "title": "Remove Duplicates", - "description": "Removes duplicate values from an array.", - "code": [ - "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]" - ], - "tags": ["javascript", "array", "deduplicate", "utility"], - "author": "dostonnabotov" - }, - { - "title": "Flatten Array", - "description": "Flattens a multi-dimensional array.", - "code": [ - "const flattenArray = (arr) => arr.flat(Infinity);", - "", - "// Usage:", - "const nestedArray = [1, [2, [3, [4]]]];", - "console.log(flattenArray(nestedArray)); // Output: [1, 2, 3, 4]" - ], - "tags": ["javascript", "array", "flatten", "utility"], - "author": "dostonnabotov" - }, - { - "title": "Shuffle Array", - "description": "Shuffles an Array.", - "code": [ - "function shuffleArray(array) {", - " for (let i = array.length - 1; i >= 0; i--) {", - " const j = Math.floor(Math.random() * (i + 1));", - " [array[i], array[j]] = [array[j], array[i]];", - " }", - "}" - ], - "tags": ["javascript", "array", "shuffle", "utility"], - "author": "loxt-nixo" - }, - { - "title": "Zip Arrays", - "description": "Combines two arrays by pairing corresponding elements from each array.", - "code": [ - "const zip = (arr1, arr2) => arr1.map((value, index) => [value, arr2[index]]);", - "", - "// Usage:", - "const arr1 = ['a', 'b', 'c'];", - "const arr2 = [1, 2, 3];", - "console.log(zip(arr1, arr2)); // Output: [['a', 1], ['b', 2], ['c', 3]]" - ], - "tags": ["javascript", "array", "utility", "map"], - "author": "Swaraj-Singh-30" - } - ] - }, - { - "categoryName": "String Manipulation", - "snippets": [ - { - "title": "Slugify String", - "description": "Converts a string into a URL-friendly slug format.", - "code": [ - "const 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 -", - "};", - "", - "// 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'" - ], - "tags": ["javascript", "string", "slug", "utility"], - "author": "dostonnabotov" - }, - { - "title": "Capitalize String", - "description": "Capitalizes the first letter of a string.", - "code": [ - "const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);", - "", - "// Usage:", - "console.log(capitalize('hello')); // Output: 'Hello'" - ], - "tags": ["javascript", "string", "capitalize", "utility"], - "author": "dostonnabotov" - }, - { - "title": "Reverse String", - "description": "Reverses the characters in a string.", - "code": [ - "const reverseString = (str) => str.split('').reverse().join('');", - "", - "// Usage:", - "console.log(reverseString('hello')); // Output: 'olleh'" - ], - "tags": ["javascript", "string", "reverse", "utility"], - "author": "dostonnabotov" - }, - { - "title": "Truncate Text", - "description": "Truncates the text to a maximum length and appends '...' if the text exceeds the maximum length.", - "code": [ - "const truncateText = (text = '', maxLength = 50) => {", - " return `${text.slice(0, maxLength)}${text.length >= maxLength ? '...' : ''}`;", - "};", - "", - "// 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...'" - ], - "tags": ["javascript", "string", "truncate", "utility", "text"], - "author": "realvishalrana" - }, - { - "title": "Data with Prefix", - "description": "Adds a prefix and postfix to data, with a fallback value.", - "code": [ - "const dataWithPrefix = (data, fallback = '-', prefix = '', postfix = '') => {", - " return data ? `${prefix}${data}${postfix}` : fallback;", - "};", - "", - "// 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'" - ], - "tags": ["javascript", "data", "utility"], - "author": "realvishalrana" - }, - { - "title": "Check if String is a Palindrome", - "description": "Checks whether a given string is a palindrome.", - "code": [ - "function isPalindrome(str) {", - " const cleanStr = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();", - " return cleanStr === cleanStr.split('').reverse().join('');", - "}", - "", - "// Example usage:", - "console.log(isPalindrome('A man, a plan, a canal, Panama')); // Output: true" - ], - "tags": ["javascript", "check", "palindrome", "string"], - "author": "axorax" - }, - { - "title": "Count Words in a String", - "description": "Counts the number of words in a string.", - "code": [ - "function countWords(str) {", - " return str.trim().split(/\\s+/).length;", - "}", - "", - "// Example usage:", - "console.log(countWords('Hello world! This is a test.')); // Output: 6" - ], - "tags": ["javascript", "string", "manipulation", "word count", "count"], - "author": "axorax" - }, - { - "title": "Remove All Whitespace", - "description": "Removes all whitespace from a string.", - "code": [ - "function removeWhitespace(str) {", - " return str.replace(/\\s+/g, '');", - "}", - "", - "// Example usage:", - "console.log(removeWhitespace('Hello world!')); // Output: 'Helloworld!'" - ], - "tags": ["javascript", "string", "whitespace"], - "author": "axorax" - }, - { - "title": "Pad String on Both Sides", - "description": "Pads a string on both sides with a specified character until it reaches the desired length.", - "code": [ - "function padString(str, length, char = ' ') {", - " const totalPad = length - str.length;", - " const padStart = Math.floor(totalPad / 2);", - " const padEnd = totalPad - padStart;", - " return char.repeat(padStart) + str + char.repeat(padEnd);", - "}", - "", - "// Example usage:", - "console.log(padString('hello', 10, '*')); // Output: '**hello***'" - ], - "tags": ["string", "pad", "manipulation"], - "author": "axorax" - }, - { - "title": "Convert String to Snake Case", - "description": "Converts a given string into snake_case.", - "code": [ - "function toSnakeCase(str) {", - " return str.replace(/([a-z])([A-Z])/g, '$1_$2')", - " .replace(/\\s+/g, '_')", - " .toLowerCase();", - "}", - "", - "// Example usage:", - "console.log(toSnakeCase('Hello World Test')); // Output: 'hello_world_test'" - ], - "tags": ["string", "case", "snake_case"], - "author": "axorax" - }, - { - "title": "Convert String to Camel Case", - "description": "Converts a given string into camelCase.", - "code": [ - "function toCamelCase(str) {", - " return str.replace(/\\W+(.)/g, (match, chr) => chr.toUpperCase());", - "}", - "", - "// Example usage:", - "console.log(toCamelCase('hello world test')); // Output: 'helloWorldTest'" - ], - "tags": ["string", "case", "camelCase"], - "author": "aumirza" - }, - { - "title": "Convert String to Title Case", - "description": "Converts a given string into Title Case.", - "code": [ - "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'" - ], - "tags": ["string", "case", "titleCase"], - "author": "aumirza" - }, - { - "title": "Convert String to Pascal Case", - "description": "Converts a given string into Pascal Case.", - "code": [ - "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'" - ], - "tags": ["string", "case", "pascalCase"], - "author": "aumirza" - }, - { - "title": "Convert String to Param Case", - "description": "Converts a given string into param-case.", - "code": [ - "function toParamCase(str) {", - " return str.toLowerCase().replace(/\\s+/g, '-');", - "}", - "", - "// Example usage:", - "console.log(toParamCase('Hello World Test')); // Output: 'hello-world-test'" - ], - "tags": ["string", "case", "paramCase"], - "author": "aumirza" - }, - { - "title": "Remove Vowels from a String", - "description": "Removes all vowels from a given string.", - "code": [ - "function removeVowels(str) {", - " return str.replace(/[aeiouAEIOU]/g, '');", - "}", - "", - "// Example usage:", - "console.log(removeVowels('Hello World')); // Output: 'Hll Wrld'" - ], - "tags": ["string", "remove", "vowels"], - "author": "axorax" - }, - { - "title": "Mask Sensitive Information", - "description": "Masks parts of a sensitive string, like a credit card or email address.", - "code": [ - "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#############'" - ], - "tags": ["string", "mask", "sensitive"], - "author": "axorax" - }, - { - "title": "Extract Initials from Name", - "description": "Extracts and returns the initials from a full name.", - "code": [ - "function getInitials(name) {", - " return name.split(' ').map(part => part.charAt(0).toUpperCase()).join('');", - "}", - "", - "// Example usage:", - "console.log(getInitials('John Doe')); // Output: 'JD'" - ], - "tags": ["string", "initials", "name"], - "author": "axorax" - }, - { - "title": "Convert Tabs to Spaces", - "description": "Converts all tab characters in a string to spaces.", - "code": [ - "function tabsToSpaces(str, spacesPerTab = 4) {", - " return str.replace(/\\t/g, ' '.repeat(spacesPerTab));", - "}", - "", - "// Example usage:", - "console.log(tabsToSpaces('Hello\\tWorld', 2)); // Output: 'Hello World'" - ], - "tags": ["string", "tabs", "spaces"], - "author": "axorax" - }, - { - "title": "Random string", - "description": "Generates a random string of characters of a certain length", - "code": [ - "function makeid(length, characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {", - " return Array.from({ length }, () => characters.charAt(Math.floor(Math.random() * characters.length))).join('');", - "}", - "", - "console.log(makeid(5, \"1234\" /* (optional) */));" - ], - "tags": ["javascript", "function", "random"], - "author": "kruimol" - } - ] - }, - { - "categoryName": "Object Manipulation", - "snippets": [ - { - "title": "Filter Object", - "description": "Filter out entries in an object where the value is falsy, including empty strings, empty objects, null, and undefined.", - "code": [ - "export const filterObject = (object = {}) =>", - " Object.fromEntries(", - " Object.entries(object)", - " .filter(([key, value]) => value !== null && value !== undefined && value !== '' && (typeof value !== 'object' || Object.keys(value).length > 0))", - " );", - "", - "// Usage:", - "const obj1 = { a: 1, b: null, c: undefined, d: 4, e: '', f: {} };", - "console.log(filterObject(obj1)); // Output: { a: 1, d: 4 }", - "", - "const obj2 = { x: 0, y: false, z: 'Hello', w: [] };", - "console.log(filterObject(obj2)); // Output: { z: 'Hello' }", - "", - "const obj3 = { name: 'John', age: null, address: { city: 'New York' }, phone: '' };", - "console.log(filterObject(obj3)); // Output: { name: 'John', address: { city: 'New York' } }", - "", - "const obj4 = { a: 0, b: '', c: false, d: {}, e: 'Valid' };", - "console.log(filterObject(obj4)); // Output: { e: 'Valid' }" - ], - "tags": ["javascript", "object", "filter", "utility"], - "author": "realvishalrana" - }, - { - "title": "Get Nested Value", - "description": "Retrieves the value at a given path in a nested object.", - "code": [ - "const getNestedValue = (obj, path) => {", - " const keys = path.split('.');", - " return keys.reduce((currentObject, key) => {", - " return currentObject && typeof currentObject === 'object' ? currentObject[key] : undefined;", - " }, obj);", - "};", - "", - "// Usage:", - "const obj = { a: { b: { c: 42 } } };", - "console.log(getNestedValue(obj, 'a.b.c')); // Output: 42" - ], - "tags": ["javascript", "object", "nested", "utility"], - "author": "realvishalrana" - }, - { - "title": "Unique By Key", - "description": "Filters an array of objects to only include unique objects by a specified key.", - "code": [ - "const uniqueByKey = (key, arr) =>", - " arr.filter((obj, index, self) => index === self.findIndex((t) => t?.[key] === obj?.[key]));", - "", - "// Usage:", - "const arr = [", - " { id: 1, name: 'John' },", - " { id: 2, name: 'Jane' },", - " { id: 1, name: 'John' }", - "];", - "console.log(uniqueByKey('id', arr)); // Output: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]" - ], - "tags": ["javascript", "array", "unique", "utility"], - "author": "realvishalrana" - }, - { - "title": "Merge Objects Deeply", - "description": "Deeply merges two or more objects, including nested properties.", - "code": [ - "function deepMerge(...objects) {", - " return objects.reduce((acc, obj) => {", - " Object.keys(obj).forEach(key => {", - " if (typeof obj[key] === 'object' && obj[key] !== null) {", - " acc[key] = deepMerge(acc[key] || {}, obj[key]);", - " } else {", - " acc[key] = obj[key];", - " }", - " });", - " return acc;", - " }, {});", - "}", - "", - "// 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 }" - ], - "tags": ["javascript", "object", "merge", "deep"], - "author": "axorax" - }, - { - "title": "Omit Keys from Object", - "description": "Creates a new object with specific keys omitted.", - "code": [ - "function omitKeys(obj, keys) {", - " return Object.fromEntries(", - " Object.entries(obj).filter(([key]) => !keys.includes(key))", - " );", - "}", - "", - "// Usage:", - "const obj = { a: 1, b: 2, c: 3 };", - "console.log(omitKeys(obj, ['b', 'c'])); // Output: { a: 1 }" - ], - "tags": ["javascript", "object", "omit", "utility"], - "author": "axorax" - }, - { - "title": "Convert Object to Query String", - "description": "Converts an object to a query string for use in URLs.", - "code": [ - "function toQueryString(obj) {", - " return Object.entries(obj)", - " .map(([key, value]) => encodeURIComponent(key) + '=' + encodeURIComponent(value))", - " .join('&');", - "}", - "", - "// Usage:", - "const params = { search: 'test', page: 1 };", - "console.log(toQueryString(params)); // Output: 'search=test&page=1'" - ], - "tags": ["javascript", "object", "query string", "url"], - "author": "axorax" - }, - { - "title": "Flatten Nested Object", - "description": "Flattens a nested object into a single-level object with dot notation for keys.", - "code": [ - "function flattenObject(obj, prefix = '') {", - " return Object.keys(obj).reduce((acc, key) => {", - " const fullPath = prefix ? `${prefix}.${key}` : key;", - " if (typeof obj[key] === 'object' && obj[key] !== null) {", - " Object.assign(acc, flattenObject(obj[key], fullPath));", - " } else {", - " acc[fullPath] = obj[key];", - " }", - " return acc;", - " }, {});", - "}", - "", - "// 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 }" - ], - "tags": ["javascript", "object", "flatten", "utility"], - "author": "axorax" - }, - { - "title": "Pick Keys from Object", - "description": "Creates a new object with only the specified keys.", - "code": [ - "function pickKeys(obj, keys) {", - " return Object.fromEntries(", - " Object.entries(obj).filter(([key]) => keys.includes(key))", - " );", - "}", - "", - "// Usage:", - "const obj = { a: 1, b: 2, c: 3 };", - "console.log(pickKeys(obj, ['a', 'c'])); // Output: { a: 1, c: 3 }" - ], - "tags": ["javascript", "object", "pick", "utility"], - "author": "axorax" - }, - { - "title": "Check if Object is Empty", - "description": "Checks whether an object has no own enumerable properties.", - "code": [ - "function isEmptyObject(obj) {", - " return Object.keys(obj).length === 0;", - "}", - "", - "// Usage:", - "console.log(isEmptyObject({})); // Output: true", - "console.log(isEmptyObject({ a: 1 })); // Output: false" - ], - "tags": ["javascript", "object", "check", "empty"], - "author": "axorax" - }, - { - "title": "Invert Object Keys and Values", - "description": "Creates a new object by swapping keys and values of the given object.", - "code": [ - "function invertObject(obj) {", - " return Object.fromEntries(", - " Object.entries(obj).map(([key, value]) => [value, key])", - " );", - "}", - "", - "// Usage:", - "const obj = { a: 1, b: 2, c: 3 };", - "console.log(invertObject(obj)); // Output: { '1': 'a', '2': 'b', '3': 'c' }" - ], - "tags": ["javascript", "object", "invert", "utility"], - "author": "axorax" - }, - { - "title": "Clone Object Shallowly", - "description": "Creates a shallow copy of an object.", - "code": [ - "function shallowClone(obj) {", - " return { ...obj };", - "}", - "", - "// Usage:", - "const obj = { a: 1, b: 2 };", - "const clone = shallowClone(obj);", - "console.log(clone); // Output: { a: 1, b: 2 }" - ], - "tags": ["javascript", "object", "clone", "shallow"], - "author": "axorax" - }, - { - "title": "Count Properties in Object", - "description": "Counts the number of own properties in an object.", - "code": [ - "function countProperties(obj) {", - " return Object.keys(obj).length;", - "}", - "", - "// Usage:", - "const obj = { a: 1, b: 2, c: 3 };", - "console.log(countProperties(obj)); // Output: 3" - ], - "tags": ["javascript", "object", "count", "properties"], - "author": "axorax" - }, - { - "title": "Compare Two Objects Shallowly", - "description": "Compares two objects shallowly and returns whether they are equal.", - "code": [ - "function shallowEqual(obj1, obj2) {", - " const keys1 = Object.keys(obj1);", - " const keys2 = Object.keys(obj2);", - " if (keys1.length !== keys2.length) return false;", - " return keys1.every(key => obj1[key] === obj2[key]);", - "}", - "", - "// Usage:", - "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" - ], - "tags": ["javascript", "object", "compare", "shallow"], - "author": "axorax" - }, - { - "title": "Freeze Object", - "description": "Freezes an object to make it immutable.", - "code": [ - "function freezeObject(obj) {", - " return Object.freeze(obj);", - "}", - "", - "// Usage:", - "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" - ], - "tags": ["javascript", "object", "freeze", "immutable"], - "author": "axorax" - } - ] - }, - { - "categoryName": "Date and Time", - "snippets": [ - { - "title": "Format Date", - "description": "Formats a date in 'YYYY-MM-DD' format.", - "code": [ - "const formatDate = (date) => date.toISOString().split('T')[0];", - "", - "// Usage:", - "console.log(formatDate(new Date())); // Output: '2024-12-10'" - ], - "tags": ["javascript", "date", "format", "utility"], - "author": "dostonnabotov" - }, - { - "title": "Get Time Difference", - "description": "Calculates the time difference in days between two dates.", - "code": [ - "const getTimeDifference = (date1, date2) => {", - " const diff = Math.abs(date2 - date1);", - " return Math.ceil(diff / (1000 * 60 * 60 * 24));", - "};", - "", - "// Usage:", - "const date1 = new Date('2024-01-01');", - "const date2 = new Date('2024-12-31');", - "console.log(getTimeDifference(date1, date2)); // Output: 365" - ], - "tags": ["javascript", "date", "time-difference", "utility"], - "author": "dostonnabotov" - }, - { - "title": "Relative Time Formatter", - "description": "Displays how long ago a date occurred or how far in the future a date is.", - "code": [ - "const getRelativeTime = (date) => {", - " const now = Date.now();", - " const diff = date.getTime() - now;", - " const seconds = Math.abs(Math.floor(diff / 1000));", - " const minutes = Math.abs(Math.floor(seconds / 60));", - " const hours = Math.abs(Math.floor(minutes / 60));", - " const days = Math.abs(Math.floor(hours / 24));", - " const years = Math.abs(Math.floor(days / 365));", - "", - " if (Math.abs(diff) < 1000) return 'just now';", - "", - " const isFuture = diff > 0;", - "", - " if (years > 0) return `${isFuture ? 'in ' : ''}${years} ${years === 1 ? 'year' : 'years'}${isFuture ? '' : ' ago'}`;", - " if (days > 0) return `${isFuture ? 'in ' : ''}${days} ${days === 1 ? 'day' : 'days'}${isFuture ? '' : ' ago'}`;", - " if (hours > 0) return `${isFuture ? 'in ' : ''}${hours} ${hours === 1 ? 'hour' : 'hours'}${isFuture ? '' : ' ago'}`;", - " if (minutes > 0) return `${isFuture ? 'in ' : ''}${minutes} ${minutes === 1 ? 'minute' : 'minutes'}${isFuture ? '' : ' ago'}`;", - "", - " return `${isFuture ? 'in ' : ''}${seconds} ${seconds === 1 ? 'second' : 'seconds'}${isFuture ? '' : ' ago'}`;", - "}", - "", - "// 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" - ], - "tags": [ - "javascript", - "date", - "time", - "relative", - "future", - "past", - "utility" - ], - "author": "Yugveer06" - }, - { - "title": "Get Current Timestamp", - "description": "Retrieves the current timestamp in milliseconds since January 1, 1970.", - "code": [ - "const getCurrentTimestamp = () => Date.now();", - "", - "// Usage:", - "console.log(getCurrentTimestamp()); // Output: 1691825935839 (example)" - ], - "tags": ["javascript", "date", "timestamp", "utility"], - "author": "axorax" - }, - { - "title": "Check Leap Year", - "description": "Determines if a given year is a leap year.", - "code": [ - "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" - ], - "tags": ["javascript", "date", "leap-year", "utility"], - "author": "axorax" - }, - { - "title": "Add Days to a Date", - "description": "Adds a specified number of days to a given date.", - "code": [ - "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" - ], - "tags": ["javascript", "date", "add-days", "utility"], - "author": "axorax" - }, - { - "title": "Start of the Day", - "description": "Returns the start of the day (midnight) for a given date.", - "code": [ - "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" - ], - "tags": ["javascript", "date", "start-of-day", "utility"], - "author": "axorax" - }, - { - "title": "Get Days in Month", - "description": "Calculates the number of days in a specific month of a given year.", - "code": [ - "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" - ], - "tags": ["javascript", "date", "days-in-month", "utility"], - "author": "axorax" - }, - { - "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.", - "code": [ - "const getDayOfYear = (date) => {", - " const startOfYear = new Date(date.getFullYear(), 0, 0);", - " const diff = date - startOfYear + (startOfYear.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000;", - " return Math.floor(diff / (1000 * 60 * 60 * 24));", - "};", - "", - "// Usage:", - "const today = new Date('2024-12-31');", - "console.log(getDayOfYear(today)); // Output: 366 (in a leap year)" - ], - "tags": ["javascript", "date", "day-of-year", "utility"], - "author": "axorax" - } - ] - }, - { - "categoryName": "Function Utilities", - "snippets": [ - { - "title": "Repeat Function Invocation", - "description": "Invokes a function a specified number of times.", - "code": [ - "const times = (func, n) => {", - " Array.from(Array(n)).forEach(() => {", - " func();", - " });", - "};", - "", - "// Usage:", - "const randomFunction = () => console.log('Function called!');", - "times(randomFunction, 3); // Logs 'Function called!' three times" - ], - "tags": ["javascript", "function", "repeat", "utility"], - "author": "dostonnabotov" - }, - { - "title": "Debounce Function", - "description": "Delays a function execution until after a specified time.", - "code": [ - "const debounce = (func, delay) => {", - " let timeout;", - "", - " return (...args) => {", - " clearTimeout(timeout);", - " timeout = setTimeout(() => func(...args), delay);", - " };", - "};", - "", - "// Usage:", - "window.addEventListener('resize', debounce(() => console.log('Resized!'), 500));" - ], - "tags": ["javascript", "utility", "debounce", "performance"], - "author": "dostonnabotov" - }, - { - "title": "Throttle Function", - "description": "Limits a function execution to once every specified time interval.", - "code": [ - "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));" - ], - "tags": ["javascript", "utility", "throttle", "performance"], - "author": "dostonnabotov" - }, - { - "title": "Get Contrast Color", - "description": "Returns either black or white text color based on the brightness of the provided hex color.", - "code": [ - "const getContrastColor = (hexColor) => {", - " // Expand short hex color to full format", - " if (hexColor.length === 4) {", - " hexColor = `#${hexColor[1]}${hexColor[1]}${hexColor[2]}${hexColor[2]}${hexColor[3]}${hexColor[3]}`;", - " }", - " const r = parseInt(hexColor.slice(1, 3), 16);", - " const g = parseInt(hexColor.slice(3, 5), 16);", - " const b = parseInt(hexColor.slice(5, 7), 16);", - " const brightness = (r * 299 + g * 587 + b * 114) / 1000;", - " return brightness >= 128 ? \"#000000\" : \"#FFFFFF\";", - "};", - "", - "// 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)" - ], - "tags": [ - "javascript", - "color", - "hex", - "contrast", - "brightness", - "utility" - ], - "author": "yaya12085" - }, - { - "title": "Sleep Function", - "description": "Waits for a specified amount of milliseconds before resolving.", - "code": [ - "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();" - ], - "tags": ["javascript", "sleep", "delay", "utility", "promises"], - "author": "0xHouss" - }, - { - "title": "Memoize Function", - "description": "Caches the result of a function based on its arguments to improve performance.", - "code": [ - "const memoize = (func) => {", - " const cache = new Map();", - " return (...args) => {", - " const key = JSON.stringify(args);", - " if (cache.has(key)) {", - " return cache.get(key);", - " }", - " const result = func(...args);", - " cache.set(key, result);", - " return result;", - " };", - "};", - "", - "// 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)" - ], - "tags": ["javascript", "memoization", "optimization", "utility"], - "author": "axorax" - }, - { - "title": "Once Function", - "description": "Ensures a function is only called once.", - "code": [ - "const once = (func) => {", - " let called = false;", - " return (...args) => {", - " if (!called) {", - " called = true;", - " return func(...args);", - " }", - " };", - "};", - "", - "// Usage:", - "const initialize = once(() => console.log('Initialized!'));", - "initialize(); // Output: Initialized!", - "initialize(); // No output" - ], - "tags": ["javascript", "function", "once", "utility"], - "author": "axorax" - }, - { - "title": "Curry Function", - "description": "Transforms a function into its curried form.", - "code": [ - "const curry = (func) => {", - " const curried = (...args) => {", - " if (args.length >= func.length) {", - " return func(...args);", - " }", - " return (...nextArgs) => curried(...args, ...nextArgs);", - " };", - " return curried;", - "};", - "", - "// 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" - ], - "tags": ["javascript", "curry", "function", "utility"], - "author": "axorax" - }, - { - "title": "Compose Functions", - "description": "Composes multiple functions into a single function, where the output of one function becomes the input of the next.", - "code": [ - "const compose = (...funcs) => (initialValue) => {", - " return funcs.reduce((acc, func) => func(acc), initialValue);", - "};", - "", - "// Usage:", - "const add2 = (x) => x + 2;", - "const multiply3 = (x) => x * 3;", - "const composed = compose(multiply3, add2);", - "console.log(composed(5)); // Output: 21 ((5 + 2) * 3)" - ], - "tags": ["javascript", "function", "compose", "utility"], - "author": "axorax" - }, - { - "title": "Rate Limit Function", - "description": "Limits how often a function can be executed within a given time window.", - "code": [ - "const rateLimit = (func, limit, timeWindow) => {", - " let queue = [];", - " setInterval(() => {", - " if (queue.length) {", - " const next = queue.shift();", - " func(...next.args);", - " }", - " }, timeWindow);", - " return (...args) => {", - " if (queue.length < limit) {", - " queue.push({ args });", - " }", - " };", - "};", - "", - "// Usage:", - "const fetchData = () => console.log('Fetching data...');", - "const rateLimitedFetch = rateLimit(fetchData, 2, 1000);", - "setInterval(() => rateLimitedFetch(), 200); // Only calls fetchData twice every second" - ], - "tags": ["javascript", "function", "rate-limiting", "utility"], - "author": "axorax" - } - ] - }, - { - "categoryName": "DOM Manipulation", - "snippets": [ - { - "title": "Toggle Class", - "description": "Toggles a class on an element.", - "code": [ - "const toggleClass = (element, className) => {", - " element.classList.toggle(className);", - "};", - "", - "// Usage:", - "const element = document.querySelector('.my-element');", - "toggleClass(element, 'active');" - ], - "tags": ["javascript", "dom", "class", "utility"], - "author": "dostonnabotov" - }, - { - "title": "Smooth Scroll to Element", - "description": "Scrolls smoothly to a specified element.", - "code": [ - "const smoothScroll = (element) => {", - " element.scrollIntoView({ behavior: 'smooth' });", - "};", - "", - "// Usage:", - "const target = document.querySelector('#target');", - "smoothScroll(target);" - ], - "tags": ["javascript", "dom", "scroll", "ui"], - "author": "dostonnabotov" - }, - { - "title": "Get Element Position", - "description": "Gets the position of an element relative to the viewport.", - "code": [ - "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 }" - ], - "tags": ["javascript", "dom", "position", "utility"], - "author": "axorax" - }, - { - "title": "Change Element Style", - "description": "Changes the inline style of an element.", - "code": [ - "const changeElementStyle = (element, styleObj) => {", - " Object.entries(styleObj).forEach(([property, value]) => {", - " element.style[property] = value;", - " });", - "};", - "", - "// Usage:", - "const element = document.querySelector('.my-element');", - "changeElementStyle(element, { color: 'red', backgroundColor: 'yellow' });" - ], - "tags": ["javascript", "dom", "style", "utility"], - "author": "axorax" - }, - { - "title": "Remove Element", - "description": "Removes a specified element from the DOM.", - "code": [ - "const removeElement = (element) => {", - " if (element && element.parentNode) {", - " element.parentNode.removeChild(element);", - " }", - "};", - "", - "// Usage:", - "const element = document.querySelector('.my-element');", - "removeElement(element);" - ], - "tags": ["javascript", "dom", "remove", "utility"], - "author": "axorax" - } - ] - }, - { - "categoryName": "Local Storage", - "snippets": [ - { - "title": "Add Item to localStorage", - "description": "Stores a value in localStorage under the given key.", - "code": [ - "const addToLocalStorage = (key, value) => {", - " localStorage.setItem(key, JSON.stringify(value));", - "};", - "", - "// Usage:", - "addToLocalStorage('user', { name: 'John', age: 30 });" - ], - "tags": ["javascript", "localStorage", "storage", "utility"], - "author": "dostonnabotov" - }, - { - "title": "Retrieve Item from localStorage", - "description": "Retrieves a value from localStorage by key and parses it.", - "code": [ - "const getFromLocalStorage = (key) => {", - " const item = localStorage.getItem(key);", - " return item ? JSON.parse(item) : null;", - "};", - "", - "// Usage:", - "const user = getFromLocalStorage('user');", - "console.log(user); // Output: { name: 'John', age: 30 }" - ], - "tags": ["javascript", "localStorage", "storage", "utility"], - "author": "dostonnabotov" - }, - { - "title": "Clear All localStorage", - "description": "Clears all data from localStorage.", - "code": [ - "const clearLocalStorage = () => {", - " localStorage.clear();", - "};", - "", - "// Usage:", - "clearLocalStorage(); // Removes all items from localStorage" - ], - "tags": ["javascript", "localStorage", "storage", "utility"], - "author": "dostonnabotov" - }, - { - "title": "Check if Item Exists in localStorage", - "description": "Checks if a specific item exists in localStorage.", - "code": [ - "const isItemInLocalStorage = (key) => {", - " return localStorage.getItem(key) !== null;", - "};", - "", - "// Usage:", - "console.log(isItemInLocalStorage('user')); // Output: true or false" - ], - "tags": ["javascript", "localStorage", "storage", "utility"], - "author": "axorax" - } - ] - }, - { - "categoryName": "Number Formatting", - "snippets": [ - { - "title": "Number Formatter", - "description": "Formats a number with suffixes (K, M, B, etc.).", - "code": [ - "const nFormatter = (num) => {", - " if (!num) return;", - " num = parseFloat(num.toString().replace(/[^0-9.]/g, ''));", - " const suffixes = ['', 'K', 'M', 'B', 'T', 'P', 'E'];", - " let index = 0;", - " while (num >= 1000 && index < suffixes.length - 1) {", - " num /= 1000;", - " index++;", - " }", - " return num.toFixed(2).replace(/\\.0+$|(\\.[0-9]*[1-9])0+$/, '$1') + suffixes[index];", - "};", - "", - "// Usage:", - "console.log(nFormatter(1234567)); // Output: '1.23M'" - ], - "tags": ["javascript", "number", "format", "utility"], - "author": "realvishalrana" - }, - { - "title": "Format Number with Commas", - "description": "Formats a number with commas for better readability (e.g., 1000 -> 1,000).", - "code": [ - "const formatNumberWithCommas = (num) => {", - " return num.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');", - "};", - "", - "// Usage:", - "console.log(formatNumberWithCommas(1000)); // Output: '1,000'", - "console.log(formatNumberWithCommas(1234567)); // Output: '1,234,567'", - "console.log(formatNumberWithCommas(987654321)); // Output: '987,654,321'" - ], - "tags": ["javascript", "number", "format", "utility"], - "author": "axorax" - }, - { - "title": "Convert Number to Currency", - "description": "Converts a number to a currency format with a specific locale.", - "code": [ - "const convertToCurrency = (num, locale = 'en-US', currency = 'USD') => {", - " return new Intl.NumberFormat(locale, {", - " style: 'currency',", - " currency: currency", - " }).format(num);", - "};", - "", - "// Usage:", - "console.log(convertToCurrency(1234567.89)); // Output: '$1,234,567.89'", - "console.log(convertToCurrency(987654.32, 'de-DE', 'EUR')); // Output: '987.654,32 €'" - ], - "tags": ["javascript", "number", "currency", "utility"], - "author": "axorax" - }, - { - "title": "Convert Number to Roman Numerals", - "description": "Converts a number to Roman numeral representation.", - "code": [ - "const numberToRoman = (num) => {", - " const romanNumerals = {", - " 1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L',", - " 90: 'XC', 100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M'", - " };", - " let result = '';", - " Object.keys(romanNumerals).reverse().forEach(value => {", - " while (num >= value) {", - " result += romanNumerals[value];", - " num -= value;", - " }", - " });", - " return result;", - "};", - "", - "// Usage:", - "console.log(numberToRoman(1994)); // Output: 'MCMXCIV'", - "console.log(numberToRoman(58)); // Output: 'LVIII'" - ], - "tags": ["javascript", "number", "roman", "utility"], - "author": "axorax" - }, - { - "title": "Number to Words Converter", - "description": "Converts a number to its word representation in English.", - "code": [ - "const numberToWords = (num) => {", - " const below20 = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'];", - " const tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];", - " const above1000 = ['Hundred', 'Thousand', 'Million', 'Billion'];", - " if (num < 20) return below20[num];", - " let words = '';", - " for (let i = 0; num > 0; i++) {", - " if (i > 0 && num % 1000 !== 0) words = above1000[i] + ' ' + words;", - " if (num % 100 >= 20) {", - " words = tens[Math.floor(num / 10)] + ' ' + words;", - " num %= 10;", - " }", - " if (num < 20) words = below20[num] + ' ' + words;", - " num = Math.floor(num / 100);", - " }", - " return words.trim();", - "};", - "", - "// Usage:", - "console.log(numberToWords(123)); // Output: 'One Hundred Twenty Three'", - "console.log(numberToWords(2045)); // Output: 'Two Thousand Forty Five'" - ], - "tags": ["javascript", "number", "words", "utility"], - "author": "axorax" - }, - { - "title": "Convert to Scientific Notation", - "description": "Converts a number to scientific notation.", - "code": [ - "const toScientificNotation = (num) => {", - " if (isNaN(num)) {", - " throw new Error('Input must be a number');", - " }", - " if (num === 0) {", - " return '0e+0';", - " }", - " const exponent = Math.floor(Math.log10(Math.abs(num)));", - " const mantissa = num / Math.pow(10, exponent);", - " return `${mantissa.toFixed(2)}e${exponent >= 0 ? '+' : ''}${exponent}`;", - "};", - "", - "// 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'" - ], - "tags": ["javascript", "number", "scientific", "utility"], - "author": "axorax" - } - ] - }, { - "categoryName": "Regular expression", - "snippets": [ - { - "title": "Regex Match Utility Function", - "description": "Enhanced regular expression matching utility.", - "code": [ - "/**", - "* @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,", - " };", - " });", - "}" - ], - "tags": ["javascript","regex"], - "author": "aumirza" - } - ] - } -] + "categoryName": "Array Manipulation", + "snippets": [ + { + "title": "Flatten Array", + "description": "Flattens a multi-dimensional array.", + "author": "dostonnabotov", + "tags": [ + "javascript", + "array", + "flatten", + "utility" + ], + "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": "Remove Duplicates", + "description": "Removes duplicate values from an array.", + "author": "dostonnabotov", + "tags": [ + "javascript", + "array", + "deduplicate", + "utility" + ], + "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" + }, + { + "title": "Shuffle Array", + "description": "Shuffles an Array.", + "author": "loxt-nixo", + "tags": [ + "javascript", + "array", + "shuffle", + "utility" + ], + "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" + }, + { + "title": "Zip Arrays", + "description": "Combines two arrays by pairing corresponding elements from each array.", + "author": "Swaraj-Singh-30", + "tags": [ + "javascript", + "array", + "utility", + "map" + ], + "code": "const zip = (arr1, arr2) => arr1.map((value, index) => [value, arr2[index]]);\n\n// Usage:\nconst arr1 = ['a', 'b', 'c'];\nconst arr2 = [1, 2, 3];\nconsole.log(zip(arr1, arr2)); // Output: [['a', 1], ['b', 2], ['c', 3]]\n" + } + ] + }, + { + "categoryName": "Basics", + "snippets": [ + { + "title": "Hello, World!", + "description": "Prints Hello, World! to the terminal.", + "author": "James-Beans", + "tags": [ + "javascript", + "printing", + "hello-world", + "utility" + ], + "code": "console.log(\"Hello, World!\"); // Prints Hello, World! to the console\n" + } + ] + }, + { + "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" + ], + "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" + ], + "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" + }, + { + "title": "Format Date", + "description": "Formats a date in 'YYYY-MM-DD' format.", + "author": "dostonnabotov", + "tags": [ + "javascript", + "date", + "format", + "utility" + ], + "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" + ], + "code": "const getCurrentTimestamp = () => Date.now();\n\n// Usage:\nconsole.log(getCurrentTimestamp()); // Output: 1691825935839 (example)\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" + ], + "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" + }, + { + "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" + ], + "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" + }, + { + "title": "Get Time Difference", + "description": "Calculates the time difference in days between two dates.", + "author": "dostonnabotov", + "tags": [ + "javascript", + "date", + "time-difference", + "utility" + ], + "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" + }, + { + "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" + ], + "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" + }, + { + "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" + ], + "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" + } + ] + }, + { + "categoryName": "Dom Manipulation", + "snippets": [ + { + "title": "Change Element Style", + "description": "Changes the inline style of an element.", + "author": "axorax", + "tags": [ + "javascript", + "dom", + "style", + "utility" + ], + "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" + ], + "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" + ], + "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" + ], + "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" + ], + "code": "const toggleClass = (element, className) => {\n element.classList.toggle(className);\n};\n\n// Usage:\nconst element = document.querySelector('.my-element');\ntoggleClass(element, 'active');\n" + } + ] + }, + { + "categoryName": "Function Utilities", + "snippets": [ + { + "title": "Compose Functions", + "description": "Composes multiple functions into a single function, where the output of one function becomes the input of the next.", + "author": "axorax", + "tags": [ + "javascript", + "function", + "compose", + "utility" + ], + "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" + }, + { + "title": "Curry Function", + "description": "Transforms a function into its curried form.", + "author": "axorax", + "tags": [ + "javascript", + "curry", + "function", + "utility" + ], + "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" + }, + { + "title": "Debounce Function", + "description": "Delays a function execution until after a specified time.", + "author": "dostonnabotov", + "tags": [ + "javascript", + "utility", + "debounce", + "performance" + ], + "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" + }, + { + "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" + ], + "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" + }, + { + "title": "Memoize Function", + "description": "Caches the result of a function based on its arguments to improve performance.", + "author": "axorax", + "tags": [ + "javascript", + "memoization", + "optimization", + "utility" + ], + "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" + }, + { + "title": "Once Function", + "description": "Ensures a function is only called once.", + "author": "axorax", + "tags": [ + "javascript", + "function", + "once", + "utility" + ], + "code": "const once = (func) => {\n let called = false;\n return (...args) => {\n if (!called) {\n called = true;\n return func(...args);\n }\n };\n};\n\n// Usage:\nconst initialize = once(() => console.log('Initialized!'));\ninitialize(); // Output: Initialized!\ninitialize(); // No output\n" + }, + { + "title": "Rate Limit Function", + "description": "Limits how often a function can be executed within a given time window.", + "author": "axorax", + "tags": [ + "javascript", + "function", + "rate-limiting", + "utility" + ], + "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" + }, + { + "title": "Repeat Function Invocation", + "description": "Invokes a function a specified number of times.", + "author": "dostonnabotov", + "tags": [ + "javascript", + "function", + "repeat", + "utility" + ], + "code": "const times = (func, n) => {\n Array.from(Array(n)).forEach(() => {\n func();\n });\n};\n\n// Usage:\nconst randomFunction = () => console.log('Function called!');\ntimes(randomFunction, 3); // Logs 'Function called!' three times\n" + }, + { + "title": "Sleep Function", + "description": "Waits for a specified amount of milliseconds before resolving.", + "author": "0xHouss", + "tags": [ + "javascript", + "sleep", + "delay", + "utility", + "promises" + ], + "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" + ], + "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" + } + ] + }, + { + "categoryName": "Local Storage", + "snippets": [ + { + "title": "Add Item to localStorage", + "description": "Stores a value in localStorage under the given key.", + "author": "dostonnabotov", + "tags": [ + "javascript", + "localStorage", + "storage", + "utility" + ], + "code": "const addToLocalStorage = (key, value) => {\n localStorage.setItem(key, JSON.stringify(value));\n};\n\n// Usage:\naddToLocalStorage('user', { name: 'John', age: 30 });\n" + }, + { + "title": "Check if Item Exists in localStorage", + "description": "Checks if a specific item exists in localStorage.", + "author": "axorax", + "tags": [ + "javascript", + "localStorage", + "storage", + "utility" + ], + "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" + ], + "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" + ], + "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" + } + ] + }, + { + "categoryName": "Number Formatting", + "snippets": [ + { + "title": "Convert Number to Currency", + "description": "Converts a number to a currency format with a specific locale.", + "author": "axorax", + "tags": [ + "javascript", + "number", + "currency", + "utility" + ], + "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" + }, + { + "title": "Convert Number to Roman Numerals", + "description": "Converts a number to Roman numeral representation.", + "author": "axorax", + "tags": [ + "javascript", + "number", + "roman", + "utility" + ], + "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" + }, + { + "title": "Convert to Scientific Notation", + "description": "Converts a number to scientific notation.", + "author": "axorax", + "tags": [ + "javascript", + "number", + "scientific", + "utility" + ], + "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" + }, + { + "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" + ], + "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" + }, + { + "title": "Number Formatter", + "description": "Formats a number with suffixes (K, M, B, etc.).", + "author": "realvishalrana", + "tags": [ + "javascript", + "number", + "format", + "utility" + ], + "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" + }, + { + "title": "Number to Words Converter", + "description": "Converts a number to its word representation in English.", + "author": "axorax", + "tags": [ + "javascript", + "number", + "words", + "utility" + ], + "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" + } + ] + }, + { + "categoryName": "Object Manipulation", + "snippets": [ + { + "title": "Check if Object is Empty", + "description": "Checks whether an object has no own enumerable properties.", + "author": "axorax", + "tags": [ + "javascript", + "object", + "check", + "empty" + ], + "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" + ], + "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" + }, + { + "title": "Compare Two Objects Shallowly", + "description": "Compares two objects shallowly and returns whether they are equal.", + "author": "axorax", + "tags": [ + "javascript", + "object", + "compare", + "shallow" + ], + "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" + }, + { + "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" + ], + "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" + }, + { + "title": "Count Properties in Object", + "description": "Counts the number of own properties in an object.", + "author": "axorax", + "tags": [ + "javascript", + "object", + "count", + "properties" + ], + "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" + }, + { + "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" + ], + "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" + }, + { + "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" + ], + "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" + }, + { + "title": "Freeze Object", + "description": "Freezes an object to make it immutable.", + "author": "axorax", + "tags": [ + "javascript", + "object", + "freeze", + "immutable" + ], + "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" + }, + { + "title": "Get Nested Value", + "description": "Retrieves the value at a given path in a nested object.", + "author": "realvishalrana", + "tags": [ + "javascript", + "object", + "nested", + "utility" + ], + "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" + }, + { + "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" + ], + "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" + }, + { + "title": "Merge Objects Deeply", + "description": "Deeply merges two or more objects, including nested properties.", + "author": "axorax", + "tags": [ + "javascript", + "object", + "merge", + "deep" + ], + "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" + }, + { + "title": "Omit Keys from Object", + "description": "Creates a new object with specific keys omitted.", + "author": "axorax", + "tags": [ + "javascript", + "object", + "omit", + "utility" + ], + "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" + }, + { + "title": "Pick Keys from Object", + "description": "Creates a new object with only the specified keys.", + "author": "axorax", + "tags": [ + "javascript", + "object", + "pick", + "utility" + ], + "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" + }, + { + "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" + ], + "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" + ], + "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" + } + ] + }, + { + "categoryName": "String Manipulation", + "snippets": [ + { + "title": "Capitalize String", + "description": "Capitalizes the first letter of a string.", + "author": "dostonnabotov", + "tags": [ + "javascript", + "string", + "capitalize", + "utility" + ], + "code": "const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);\n\n// Usage:\nconsole.log(capitalize('hello')); // Output: '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" + ], + "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" + }, + { + "title": "Convert String to Camel Case", + "description": "Converts a given string into camelCase.", + "author": "aumirza", + "tags": [ + "string", + "case", + "camelCase" + ], + "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" + }, + { + "title": "Convert String to Param Case", + "description": "Converts a given string into param-case.", + "author": "aumirza", + "tags": [ + "string", + "case", + "paramCase" + ], + "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" + }, + { + "title": "Convert String to Pascal Case", + "description": "Converts a given string into Pascal Case.", + "author": "aumirza", + "tags": [ + "string", + "case", + "pascalCase" + ], + "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" + }, + { + "title": "Convert String to Snake Case", + "description": "Converts a given string into snake_case.", + "author": "axorax", + "tags": [ + "string", + "case", + "snake_case" + ], + "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" + }, + { + "title": "Convert String to Title Case", + "description": "Converts a given string into Title Case.", + "author": "aumirza", + "tags": [ + "string", + "case", + "titleCase" + ], + "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" + }, + { + "title": "Convert Tabs to Spaces", + "description": "Converts all tab characters in a string to spaces.", + "author": "axorax", + "tags": [ + "string", + "tabs", + "spaces" + ], + "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" + }, + { + "title": "Count Words in a String", + "description": "Counts the number of words in a string.", + "author": "axorax", + "tags": [ + "javascript", + "string", + "manipulation", + "word count", + "count" + ], + "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" + }, + { + "title": "Data with Prefix", + "description": "Adds a prefix and postfix to data, with a fallback value.", + "author": "realvishalrana", + "tags": [ + "javascript", + "data", + "utility" + ], + "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" + }, + { + "title": "Extract Initials from Name", + "description": "Extracts and returns the initials from a full name.", + "author": "axorax", + "tags": [ + "string", + "initials", + "name" + ], + "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" + }, + { + "title": "Mask Sensitive Information", + "description": "Masks parts of a sensitive string, like a credit card or email address.", + "author": "axorax", + "tags": [ + "string", + "mask", + "sensitive" + ], + "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" + }, + { + "title": "Pad String on Both Sides", + "description": "Pads a string on both sides with a specified character until it reaches the desired length.", + "author": "axorax", + "tags": [ + "string", + "pad", + "manipulation" + ], + "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" + }, + { + "title": "Random string", + "description": "Generates a random string of characters of a certain length", + "author": "kruimol", + "tags": [ + "javascript", + "function", + "random" + ], + "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" + }, + { + "title": "Remove All Whitespace", + "description": "Removes all whitespace from a string.", + "author": "axorax", + "tags": [ + "javascript", + "string", + "whitespace" + ], + "code": "function removeWhitespace(str) {\n return str.replace(/\\s+/g, '');\n}\n\n// Example usage:\nconsole.log(removeWhitespace('Hello world!')); // Output: 'Helloworld!'\n" + }, + { + "title": "Remove Vowels from a String", + "description": "Removes all vowels from a given string.", + "author": "axorax", + "tags": [ + "string", + "remove", + "vowels" + ], + "code": "function removeVowels(str) {\n return str.replace(/[aeiouAEIOU]/g, '');\n}\n\n// Example usage:\nconsole.log(removeVowels('Hello World')); // Output: 'Hll Wrld'\n" + }, + { + "title": "Reverse String", + "description": "Reverses the characters in a string.", + "author": "dostonnabotov", + "tags": [ + "javascript", + "string", + "reverse", + "utility" + ], + "code": "const reverseString = (str) => str.split('').reverse().join('');\n\n// Usage:\nconsole.log(reverseString('hello')); // Output: 'olleh'\n" + }, + { + "title": "Slugify String", + "description": "Converts a string into a URL-friendly slug format.", + "author": "dostonnabotov", + "tags": [ + "javascript", + "string", + "slug", + "utility" + ], + "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" + }, + { + "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" + ], + "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" + } + ] + } +] \ No newline at end of file diff --git a/public/data/python.json b/public/data/python.json index 7b2d32c4..b8a46b3f 100644 --- a/public/data/python.json +++ b/public/data/python.json @@ -1,1188 +1,850 @@ [ - { - "categoryName": "Basics", - "snippets": [ - { - "title": "Hello, World!", - "description": "Prints Hello, World! to the terminal.", - "code": [ - "print(\"Hello, World!\") # Prints Hello, World! to the terminal." - ], - "tags": ["python", "printing", "hello-world", "utility"], - "author": "James-Beans" - } - ] - }, - { - "categoryName": "String Manipulation", - "snippets": [ - { - "title": "Reverse String", - "description": "Reverses the characters in a string.", - "code": [ - "def reverse_string(s):", - " return s[::-1]", - "", - "# Usage:", - "print(reverse_string('hello')) # Output: 'olleh'" - ], - "tags": ["python", "string", "reverse", "utility"], - "author": "dostonnabotov" - }, - { - "title": "Check Palindrome", - "description": "Checks if a string is a palindrome.", - "code": [ - "def is_palindrome(s):", - " s = s.lower().replace(' ', '')", - " return s == s[::-1]", - "", - "# Usage:", - "print(is_palindrome('A man a plan a canal Panama')) # Output: True" - ], - "tags": ["python", "string", "palindrome", "utility"], - "author": "dostonnabotov" - }, - { - "title": "Count Vowels", - "description": "Counts the number of vowels in a string.", - "code": [ - "def count_vowels(s):", - " vowels = 'aeiou'", - " return len([char for char in s.lower() if char in vowels])", - "", - "# Usage:", - "print(count_vowels('hello')) # Output: 2" - ], - "tags": ["python", "string", "vowels", "count", "utility"], - "author": "SteliosGee" - }, - { - "title": "Check Anagram", - "description": "Checks if two strings are anagrams of each other.", - "code": [ - "def is_anagram(s1, s2):", - " return sorted(s1) == sorted(s2)", - "", - "# Usage:", - "print(is_anagram('listen', 'silent')) # Output: True" - ], - "tags": ["python", "string", "anagram", "check", "utility"], - "author": "SteliosGee" - }, - { - "title": "Remove Punctuation", - "description": "Removes punctuation from a string.", - "code": [ - "import string", - "", - "def remove_punctuation(s):", - " return s.translate(str.maketrans('', '', string.punctuation))", - "", - "# Usage:", - "print(remove_punctuation('Hello, World!')) # Output: 'Hello World'" - ], - "tags": ["python", "string", "punctuation", "remove", "utility"], - "author": "SteliosGee" - }, - { - "title": "Capitalize Words", - "description": "Capitalizes the first letter of each word in a string.", - "code": [ - "def capitalize_words(s):", - " return ' '.join(word.capitalize() for word in s.split())", - "", - "# Usage:", - "print(capitalize_words('hello world')) # Output: 'Hello World'" - ], - "tags": ["python", "string", "capitalize", "utility"], - "author": "axorax" - }, - { - "title": "Find Longest Word", - "description": "Finds the longest word in a string.", - "code": [ - "def find_longest_word(s):", - " words = s.split()", - " return max(words, key=len) if words else ''", - "", - "# Usage:", - "print(find_longest_word('The quick brown fox')) # Output: 'quick'" - ], - "tags": ["python", "string", "longest-word", "utility"], - "author": "axorax" - }, - { - "title": "Remove Duplicate Characters", - "description": "Removes duplicate characters from a string while maintaining the order.", - "code": [ - "def remove_duplicate_chars(s):", - " seen = set()", - " return ''.join(char for char in s if not (char in seen or seen.add(char)))", - "", - "# Usage:", - "print(remove_duplicate_chars('programming')) # Output: 'progamin'" - ], - "tags": ["python", "string", "duplicates", "remove", "utility"], - "author": "axorax" - }, - { - "title": "Count Words", - "description": "Counts the number of words in a string.", - "code": [ - "def count_words(s):", - " return len(s.split())", - "", - "# Usage:", - "print(count_words('The quick brown fox')) # Output: 4" - ], - "tags": ["python", "string", "word-count", "utility"], - "author": "axorax" - }, - { - "title": "Split Camel Case", - "description": "Splits a camel case string into separate words.", - "code": [ - "import re", - "", - "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'" - ], - "tags": ["python", "string", "camel-case", "split", "utility"], - "author": "axorax" - }, - { - "title": "Count Character Frequency", - "description": "Counts the frequency of each character in a string.", - "code": [ - "from collections import Counter", - "", - "def char_frequency(s):", - " return dict(Counter(s))", - "", - "# Usage:", - "print(char_frequency('hello')) # Output: {'h': 1, 'e': 1, 'l': 2, 'o': 1}" - ], - "tags": ["python", "string", "character-frequency", "utility"], - "author": "axorax" - }, - { - "title": "Remove Whitespace", - "description": "Removes all whitespace from a string.", - "code": [ - "def remove_whitespace(s):", - " return ''.join(s.split())", - "", - "# Usage:", - "print(remove_whitespace('hello world')) # Output: 'helloworld'" - ], - "tags": ["python", "string", "whitespace", "remove", "utility"], - "author": "axorax" - }, - { - "title": "Find All Substrings", - "description": "Finds all substrings of a given string.", - "code": [ - "def find_substrings(s):", - " substrings = []", - " for i in range(len(s)):", - " for j in range(i + 1, len(s) + 1):", - " substrings.append(s[i:j])", - " return substrings", - "", - "# Usage:", - "print(find_substrings('abc')) # Output: ['a', 'ab', 'abc', 'b', 'bc', 'c']" - ], - "tags": ["python", "string", "substring", "find", "utility"], - "author": "axorax" - }, - { - "title": "Convert Snake Case to Camel Case", - "description": "Converts a snake_case string to camelCase.", - "code": [ - "def snake_to_camel(s):", - " parts = s.split('_')", - " return parts[0] + ''.join(word.capitalize() for word in parts[1:])", - "", - "# Usage:", - "print(snake_to_camel('hello_world')) # Output: 'helloWorld'" - ], - "tags": ["python", "string", "snake-case", "camel-case", "convert", "utility"], - "author": "axorax" - }, - { - "title": "Remove Specific Characters", - "description": "Removes specific characters from a string.", - "code": [ - "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'" - ], - "tags": ["python", "string", "remove", "characters", "utility"], - "author": "axorax" - }, - { - "title": "Find Unique Characters", - "description": "Finds all unique characters in a string.", - "code": [ - "def find_unique_chars(s):", - " return ''.join(sorted(set(s)))", - "", - "# Usage:", - "print(find_unique_chars('banana')) # Output: 'abn'" - ], - "tags": ["python", "string", "unique", "characters", "utility"], - "author": "axorax" - }, - { - "title": "Convert String to ASCII", - "description": "Converts a string into its ASCII representation.", - "code": [ - "def string_to_ascii(s):", - " return [ord(char) for char in s]", - "", - "# Usage:", - "print(string_to_ascii('hello')) # Output: [104, 101, 108, 108, 111]" - ], - "tags": ["python", "string", "ascii", "convert", "utility"], - "author": "axorax" - }, - { - "title": "Truncate String", - "description": "Truncates a string to a specified length and adds an ellipsis.", - "code": [ - "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 ...'" - ], - "tags": ["python", "string", "truncate", "utility"], - "author": "axorax" - } - ] - }, - { - "categoryName": "List Manipulation", - "snippets": [ - { - "title": "Flatten Nested List", - "description": "Flattens a multi-dimensional list into a single list.", - "code": [ - "def flatten_list(lst):", - " return [item for sublist in lst for item in sublist]", - "", - "# Usage:", - "nested_list = [[1, 2], [3, 4], [5]]", - "print(flatten_list(nested_list)) # Output: [1, 2, 3, 4, 5]" - ], - "tags": ["python", "list", "flatten", "utility"], - "author": "dostonnabotov" - }, - { - "title": "Flatten Unevenly Nested Lists", - "description": "Converts unevenly nested lists of any depth into a single flat list.", - "code": [ - "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)", - " else:", - " yield item", - "", - "# Usage:", - "nested_list = [1, [2, [3, 4]], 5]", - "flattened = list(flatten(nested_list))", - "print(flattened) # Output: [1, 2, 3, 4, 5]" - ], - "tags": [ - "python", - "list", - "flattening", - "nested-lists", - "depth", - "utilities" - ], - "author": "agilarasu" - }, - { - "title": "Remove Duplicates", - "description": "Removes duplicate elements from a list while maintaining order.", - "code": [ - "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]" - ], - "tags": ["python", "list", "duplicates", "utility"], - "author": "dostonnabotov" - }, - { - "title": "Find Duplicates in a List", - "description": "Identifies duplicate elements in a list.", - "code": [ - "def find_duplicates(lst):", - " seen = set()", - " duplicates = set()", - " for item in lst:", - " if item in seen:", - " duplicates.add(item)", - " else:", - " seen.add(item)", - " return list(duplicates)", - "", - "# Usage:", - "data = [1, 2, 3, 2, 4, 5, 1]", - "print(find_duplicates(data)) # Output: [1, 2]" - ], - "tags": ["python", "list", "duplicates", "utility"], - "author": "axorax" - }, - { - "title": "Partition List", - "description": "Partitions a list into sublists of a given size.", - "code": [ - "def partition_list(lst, size):", - " for i in range(0, len(lst), size):", - " yield lst[i:i + 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]]" - ], - "tags": ["python", "list", "partition", "utility"], - "author": "axorax" - }, - { - "title": "Find Intersection of Two Lists", - "description": "Finds the common elements between two lists.", - "code": [ - "def list_intersection(lst1, lst2):", - " return [item for item in lst1 if item in lst2]", - "", - "# Usage:", - "list_a = [1, 2, 3, 4]", - "list_b = [3, 4, 5, 6]", - "print(list_intersection(list_a, list_b)) # Output: [3, 4]" - ], - "tags": ["python", "list", "intersection", "utility"], - "author": "axorax" - }, - { - "title": "Find Maximum Difference in List", - "description": "Finds the maximum difference between any two elements in a list.", - "code": [ - "def max_difference(lst):", - " if not lst or len(lst) < 2:", - " return 0", - " return max(lst) - min(lst)", - "", - "# Usage:", - "data = [10, 3, 5, 20, 7]", - "print(max_difference(data)) # Output: 17" - ], - "tags": ["python", "list", "difference", "utility"], - "author": "axorax" - } - ] - }, - { - "categoryName": "File Handling", - "snippets": [ - { - "title": "Read File Lines", - "description": "Reads all lines from a file and returns them as a list.", - "code": [ - "def read_file_lines(filepath):", - " with open(filepath, 'r') as file:", - " return file.readlines()", - "", - "# Usage:", - "lines = read_file_lines('example.txt')", - "print(lines)" - ], - "tags": ["python", "file", "read", "utility"], - "author": "dostonnabotov" - }, - { - "title": "Write to File", - "description": "Writes content to a file.", - "code": [ - "def write_to_file(filepath, content):", - " with open(filepath, 'w') as file:", - " file.write(content)", - "", - "# Usage:", - "write_to_file('example.txt', 'Hello, World!')" - ], - "tags": ["python", "file", "write", "utility"], - "author": "dostonnabotov" - }, - { - "title": "Find Files", - "description": "Finds all files of the specified type within a given directory.", - "code": [ - "import os", - "", - "def find_files(directory, file_type):", - " file_type = file_type.lower() # Convert file_type to lowercase", - " found_files = []", - "", - " for root, _, files in os.walk(directory):", - " for file in files:", - " file_ext = os.path.splitext(file)[1].lower()", - " if file_ext == file_type:", - " full_path = os.path.join(root, file)", - " found_files.append(full_path)", - "", - " return found_files", - "", - "# Example Usage:", - "pdf_files = find_files('/path/to/your/directory', '.pdf')", - "print(pdf_files)" - ], - "tags": ["python", "os", "filesystem", "file_search"], - "author": "Jackeastern" - }, - { - "title": "Append to File", - "description": "Appends content to the end of a file.", - "code": [ - "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.')" - ], - "tags": ["python", "file", "append", "utility"], - "author": "axorax" - }, - { - "title": "Check if File Exists", - "description": "Checks if a file exists at the specified path.", - "code": [ - "import os", - "", - "def file_exists(filepath):", - " return os.path.isfile(filepath)", - "", - "# Usage:", - "print(file_exists('example.txt')) # Output: True or False" - ], - "tags": ["python", "file", "exists", "check", "utility"], - "author": "axorax" - }, - { - "title": "Delete File", - "description": "Deletes a file at the specified path.", - "code": [ - "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')" - ], - "tags": ["python", "file", "delete", "utility"], - "author": "axorax" - }, - { - "title": "Copy File", - "description": "Copies a file from source to destination.", - "code": [ - "import shutil", - "", - "def copy_file(src, dest):", - " shutil.copy(src, dest)", - "", - "# Usage:", - "copy_file('example.txt', 'copy_of_example.txt')" - ], - "tags": ["python", "file", "copy", "utility"], - "author": "axorax" - }, - { - "title": "List Files in Directory", - "description": "Lists all files in a specified directory.", - "code": [ - "import os", - "", - "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)" - ], - "tags": ["python", "file", "list", "directory", "utility"], - "author": "axorax" - }, - { - "title": "Get File Extension", - "description": "Gets the extension of a file.", - "code": [ - "import os", - "", - "def get_file_extension(filepath):", - " return os.path.splitext(filepath)[1]", - "", - "# Usage:", - "print(get_file_extension('example.txt')) # Output: '.txt'" - ], - "tags": ["python", "file", "extension", "utility"], - "author": "axorax" - }, - { - "title": "Read File in Chunks", - "description": "Reads a file in chunks of a specified size.", - "code": [ - "def read_file_in_chunks(filepath, chunk_size):", - " with open(filepath, 'r') as file:", - " while chunk := file.read(chunk_size):", - " yield chunk", - "", - "# Usage:", - "for chunk in read_file_in_chunks('example.txt', 1024):", - " print(chunk)" - ], - "tags": ["python", "file", "read", "chunks", "utility"], - "author": "axorax" - } - ] - }, - { - "categoryName": "Math and Numbers", - "snippets": [ - { - "title": "Find Factorial", - "description": "Calculates the factorial of a number.", - "code": [ - "def factorial(n):", - " if n == 0:", - " return 1", - " return n * factorial(n - 1)", - "", - "# Usage:", - "print(factorial(5)) # Output: 120" - ], - "tags": ["python", "math", "factorial", "utility"], - "author": "dostonnabotov" - }, - { - "title": "Check Prime Number", - "description": "Checks if a number is a prime number.", - "code": [ - "def is_prime(n):", - " if n <= 1:", - " return False", - " for i in range(2, int(n**0.5) + 1):", - " if n % i == 0:", - " return False", - " return True", - "", - "# Usage:", - "print(is_prime(17)) # Output: True" - ], - "tags": ["python", "math", "prime", "check"], - "author": "dostonnabotov" - }, - { - "title": "Check Perfect Square", - "description": "Checks if a number is a perfect square.", - "code": [ - "def is_perfect_square(n):", - " if n < 0:", - " return False", - " root = int(n**0.5)", - " return root * root == n", - "", - "# Usage:", - "print(is_perfect_square(16)) # Output: True", - "print(is_perfect_square(20)) # Output: False" - ], - "tags": ["python", "math", "perfect square", "check"], - "author": "axorax" - }, - { - "title": "Convert Binary to Decimal", - "description": "Converts a binary string to its decimal equivalent.", - "code": [ - "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" - ], - "tags": ["python", "math", "binary", "decimal", "conversion"], - "author": "axorax" - }, - { - "title": "Find LCM (Least Common Multiple)", - "description": "Calculates the least common multiple (LCM) of two numbers.", - "code": [ - "def lcm(a, b):", - " return abs(a * b) // gcd(a, b)", - "", - "# Usage:", - "print(lcm(12, 15)) # Output: 60", - "print(lcm(7, 5)) # Output: 35" - ], - "tags": ["python", "math", "lcm", "gcd", "utility"], - "author": "axorax" - }, - { - "title": "Solve Quadratic Equation", - "description": "Solves a quadratic equation ax^2 + bx + c = 0 and returns the roots.", - "code": [ - "import cmath", - "", - "def solve_quadratic(a, b, c):", - " discriminant = cmath.sqrt(b**2 - 4 * a * c)", - " root1 = (-b + discriminant) / (2 * a)", - " root2 = (-b - discriminant) / (2 * a)", - " 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))" - ], - "tags": ["python", "math", "quadratic", "equation", "solver"], - "author": "axorax" - }, - { - "title": "Calculate Compound Interest", - "description": "Calculates compound interest for a given principal amount, rate, and time period.", - "code": [ - "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" - ], - "tags": ["python", "math", "compound interest", "finance"], - "author": "axorax" - } - ] - }, - { - "categoryName": "Utilities", - "snippets": [ - { - "title": "Measure Execution Time", - "description": "Measures the execution time of a code block.", - "code": [ - "import time", - "", - "def measure_time(func, *args):", - " start = time.time()", - " result = func(*args)", - " end = time.time()", - " print(f'Execution time: {end - start:.6f} seconds')", - " return result", - "", - "# Usage:", - "def slow_function():", - " time.sleep(2)", - "", - "measure_time(slow_function)" - ], - "tags": ["python", "time", "execution", "utility"], - "author": "dostonnabotov" - }, - { - "title": "Generate Random String", - "description": "Generates a random alphanumeric string.", - "code": [ - "import random", - "import string", - "", - "def random_string(length):", - " letters_and_digits = string.ascii_letters + string.digits", - " return ''.join(random.choice(letters_and_digits) for _ in range(length))", - "", - "# Usage:", - "print(random_string(10)) # Output: Random 10-character string" - ], - "tags": ["python", "random", "string", "utility"], - "author": "dostonnabotov" - }, - { - "title": "Convert Bytes to Human-Readable Format", - "description": "Converts a size in bytes to a human-readable format.", - "code": [ - "def bytes_to_human_readable(num):", - " for unit in ['B', 'KB', 'MB', 'GB', 'TB', 'PB']:", - " if num < 1024:", - " return f\"{num:.2f} {unit}\"", - " num /= 1024", - "", - "# Usage:", - "print(bytes_to_human_readable(123456789)) # Output: '117.74 MB'" - ], - "tags": ["python", "bytes", "format", "utility"], - "author": "axorax" - } - ] - }, - { - "categoryName": "JSON Manipulation", - "snippets": [ - { - "title": "Read JSON File", - "description": "Reads a JSON file and parses its content.", - "code": [ - "import json", - "", - "def read_json(filepath):", - " with open(filepath, 'r') as file:", - " return json.load(file)", - "", - "# Usage:", - "data = read_json('data.json')", - "print(data)" - ], - "tags": ["python", "json", "file", "read"], - "author": "e3nviction" - }, - { - "title": "Write JSON File", - "description": "Writes a dictionary to a JSON file.", - "code": [ - "import json", - "", - "def write_json(filepath, data):", - " with open(filepath, 'w') as file:", - " json.dump(data, file, indent=4)", - "", - "# Usage:", - "data = {'name': 'John', 'age': 30}", - "write_json('data.json', data)" - ], - "tags": ["python", "json", "file", "write"], - "author": "e3nviction" - }, - { - "title": "Update JSON File", - "description": "Updates an existing JSON file with new data or modifies the existing values.", - "code": [ - "import json", - "", - "def update_json(filepath, new_data):", - " # Read the existing JSON data", - " with open(filepath, 'r') as file:", - " data = json.load(file)", - "", - " # Update the data with the new content", - " data.update(new_data)", - "", - " # Write the updated data back to the JSON file", - " with open(filepath, 'w') as file:", - " json.dump(data, file, indent=4)", - "", - "# Usage:", - "new_data = {'age': 31}", - "update_json('data.json', new_data)" - ], - "tags": ["python", "json", "update", "file"], - "author": "axorax" - }, - { - "title": "Merge Multiple JSON Files", - "description": "Merges multiple JSON files into one and writes the merged data into a new file.", - "code": [ - "import json", - "", - "def merge_json_files(filepaths, output_filepath):", - " merged_data = []", - "", - " # Read each JSON file and merge their data", - " for filepath in filepaths:", - " with open(filepath, 'r') as file:", - " data = json.load(file)", - " merged_data.extend(data)", - "", - " # Write the merged data into a new file", - " with open(output_filepath, 'w') as file:", - " json.dump(merged_data, file, indent=4)", - "", - "# Usage:", - "files_to_merge = ['file1.json', 'file2.json']", - "merge_json_files(files_to_merge, 'merged.json')" - ], - "tags": ["python", "json", "merge", "file"], - "author": "axorax" - }, - { - "title": "Filter JSON Data", - "description": "Filters a JSON object based on a condition and returns the filtered data.", - "code": [ - "import json", - "", - "def filter_json_data(filepath, condition):", - " with open(filepath, 'r') as file:", - " data = json.load(file)", - "", - " # Filter data based on the provided condition", - " filtered_data = [item for item in data if condition(item)]", - "", - " return filtered_data", - "", - "# Usage:", - "condition = lambda x: x['age'] > 25", - "filtered = filter_json_data('data.json', condition)", - "print(filtered)" - ], - "tags": ["python", "json", "filter", "data"], - "author": "axorax" - }, - { - "title": "Validate JSON Schema", - "description": "Validates a JSON object against a predefined schema.", - "code": [ - "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" - ], - "tags": ["python", "json", "validation", "schema"], - "author": "axorax" - }, - { - "title": "Flatten Nested JSON", - "description": "Flattens a nested JSON object into a flat dictionary.", - "code": [ - "def flatten_json(nested_json, prefix=''):", - " flat_dict = {}", - " for key, value in nested_json.items():", - " if isinstance(value, dict):", - " flat_dict.update(flatten_json(value, prefix + key + '.'))", - " else:", - " flat_dict[prefix + key] = value", - " return flat_dict", - "", - "# 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'}" - ], - "tags": ["python", "json", "flatten", "nested"], - "author": "axorax" - } - ] - }, - { - "categoryName": "SQLite Database", - "snippets": [ - { - "title": "Create SQLite Database Table", - "description": "Creates a table in an SQLite database with a dynamic schema.", - "code": [ - "import sqlite3", - "", - "def create_table(db_name, table_name, schema):", - " conn = sqlite3.connect(db_name)", - " cursor = conn.cursor()", - " schema_string = ', '.join([f'{col} {dtype}' for col, dtype in schema.items()])", - " cursor.execute(f'''", - " CREATE TABLE IF NOT EXISTS {table_name} (", - " {schema_string}", - " )''')", - " conn.commit()", - " conn.close()", - "", - "# Usage:", - "db_name = 'example.db'", - "table_name = 'users'", - "schema = {", - " 'id': 'INTEGER PRIMARY KEY',", - " 'name': 'TEXT',", - " 'age': 'INTEGER',", - " 'email': 'TEXT'", - "}", - "create_table(db_name, table_name, schema)" - ], - "tags": ["python", "sqlite", "database", "table"], - "author": "e3nviction" - }, - { - "title": "Insert Data into Sqlite Table", - "description": "Inserts a row into a specified SQLite table using a dictionary of fields and values.", - "code": [ - "import sqlite3", - "", - "def insert_into_table(db_path, table_name, data):", - " with sqlite3.connect(db_path) as conn:", - " columns = ', '.join(data.keys())", - " placeholders = ', '.join(['?'] * len(data))", - " sql = f\"INSERT INTO {table_name} ({columns}) VALUES ({placeholders})\"", - " conn.execute(sql, tuple(data.values()))", - " conn.commit()", - "", - "# Usage:", - "db_path = 'example.db'", - "table_name = 'users'", - "data = {", - " 'name': 'John Doe',", - " 'email': 'john@example.com',", - " 'age': 30", - "}", - "insert_into_table(db_path, table_name, data)" - ], - "tags": ["python", "sqlite", "database", "utility"], - "author": "e3nviction" - } - ] - }, - { - "categoryName": "Error Handling", - "snippets": [ - { - "title": "Safe Division", - "description": "Performs division with error handling.", - "code": [ - "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!'" - ], - "tags": ["python", "error-handling", "division", "utility"], - "author": "e3nviction" - }, - { - "title": "Retry Function Execution on Exception", - "description": "Retries a function execution a specified number of times if it raises an exception.", - "code": [ - "import time", - "", - "def retry(func, retries=3, delay=1):", - " for attempt in range(retries):", - " try:", - " return func()", - " except Exception as e:", - " print(f\"Attempt {attempt + 1} failed: {e}\")", - " time.sleep(delay)", - " raise Exception(\"All retry attempts failed\")", - "", - "# Usage:", - "def unstable_function():", - " raise ValueError(\"Simulated failure\")", - "", - "# Retry 3 times with 2 seconds delay:", - "try:", - " retry(unstable_function, retries=3, delay=2)", - "except Exception as e:", - " print(e) # Output: All retry attempts failed" - ], - "tags": ["python", "error-handling", "retry", "utility"], - "author": "axorax" - }, - { - "title": "Validate Input with Exception Handling", - "description": "Validates user input and handles invalid input gracefully.", - "code": [ - "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'" - ], - "tags": ["python", "error-handling", "validation", "utility"], - "author": "axorax" - }, - { - "title": "Handle File Not Found Error", - "description": "Attempts to open a file and handles the case where the file does not exist.", - "code": [ - "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!'" - ], - "tags": ["python", "error-handling", "file", "utility"], - "author": "axorax" - } - ] - }, - { - "categoryName": "Datetime Utilities", - "snippets": [ - { - "title": "Get Current Date and Time String", - "description": "Fetches the current date and time as a formatted string.", - "code": [ - "from datetime import datetime", - "", - "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'" - ], - "tags": ["python", "datetime", "utility"], - "author": "e3nviction" - }, - { - "title": "Calculate Date Difference in Milliseconds", - "description": "Calculates the difference between two dates in milliseconds.", - "code": [ - "from datetime import datetime", - "", - "def date_difference_in_millis(date1, date2):", - " delta = date2 - date1", - " return delta.total_seconds() * 1000", - "", - "# Usage:", - "d1 = datetime(2023, 1, 1, 12, 0, 0)", - "d2 = datetime(2023, 1, 1, 12, 1, 0)", - "print(date_difference_in_millis(d1, d2))" - ], - "tags": ["python", "datetime", "utility"], - "author": "e3nviction" - }, - { - "title": "Generate Date Range List", - "description": "Generates a list of dates between two given dates.", - "code": [ - "from datetime import datetime, timedelta", - "", - "def generate_date_range(start_date, end_date):", - " if start_date > end_date:", - " raise ValueError(\"start_date must be before end_date\")", - "", - " current_date = start_date", - " date_list = []", - " while current_date <= end_date:", - " date_list.append(current_date)", - " current_date += timedelta(days=1)", - "", - " return date_list", - "", - "# Usage:", - "start = datetime(2023, 1, 1)", - "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'" - ], - "tags": ["python", "datetime", "range", "utility"], - "author": "axorax" - }, - { - "title": "Determine Day of the Week", - "description": "Calculates the day of the week for a given date.", - "code": [ - "from datetime import datetime", - "", - "def get_day_of_week(date):", - " days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']", - " try:", - " return days[date.weekday()]", - " except IndexError:", - " raise ValueError(\"Invalid date\")", - "", - "# Usage:", - "date = datetime(2023, 1, 1)", - "day = get_day_of_week(date)", - "print(day) # Output: 'Sunday'" - ], - "tags": ["python", "datetime", "weekday", "utility"], - "author": "axorax" - }, - { - "title": "Check if Date is a Weekend", - "description": "Checks whether a given date falls on a weekend.", - "code": [ - "from datetime import datetime", - "", - "def is_weekend(date):", - " try:", - " return date.weekday() >= 5 # Saturday = 5, Sunday = 6", - " except AttributeError:", - " raise TypeError(\"Input must be a datetime object\")", - "", - "# Usage:", - "date = datetime(2023, 1, 1)", - "weekend = is_weekend(date)", - "print(weekend) # Output: True (Sunday)" - ], - "tags": ["python", "datetime", "weekend", "utility"], - "author": "axorax" - }, - { - "title": "Get Number of Days in a Month", - "description": "Determines the number of days in a specific month and year.", - "code": [ - "from calendar import monthrange", - "from datetime import datetime", - "", - "def get_days_in_month(year, month):", - " try:", - " return monthrange(year, month)[1]", - " except ValueError as e:", - " 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)" - ], - "tags": ["python", "datetime", "calendar", "utility"], - "author": "axorax" - } - ] - } -] + { + "categoryName": "Basics", + "snippets": [ + { + "title": "Hello, World!", + "description": "Prints Hello, World! to the terminal.", + "author": "James-Beans", + "tags": [ + "python", + "printing", + "hello-world", + "utility" + ], + "code": "print(\"Hello, World!\") # Prints Hello, World! to the terminal.\n" + } + ] + }, + { + "categoryName": "Datetime Utilities", + "snippets": [ + { + "title": "Calculate Date Difference in Milliseconds", + "description": "Calculates the difference between two dates in milliseconds.", + "author": "e3nviction", + "tags": [ + "python", + "datetime", + "utility" + ], + "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" + }, + { + "title": "Check if Date is a Weekend", + "description": "Checks whether a given date falls on a weekend.", + "author": "axorax", + "tags": [ + "python", + "datetime", + "weekend", + "utility" + ], + "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" + }, + { + "title": "Determine Day of the Week", + "description": "Calculates the day of the week for a given date.", + "author": "axorax", + "tags": [ + "python", + "datetime", + "weekday", + "utility" + ], + "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" + }, + { + "title": "Generate Date Range List", + "description": "Generates a list of dates between two given dates.", + "author": "axorax", + "tags": [ + "python", + "datetime", + "range", + "utility" + ], + "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" + }, + { + "title": "Get Current Date and Time String", + "description": "Fetches the current date and time as a formatted string.", + "author": "e3nviction", + "tags": [ + "python", + "datetime", + "utility" + ], + "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" + }, + { + "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" + ], + "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" + } + ] + }, + { + "categoryName": "Error Handling", + "snippets": [ + { + "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" + ], + "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" + ], + "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" + ], + "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" + ], + "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" + ], + "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" + ], + "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" + ], + "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" + ], + "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" + ], + "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" + }, + { + "title": "Get File Extension", + "description": "Gets the extension of a file.", + "author": "axorax", + "tags": [ + "python", + "file", + "extension", + "utility" + ], + "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" + }, + { + "title": "List Files in Directory", + "description": "Lists all files in a specified directory.", + "author": "axorax", + "tags": [ + "python", + "file", + "list", + "directory", + "utility" + ], + "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" + }, + { + "title": "Read File in Chunks", + "description": "Reads a file in chunks of a specified size.", + "author": "axorax", + "tags": [ + "python", + "file", + "read", + "chunks", + "utility" + ], + "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" + ], + "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" + ], + "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" + } + ] + }, + { + "categoryName": "Json Manipulation", + "snippets": [ + { + "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" + ], + "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" + }, + { + "title": "Flatten Nested JSON", + "description": "Flattens a nested JSON object into a flat dictionary.", + "author": "axorax", + "tags": [ + "python", + "json", + "flatten", + "nested" + ], + "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" + }, + { + "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" + ], + "code": "import json\n\ndef merge_json_files(filepaths, output_filepath):\n merged_data = []\n\n # Read each JSON file and merge their data\n for filepath in filepaths:\n with open(filepath, 'r') as file:\n data = json.load(file)\n merged_data.extend(data)\n\n # Write the merged data into a new file\n with open(output_filepath, 'w') as file:\n json.dump(merged_data, file, indent=4)\n\n# Usage:\nfiles_to_merge = ['file1.json', 'file2.json']\nmerge_json_files(files_to_merge, 'merged.json')\n" + }, + { + "title": "Read JSON File", + "description": "Reads a JSON file and parses its content.", + "author": "e3nviction", + "tags": [ + "python", + "json", + "file", + "read" + ], + "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" + }, + { + "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" + ], + "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" + ], + "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" + }, + { + "title": "Write JSON File", + "description": "Writes a dictionary to a JSON file.", + "author": "e3nviction", + "tags": [ + "python", + "json", + "file", + "write" + ], + "code": "import json\n\ndef write_json(filepath, data):\n with open(filepath, 'w') as file:\n json.dump(data, file, indent=4)\n\n# Usage:\ndata = {'name': 'John', 'age': 30}\nwrite_json('data.json', data)\n" + } + ] + }, + { + "categoryName": "List Manipulation", + "snippets": [ + { + "title": "Find Duplicates in a List", + "description": "Identifies duplicate elements in a list.", + "author": "axorax", + "tags": [ + "python", + "list", + "duplicates", + "utility" + ], + "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" + }, + { + "title": "Find Intersection of Two Lists", + "description": "Finds the common elements between two lists.", + "author": "axorax", + "tags": [ + "python", + "list", + "intersection", + "utility" + ], + "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" + }, + { + "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" + ], + "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" + }, + { + "title": "Flatten Nested List", + "description": "Flattens a multi-dimensional list into a single list.", + "author": "dostonnabotov", + "tags": [ + "python", + "list", + "flatten", + "utility" + ], + "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" + }, + { + "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" + ], + "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" + }, + { + "title": "Partition List", + "description": "Partitions a list into sublists of a given size.", + "author": "axorax", + "tags": [ + "python", + "list", + "partition", + "utility" + ], + "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" + }, + { + "title": "Remove Duplicates", + "description": "Removes duplicate elements from a list while maintaining order.", + "author": "dostonnabotov", + "tags": [ + "python", + "list", + "duplicates", + "utility" + ], + "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" + } + ] + }, + { + "categoryName": "Math And Numbers", + "snippets": [ + { + "title": "Calculate Compound Interest", + "description": "Calculates compound interest for a given principal amount, rate, and time period.", + "author": "axorax", + "tags": [ + "python", + "math", + "compound interest", + "finance" + ], + "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" + }, + { + "title": "Check Perfect Square", + "description": "Checks if a number is a perfect square.", + "author": "axorax", + "tags": [ + "python", + "math", + "perfect square", + "check" + ], + "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" + }, + { + "title": "Check Prime Number", + "description": "Checks if a number is a prime number.", + "author": "dostonnabotov", + "tags": [ + "python", + "math", + "prime", + "check" + ], + "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" + }, + { + "title": "Convert Binary to Decimal", + "description": "Converts a binary string to its decimal equivalent.", + "author": "axorax", + "tags": [ + "python", + "math", + "binary", + "decimal", + "conversion" + ], + "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" + }, + { + "title": "Find Factorial", + "description": "Calculates the factorial of a number.", + "author": "dostonnabotov", + "tags": [ + "python", + "math", + "factorial", + "utility" + ], + "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" + }, + { + "title": "Find LCM (Least Common Multiple)", + "description": "Calculates the least common multiple (LCM) of two numbers.", + "author": "axorax", + "tags": [ + "python", + "math", + "lcm", + "gcd", + "utility" + ], + "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" + }, + { + "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" + ], + "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" + } + ] + }, + { + "categoryName": "Sqlite Database", + "snippets": [ + { + "title": "Create SQLite Database Table", + "description": "Creates a table in an SQLite database with a dynamic schema.", + "author": "e3nviction", + "tags": [ + "python", + "sqlite", + "database", + "table" + ], + "code": "import sqlite3\n\ndef create_table(db_name, table_name, schema):\n conn = sqlite3.connect(db_name)\n cursor = conn.cursor()\n schema_string = ', '.join([f'{col} {dtype}' for col, dtype in schema.items()])\n cursor.execute(f'''\n CREATE TABLE IF NOT EXISTS {table_name} (\n {schema_string}\n )''')\n conn.commit()\n conn.close()\n\n# Usage:\ndb_name = 'example.db'\ntable_name = 'users'\nschema = {\n 'id': 'INTEGER PRIMARY KEY',\n 'name': 'TEXT',\n 'age': 'INTEGER',\n 'email': 'TEXT'\n}\ncreate_table(db_name, table_name, schema)\n" + }, + { + "title": "Insert Data into Sqlite Table", + "description": "Inserts a row into a specified SQLite table using a dictionary of fields and values.", + "author": "e3nviction", + "tags": [ + "python", + "sqlite", + "database", + "utility" + ], + "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" + } + ] + }, + { + "categoryName": "String Manipulation", + "snippets": [ + { + "title": "Capitalize Words", + "description": "Capitalizes the first letter of each word in a string.", + "author": "axorax", + "tags": [ + "python", + "string", + "capitalize", + "utility" + ], + "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" + }, + { + "title": "Check Anagram", + "description": "Checks if two strings are anagrams of each other.", + "author": "SteliosGee", + "tags": [ + "python", + "string", + "anagram", + "check", + "utility" + ], + "code": "def is_anagram(s1, s2):\n return sorted(s1) == sorted(s2)\n\n# Usage:\nprint(is_anagram('listen', 'silent')) # Output: True\n" + }, + { + "title": "Check Palindrome", + "description": "Checks if a string is a palindrome.", + "author": "dostonnabotov", + "tags": [ + "python", + "string", + "palindrome", + "utility" + ], + "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" + }, + { + "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" + ], + "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" + }, + { + "title": "Convert String to ASCII", + "description": "Converts a string into its ASCII representation.", + "author": "axorax", + "tags": [ + "python", + "string", + "ascii", + "convert", + "utility" + ], + "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" + }, + { + "title": "Count Character Frequency", + "description": "Counts the frequency of each character in a string.", + "author": "axorax", + "tags": [ + "python", + "string", + "character-frequency", + "utility" + ], + "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" + }, + { + "title": "Count Vowels", + "description": "Counts the number of vowels in a string.", + "author": "SteliosGee", + "tags": [ + "python", + "string", + "vowels", + "count", + "utility" + ], + "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" + }, + { + "title": "Count Words", + "description": "Counts the number of words in a string.", + "author": "axorax", + "tags": [ + "python", + "string", + "word-count", + "utility" + ], + "code": "def count_words(s):\n return len(s.split())\n\n# Usage:\nprint(count_words('The quick brown fox')) # Output: 4\n" + }, + { + "title": "Find All Substrings", + "description": "Finds all substrings of a given string.", + "author": "axorax", + "tags": [ + "python", + "string", + "substring", + "find", + "utility" + ], + "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" + }, + { + "title": "Find Longest Word", + "description": "Finds the longest word in a string.", + "author": "axorax", + "tags": [ + "python", + "string", + "longest-word", + "utility" + ], + "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" + }, + { + "title": "Find Unique Characters", + "description": "Finds all unique characters in a string.", + "author": "axorax", + "tags": [ + "python", + "string", + "unique", + "characters", + "utility" + ], + "code": "def find_unique_chars(s):\n return ''.join(sorted(set(s)))\n\n# Usage:\nprint(find_unique_chars('banana')) # Output: 'abn'\n" + }, + { + "title": "Remove Duplicate Characters", + "description": "Removes duplicate characters from a string while maintaining the order.", + "author": "axorax", + "tags": [ + "python", + "string", + "duplicates", + "remove", + "utility" + ], + "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" + }, + { + "title": "Remove Punctuation", + "description": "Removes punctuation from a string.", + "author": "SteliosGee", + "tags": [ + "python", + "string", + "punctuation", + "remove", + "utility" + ], + "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" + }, + { + "title": "Remove Specific Characters", + "description": "Removes specific characters from a string.", + "author": "axorax", + "tags": [ + "python", + "string", + "remove", + "characters", + "utility" + ], + "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" + }, + { + "title": "Remove Whitespace", + "description": "Removes all whitespace from a string.", + "author": "axorax", + "tags": [ + "python", + "string", + "whitespace", + "remove", + "utility" + ], + "code": "def remove_whitespace(s):\n return ''.join(s.split())\n\n# Usage:\nprint(remove_whitespace('hello world')) # Output: 'helloworld'\n" + }, + { + "title": "Reverse String", + "description": "Reverses the characters in a string.", + "author": "dostonnabotov", + "tags": [ + "python", + "string", + "reverse", + "utility" + ], + "code": "def reverse_string(s):\n return s[::-1]\n\n# Usage:\nprint(reverse_string('hello')) # Output: 'olleh'\n" + }, + { + "title": "Split Camel Case", + "description": "Splits a camel case string into separate words.", + "author": "axorax", + "tags": [ + "python", + "string", + "camel-case", + "split", + "utility" + ], + "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" + }, + { + "title": "Truncate String", + "description": "Truncates a string to a specified length and adds an ellipsis.", + "author": "axorax", + "tags": [ + "python", + "string", + "truncate", + "utility" + ], + "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" + ], + "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" + ], + "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" + ], + "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" + } + ] + } +] \ No newline at end of file diff --git a/public/data/rust.json b/public/data/rust.json index 5e53632c..7763a959 100644 --- a/public/data/rust.json +++ b/public/data/rust.json @@ -1,91 +1,64 @@ [ - { - "categoryName": "Basics", - "snippets": [ - { - "title": "Hello, World!", - "description": "Prints Hello, World! to the terminal.", - "code": [ - "fn main() { // Defines the main running function", - " println!(\"Hello, World!\"); // Prints Hello, World! to the terminal.", - "}" - ], - "tags": ["rust", "printing", "hello-world", "utility"], - "author": "James-Beans" - } - ] - }, - { - "categoryName": "String Manipulation", - "snippets": [ - { - "title": "Capitalize String", - "description": "Makes the first letter of a string uppercase.", - "code": [ - "fn capitalized(str: &str) -> String {", - " let mut chars = str.chars();", - " match chars.next() {", - " None => String::new(),", - " Some(f) => f.to_uppercase().chain(chars).collect(),", - " }", - "}", - "", - "// Usage:", - "assert_eq!(capitalized(\"lower_case\"), \"Lower_case\")" - ], - "tags": ["rust", "string", "capitalize", "utility"], - "author": "Mathys-Gasnier" - } - ] - }, - { - "categoryName": "File Handling", - "snippets": [ - { - "title": "Read File Lines", - "description": "Reads all lines from a file and returns them as a vector of strings.", - "code": [ - "fn read_lines(file_name: &str) -> std::io::Result>", - " Ok(", - " std::fs::read_to_string(file_name)?", - " .lines()", - " .map(String::from)", - " .collect()", - " )", - "}", - "", - "// Usage:", - "let lines = read_lines(\"path/to/file.txt\").expect(\"Failed to read lines from file\")" - ], - "tags": ["rust", "file", "read", "utility"], - "author": "Mathys-Gasnier" - }, - { - "title": "Find Files", - "description": "Finds all files of the specified extension within a given directory.", - "code": [ - "fn find_files(directory: &str, file_type: &str) -> std::io::Result> {", - " let mut result = vec![];", - "", - " for entry in std::fs::read_dir(directory)? {", - " let dir = entry?;", - " let path = dir.path();", - " if dir.file_type().is_ok_and(|t| !t.is_file()) &&", - " path.extension().is_some_and(|ext| ext != file_type) {", - " continue;", - " }", - " result.push(path)", - " }", - "", - " Ok(result)", - "}", - "", - "// Usage:", - "let files = find_files(\"/path/to/your/directory\", \".pdf\")" - ], - "tags": ["rust", "file", "search"], - "author": "Mathys-Gasnier" - } - ] - } -] + { + "categoryName": "Basics", + "snippets": [ + { + "title": "Hello, World!", + "description": "Prints Hello, World! to the terminal.", + "author": "James-Beans", + "tags": [ + "rust", + "printing", + "hello-world", + "utility" + ], + "code": "fn main() { // Defines the main running function\n println!(\"Hello, World!\"); // Prints Hello, World! to the terminal.\n}\n" + } + ] + }, + { + "categoryName": "File Handling", + "snippets": [ + { + "title": "Find Files", + "description": "Finds all files of the specified extension within a given directory.", + "author": "Mathys-Gasnier", + "tags": [ + "rust", + "file", + "search" + ], + "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" + }, + { + "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" + ], + "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" + } + ] + }, + { + "categoryName": "String Manipulation", + "snippets": [ + { + "title": "Capitalize String", + "description": "Makes the first letter of a string uppercase.", + "author": "Mathys-Gasnier", + "tags": [ + "rust", + "string", + "capitalize", + "utility" + ], + "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" + } + ] + } +] \ No newline at end of file diff --git a/public/data/scss.json b/public/data/scss.json index b0daf4bd..955e528a 100644 --- a/public/data/scss.json +++ b/public/data/scss.json @@ -1,251 +1,201 @@ [ - { - "categoryName": "Typography", - "snippets": [ - { - "title": "Line Clamp Mixin", - "description": "A Sass mixin to clamp text to a specific number of lines.", - "code": [ - "@mixin line-clamp($number) {", - " display: -webkit-box;", - " -webkit-box-orient: vertical;", - " -webkit-line-clamp: $number;", - " overflow: hidden;", - "}" - ], - "tags": ["sass", "mixin", "typography", "css"], - "author": "dostonnabotov" - }, - { - "title": "Text Overflow Ellipsis", - "description": "Ensures long text is truncated with an ellipsis.", - "code": [ - "@mixin text-ellipsis {", - " overflow: hidden;", - " white-space: nowrap;", - " text-overflow: ellipsis;", - "}" - ], - "tags": ["sass", "mixin", "text", "css"], - "author": "dostonnabotov" - }, - { - "title": "Font Import Helper", - "description": "Simplifies importing custom fonts in Sass.", - "code": [ - "@mixin import-font($family, $weight: 400, $style: normal) {", - " @font-face {", - " font-family: #{$family};", - " font-weight: #{$weight};", - " font-style: #{$style};", - " src: url('/fonts/#{$family}-#{$weight}.woff2') format('woff2'),", - " url('/fonts/#{$family}-#{$weight}.woff') format('woff');", - " }", - "}" - ], - "tags": ["sass", "mixin", "fonts", "css"], - "author": "dostonnabotov" - }, - { - "title": "Text Gradient", - "description": "Adds a gradient color effect to text.", - "code": [ - "@mixin text-gradient($from, $to) {", - " background: linear-gradient(to right, $from, $to);", - " -webkit-background-clip: text;", - " -webkit-text-fill-color: transparent;", - "}" - ], - "tags": ["sass", "mixin", "gradient", "text", "css"], - "author": "dostonnabotov" - } - ] - }, - { - "categoryName": "Layouts", - "snippets": [ - { - "title": "Grid Container", - "description": "Creates a responsive grid container with customizable column counts.", - "code": [ - "@mixin grid-container($columns: 12, $gap: 1rem) {", - " display: grid;", - " grid-template-columns: repeat($columns, 1fr);", - " gap: $gap;", - "}" - ], - "tags": ["scss", "grid", "layout", "css"], - "author": "dostonnabotov" - }, - { - "title": "Flex Center", - "description": "A mixin to center content using flexbox.", - "code": [ - "@mixin flex-center {", - " display: flex;", - " justify-content: center;", - " align-items: center;", - "}" - ], - "tags": ["scss", "flex", "center", "css"], - "author": "dostonnabotov" - }, - { - "title": "Aspect Ratio", - "description": "Ensures that elements maintain a specific aspect ratio.", - "code": [ - "@mixin aspect-ratio($width, $height) {", - " position: relative;", - " width: 100%;", - " padding-top: ($height / $width) * 100%;", - " > * {", - " position: absolute;", - " top: 0;", - " left: 0;", - " width: 100%;", - " height: 100%;", - " }", - "}" - ], - "tags": ["scss", "aspect-ratio", "layout", "css"], - "author": "dostonnabotov" - } - ] - }, - { - "categoryName": "Animations", - "snippets": [ - { - "title": "Fade In Animation", - "description": "Animates the fade-in effect.", - "code": [ - "@keyframes fade-in {", - " from {", - " opacity: 0;", - " }", - " to {", - " opacity: 1;", - " }", - "}", - "", - "@mixin fade-in($duration: 1s, $easing: ease-in-out) {", - " animation: fade-in $duration $easing;", - "}" - ], - "tags": ["scss", "animation", "fade", "css"], - "author": "dostonnabotov" - }, - { - "title": "Slide In From Left", - "description": "Animates content sliding in from the left.", - "code": [ - "@keyframes slide-in-left {", - " from {", - " transform: translateX(-100%);", - " }", - " to {", - " transform: translateX(0);", - " }", - "}", - "", - "@mixin slide-in-left($duration: 0.5s, $easing: ease-out) {", - " animation: slide-in-left $duration $easing;", - "}" - ], - "tags": ["scss", "animation", "slide", "css"], - "author": "dostonnabotov" - } - ] - }, - { - "categoryName": "Utilities", - "snippets": [ - { - "title": "Responsive Breakpoints", - "description": "Generates media queries for responsive design.", - "code": [ - "@mixin breakpoint($breakpoint) {", - " @if $breakpoint == sm {", - " @media (max-width: 576px) { @content; }", - " } @else if $breakpoint == md {", - " @media (max-width: 768px) { @content; }", - " } @else if $breakpoint == lg {", - " @media (max-width: 992px) { @content; }", - " } @else if $breakpoint == xl {", - " @media (max-width: 1200px) { @content; }", - " }", - "}" - ], - "tags": ["scss", "responsive", "media-queries", "css"], - "author": "dostonnabotov" - }, - { - "title": "Clearfix", - "description": "Provides a clearfix utility for floating elements.", - "code": [ - "@mixin clearfix {", - " &::after {", - " content: '';", - " display: block;", - " clear: both;", - " }", - "}" - ], - "tags": ["scss", "clearfix", "utility", "css"], - "author": "dostonnabotov" - } - ] - }, - { - "categoryName": "Borders & Shadows", - "snippets": [ - { - "title": "Border Radius Helper", - "description": "Applies a customizable border-radius.", - "code": [ - "@mixin border-radius($radius: 4px) {", - " border-radius: $radius;", - "}" - ], - "tags": ["scss", "border", "radius", "css"], - "author": "dostonnabotov" - }, - { - "title": "Box Shadow Helper", - "description": "Generates a box shadow with customizable values.", - "code": [ - "@mixin box-shadow($x: 0px, $y: 4px, $blur: 10px, $spread: 0px, $color: rgba(0, 0, 0, 0.1)) {", - " box-shadow: $x $y $blur $spread $color;", - "}" - ], - "tags": ["scss", "box-shadow", "css", "effects"], - "author": "dostonnabotov" - } - ] - }, - { - "categoryName": "Components", - "snippets": [ - { - "title": "Primary Button", - "description": "Generates a styled primary button.", - "code": [ - "@mixin primary-button($bg: #007bff, $color: #fff) {", - " background-color: $bg;", - " color: $color;", - " padding: 0.5rem 1rem;", - " border: none;", - " border-radius: 4px;", - " cursor: pointer;", - "", - " &:hover {", - " background-color: darken($bg, 10%);", - " }", - "}" - ], - "tags": ["scss", "button", "primary", "css"], - "author": "dostonnabotov" - } - ] - } -] + { + "categoryName": "Animations", + "snippets": [ + { + "title": "Fade In Animation", + "description": "Animates the fade-in effect.", + "author": "dostonnabotov", + "tags": [ + "scss", + "animation", + "fade", + "css" + ], + "code": "@keyframes fade-in {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n@mixin fade-in($duration: 1s, $easing: ease-in-out) {\n animation: fade-in $duration $easing;\n}\n" + }, + { + "title": "Slide In From Left", + "description": "Animates content sliding in from the left.", + "author": "dostonnabotov", + "tags": [ + "scss", + "animation", + "slide", + "css" + ], + "code": "@keyframes slide-in-left {\n from {\n transform: translateX(-100%);\n }\n to {\n transform: translateX(0);\n }\n}\n\n@mixin slide-in-left($duration: 0.5s, $easing: ease-out) {\n animation: slide-in-left $duration $easing;\n}\n" + } + ] + }, + { + "categoryName": "Borders Shadows", + "snippets": [ + { + "title": "Border Radius Helper", + "description": "Applies a customizable border-radius.", + "author": "dostonnabotov", + "tags": [ + "scss", + "border", + "radius", + "css" + ], + "code": "@mixin border-radius($radius: 4px) {\n border-radius: $radius;\n}\n" + }, + { + "title": "Box Shadow Helper", + "description": "Generates a box shadow with customizable values.", + "author": "dostonnabotov", + "tags": [ + "scss", + "box-shadow", + "css", + "effects" + ], + "code": "@mixin box-shadow($x: 0px, $y: 4px, $blur: 10px, $spread: 0px, $color: rgba(0, 0, 0, 0.1)) {\n box-shadow: $x $y $blur $spread $color;\n}\n" + } + ] + }, + { + "categoryName": "Components", + "snippets": [ + { + "title": "Primary Button", + "description": "Generates a styled primary button.", + "author": "dostonnabotov", + "tags": [ + "scss", + "button", + "primary", + "css" + ], + "code": "@mixin primary-button($bg: #007bff, $color: #fff) {\n background-color: $bg;\n color: $color;\n padding: 0.5rem 1rem;\n border: none;\n border-radius: 4px;\n cursor: pointer;\n\n &:hover {\n background-color: darken($bg, 10%);\n }\n}\n" + } + ] + }, + { + "categoryName": "Layouts", + "snippets": [ + { + "title": "Aspect Ratio", + "description": "Ensures that elements maintain a specific aspect ratio.", + "author": "dostonnabotov", + "tags": [ + "scss", + "aspect-ratio", + "layout", + "css" + ], + "code": "@mixin aspect-ratio($width, $height) {\n position: relative;\n width: 100%;\n padding-top: ($height / $width) * 100%;\n > * {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n }\n}\n" + }, + { + "title": "Flex Center", + "description": "A mixin to center content using flexbox.", + "author": "dostonnabotov", + "tags": [ + "scss", + "flex", + "center", + "css" + ], + "code": "@mixin flex-center {\n display: flex;\n justify-content: center;\n align-items: center;\n}\n" + }, + { + "title": "Grid Container", + "description": "Creates a responsive grid container with customizable column counts.", + "author": "dostonnabotov", + "tags": [ + "scss", + "grid", + "layout", + "css" + ], + "code": "@mixin grid-container($columns: 12, $gap: 1rem) {\n display: grid;\n grid-template-columns: repeat($columns, 1fr);\n gap: $gap;\n}\n" + } + ] + }, + { + "categoryName": "Typography", + "snippets": [ + { + "title": "Font Import Helper", + "description": "Simplifies importing custom fonts in Sass.", + "author": "dostonnabotov", + "tags": [ + "sass", + "mixin", + "fonts", + "css" + ], + "code": "@mixin import-font($family, $weight: 400, $style: normal) {\n @font-face {\n font-family: #{$family};\n font-weight: #{$weight};\n font-style: #{$style};\n src: url('/fonts/#{$family}-#{$weight}.woff2') format('woff2'),\n url('/fonts/#{$family}-#{$weight}.woff') format('woff');\n }\n}\n" + }, + { + "title": "Line Clamp Mixin", + "description": "A Sass mixin to clamp text to a specific number of lines.", + "author": "dostonnabotov", + "tags": [ + "sass", + "mixin", + "typography", + "css" + ], + "code": "@mixin line-clamp($number) {\n display: -webkit-box;\n -webkit-box-orient: vertical;\n -webkit-line-clamp: $number;\n overflow: hidden;\n}\n" + }, + { + "title": "Text Gradient", + "description": "Adds a gradient color effect to text.", + "author": "dostonnabotov", + "tags": [ + "sass", + "mixin", + "gradient", + "text", + "css" + ], + "code": "@mixin text-gradient($from, $to) {\n background: linear-gradient(to right, $from, $to);\n -webkit-background-clip: text;\n -webkit-text-fill-color: transparent;\n}\n" + }, + { + "title": "Text Overflow Ellipsis", + "description": "Ensures long text is truncated with an ellipsis.", + "author": "dostonnabotov", + "tags": [ + "sass", + "mixin", + "text", + "css" + ], + "code": "@mixin text-ellipsis {\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n" + } + ] + }, + { + "categoryName": "Utilities", + "snippets": [ + { + "title": "Clearfix", + "description": "Provides a clearfix utility for floating elements.", + "author": "dostonnabotov", + "tags": [ + "scss", + "clearfix", + "utility", + "css" + ], + "code": "@mixin clearfix {\n &::after {\n content: '';\n display: block;\n clear: both;\n }\n}\n" + }, + { + "title": "Responsive Breakpoints", + "description": "Generates media queries for responsive design.", + "author": "dostonnabotov", + "tags": [ + "scss", + "responsive", + "media-queries", + "css" + ], + "code": "@mixin breakpoint($breakpoint) {\n @if $breakpoint == sm {\n @media (max-width: 576px) { @content; }\n } @else if $breakpoint == md {\n @media (max-width: 768px) { @content; }\n } @else if $breakpoint == lg {\n @media (max-width: 992px) { @content; }\n } @else if $breakpoint == xl {\n @media (max-width: 1200px) { @content; }\n }\n}\n" + } + ] + } +] \ No newline at end of file From 148a975cd61e14799aa5a2fd32f2f06f675459cb Mon Sep 17 00:00:00 2001 From: Mathys-Gasnier Date: Wed, 1 Jan 2025 12:47:21 +0100 Subject: [PATCH 04/10] Fix the frontend to support the change from of code from `string[]` to `string` --- src/components/CodePreview.tsx | 6 +++--- src/types/index.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/components/CodePreview.tsx b/src/components/CodePreview.tsx index 29fcaf42..f87b044f 100644 --- a/src/components/CodePreview.tsx +++ b/src/components/CodePreview.tsx @@ -5,7 +5,7 @@ import { useEffect, useState } from "react"; type Props = { language: string; - code: string[]; + code: string; }; const CodePreview = ({ language = "markdown", code }: Props) => { @@ -29,14 +29,14 @@ const CodePreview = ({ language = "markdown", code }: Props) => { return (
- + - {code.join("\n")} + {code}
); diff --git a/src/types/index.ts b/src/types/index.ts index 31b79fe3..b4eac550 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -11,7 +11,7 @@ export type CategoryType = { export type SnippetType = { title: string; description: string; - code: string[]; + code: string; tags: string[]; author: string; }; From 63eaf1909a5cda96ff93ed05e3367edea1100339 Mon Sep 17 00:00:00 2001 From: Mathys-Gasnier Date: Wed, 1 Jan 2025 13:32:12 +0100 Subject: [PATCH 05/10] Making the language folder name, the name of the language instead of the slug name of the language --- public/data/_index.json | 8 ++++---- snippets/{c => C}/basics/hello-world.md | 0 snippets/{c => C}/icon.svg | 0 .../mathematical-functions/factorial-function.md | 0 .../{c => C}/mathematical-functions/power-function.md | 0 snippets/{cpp => CPP}/basics/hello-world.md | 0 snippets/{cpp => CPP}/icon.svg | 0 .../string-manipulation/reverse-string.md | 0 .../{cpp => CPP}/string-manipulation/split-string.md | 0 snippets/{css => CSS}/buttons/3d-button-effect.md | 0 snippets/{css => CSS}/buttons/button-hover-effect.md | 0 snippets/{css => CSS}/buttons/macos-button.md | 0 snippets/{css => CSS}/effects/blur-background.md | 0 snippets/{css => CSS}/effects/hover-glow-effect.md | 0 snippets/{css => CSS}/icon.svg | 0 snippets/{css => CSS}/layouts/css-reset.md | 0 snippets/{css => CSS}/layouts/equal-width-columns.md | 0 snippets/{css => CSS}/layouts/grid-layout.md | 0 snippets/{css => CSS}/layouts/responsive-design.md | 0 snippets/{css => CSS}/layouts/sticky-footer.md | 0 snippets/{css => CSS}/typography/letter-spacing.md | 0 .../{css => CSS}/typography/responsive-font-sizing.md | 0 .../basic-layouts/grid-layout-with-navigation.md | 0 .../basic-layouts/sticky-header-footer-layout.md | 0 snippets/{html => HTML}/icon.svg | 0 .../array-manipulation/flatten-array.md | 0 .../array-manipulation/remove-duplicates.md | 0 .../array-manipulation/shuffle-array.md | 0 .../array-manipulation/zip-arrays.md | 0 .../{javascript => Javascript}/basics/hello-world.md | 0 .../date-and-time/add-days-to-a-date.md | 0 .../date-and-time/check-leap-year.md | 0 .../date-and-time/format-date.md | 0 .../date-and-time/get-current-timestamp.md | 0 .../date-and-time/get-day-of-the-year.md | 0 .../date-and-time/get-days-in-month.md | 0 .../date-and-time/get-time-difference.md | 0 .../date-and-time/relative-time-formatter.md | 0 .../date-and-time/start-of-the-day.md | 0 .../dom-manipulation/change-element-style.md | 0 .../dom-manipulation/get-element-position.md | 0 .../dom-manipulation/remove-element.md | 0 .../dom-manipulation/smooth-scroll-to-element.md | 0 .../dom-manipulation/toggle-class.md | 0 .../function-utilities/compose-functions.md | 0 .../function-utilities/curry-function.md | 0 .../function-utilities/debounce-function.md | 0 .../function-utilities/get-contrast-color.md | 0 .../function-utilities/memoize-function.md | 0 .../function-utilities/once-function.md | 0 .../function-utilities/rate-limit-function.md | 0 .../function-utilities/repeat-function-invocation.md | 0 .../function-utilities/sleep-function.md | 0 .../function-utilities/throttle-function.md | 0 snippets/{javascript => Javascript}/icon.svg | 0 .../local-storage/add-item-to-localstorage.md | 0 .../check-if-item-exists-in-localstorage.md | 0 .../local-storage/clear-all-localstorage.md | 0 .../local-storage/retrieve-item-from-localstorage.md | 0 .../number-formatting/convert-number-to-currency.md | 0 .../convert-number-to-roman-numerals.md | 0 .../convert-to-scientific-notation.md | 0 .../number-formatting/format-number-with-commas.md | 0 .../number-formatting/number-formatter.md | 0 .../number-formatting/number-to-words-converter.md | 0 .../object-manipulation/check-if-object-is-empty.md | 0 .../object-manipulation/clone-object-shallowly.md | 0 .../compare-two-objects-shallowly.md | 0 .../convert-object-to-query-string.md | 0 .../object-manipulation/count-properties-in-object.md | 0 .../object-manipulation/filter-object.md | 0 .../object-manipulation/flatten-nested-object.md | 0 .../object-manipulation/freeze-object.md | 0 .../object-manipulation/get-nested-value.md | 0 .../invert-object-keys-and-values.md | 0 .../object-manipulation/merge-objects-deeply.md | 0 .../object-manipulation/omit-keys-from-object.md | 0 .../object-manipulation/pick-keys-from-object.md | 0 .../object-manipulation/unique-by-key.md | 0 .../regex-match-utility-function.md | 0 .../string-manipulation/capitalize-string.md | 0 .../check-if-string-is-a-palindrome.md | 0 .../convert-string-to-camel-case.md | 0 .../convert-string-to-param-case.md | 0 .../convert-string-to-pascal-case.md | 0 .../convert-string-to-snake-case.md | 0 .../convert-string-to-title-case.md | 0 .../string-manipulation/convert-tabs-to-spaces.md | 0 .../string-manipulation/count-words-in-a-string.md | 0 .../string-manipulation/data-with-prefix.md | 0 .../string-manipulation/extract-initials-from-name.md | 0 .../string-manipulation/mask-sensitive-information.md | 0 .../string-manipulation/pad-string-on-both-sides.md | 0 .../string-manipulation/random-string.md | 0 .../string-manipulation/remove-all-whitespace.md | 0 .../remove-vowels-from-a-string.md | 0 .../string-manipulation/reverse-string.md | 0 .../string-manipulation/slugify-string.md | 0 .../string-manipulation/truncate-text.md | 0 snippets/{python => Python}/basics/hello-world.md | 0 .../calculate-date-difference-in-milliseconds.md | 0 .../datetime-utilities/check-if-date-is-a-weekend.md | 0 .../datetime-utilities/determine-day-of-the-week.md | 0 .../datetime-utilities/generate-date-range-list.md | 0 .../get-current-date-and-time-string.md | 0 .../get-number-of-days-in-a-month.md | 0 .../error-handling/handle-file-not-found-error.md | 0 .../retry-function-execution-on-exception.md | 0 .../error-handling/safe-division.md | 0 .../validate-input-with-exception-handling.md | 0 .../file-handling/append-to-file.md | 0 .../file-handling/check-if-file-exists.md | 0 .../{python => Python}/file-handling/copy-file.md | 0 .../{python => Python}/file-handling/delete-file.md | 0 .../{python => Python}/file-handling/find-files.md | 0 .../file-handling/get-file-extension.md | 0 .../file-handling/list-files-in-directory.md | 0 .../file-handling/read-file-in-chunks.md | 0 .../file-handling/read-file-lines.md | 0 .../{python => Python}/file-handling/write-to-file.md | 0 snippets/{python => Python}/icon.svg | 0 .../json-manipulation/filter-json-data.md | 0 .../json-manipulation/flatten-nested-json.md | 0 .../json-manipulation/merge-multiple-json-files.md | 0 .../json-manipulation/read-json-file.md | 0 .../json-manipulation/update-json-file.md | 0 .../json-manipulation/validate-json-schema.md | 0 .../json-manipulation/write-json-file.md | 0 .../list-manipulation/find-duplicates-in-a-list.md | 0 .../find-intersection-of-two-lists.md | 0 .../find-maximum-difference-in-list.md | 0 .../list-manipulation/flatten-nested-list.md | 0 .../flatten-unevenly-nested-lists.md | 0 .../list-manipulation/partition-list.md | 0 .../list-manipulation/remove-duplicates.md | 0 .../math-and-numbers/calculate-compound-interest.md | 0 .../math-and-numbers/check-perfect-square.md | 0 .../math-and-numbers/check-prime-number.md | 0 .../math-and-numbers/convert-binary-to-decimal.md | 0 .../math-and-numbers/find-factorial.md | 0 .../find-lcm-least-common-multiple.md | 0 .../math-and-numbers/solve-quadratic-equation.md | 0 .../sqlite-database/create-sqlite-database-table.md | 0 .../sqlite-database/insert-data-into-sqlite-table.md | 0 .../string-manipulation/capitalize-words.md | 0 .../string-manipulation/check-anagram.md | 0 .../string-manipulation/check-palindrome.md | 0 .../convert-snake-case-to-camel-case.md | 0 .../string-manipulation/convert-string-to-ascii.md | 0 .../string-manipulation/count-character-frequency.md | 0 .../string-manipulation/count-vowels.md | 0 .../string-manipulation/count-words.md | 0 .../string-manipulation/find-all-substrings.md | 0 .../string-manipulation/find-longest-word.md | 0 .../string-manipulation/find-unique-characters.md | 0 .../remove-duplicate-characters.md | 0 .../string-manipulation/remove-punctuation.md | 0 .../string-manipulation/remove-specific-characters.md | 0 .../string-manipulation/remove-whitespace.md | 0 .../string-manipulation/reverse-string.md | 0 .../string-manipulation/split-camel-case.md | 0 .../string-manipulation/truncate-string.md | 0 .../convert-bytes-to-human-readable-format.md | 0 .../utilities/generate-random-string.md | 0 .../utilities/measure-execution-time.md | 0 snippets/{rust => Rust}/basics/hello-world.md | 0 snippets/{rust => Rust}/file-handling/find-files.md | 0 .../{rust => Rust}/file-handling/read-file-lines.md | 0 snippets/{rust => Rust}/icon.svg | 0 .../string-manipulation/capitalize-string.md | 0 .../{scss => SCSS}/animations/fade-in-animation.md | 0 .../{scss => SCSS}/animations/slide-in-from-left.md | 0 .../borders-shadows/border-radius-helper.md | 0 .../borders-shadows/box-shadow-helper.md | 0 snippets/{scss => SCSS}/components/primary-button.md | 0 snippets/{scss => SCSS}/icon.svg | 0 snippets/{scss => SCSS}/layouts/aspect-ratio.md | 0 snippets/{scss => SCSS}/layouts/flex-center.md | 0 snippets/{scss => SCSS}/layouts/grid-container.md | 0 .../{scss => SCSS}/typography/font-import-helper.md | 0 .../{scss => SCSS}/typography/line-clamp-mixin.md | 0 snippets/{scss => SCSS}/typography/text-gradient.md | 0 .../typography/text-overflow-ellipsis.md | 0 snippets/{scss => SCSS}/utilities/clearfix.md | 0 .../utilities/responsive-breakpoints.md | 0 utils/consolidateSnippets.js | 9 +++++---- utils/snippetParser.js | 11 +++++++++++ 187 files changed, 20 insertions(+), 8 deletions(-) rename snippets/{c => C}/basics/hello-world.md (100%) rename snippets/{c => C}/icon.svg (100%) rename snippets/{c => C}/mathematical-functions/factorial-function.md (100%) rename snippets/{c => C}/mathematical-functions/power-function.md (100%) rename snippets/{cpp => CPP}/basics/hello-world.md (100%) rename snippets/{cpp => CPP}/icon.svg (100%) rename snippets/{cpp => CPP}/string-manipulation/reverse-string.md (100%) rename snippets/{cpp => CPP}/string-manipulation/split-string.md (100%) rename snippets/{css => CSS}/buttons/3d-button-effect.md (100%) rename snippets/{css => CSS}/buttons/button-hover-effect.md (100%) rename snippets/{css => CSS}/buttons/macos-button.md (100%) rename snippets/{css => CSS}/effects/blur-background.md (100%) rename snippets/{css => CSS}/effects/hover-glow-effect.md (100%) rename snippets/{css => CSS}/icon.svg (100%) rename snippets/{css => CSS}/layouts/css-reset.md (100%) rename snippets/{css => CSS}/layouts/equal-width-columns.md (100%) rename snippets/{css => CSS}/layouts/grid-layout.md (100%) rename snippets/{css => CSS}/layouts/responsive-design.md (100%) rename snippets/{css => CSS}/layouts/sticky-footer.md (100%) rename snippets/{css => CSS}/typography/letter-spacing.md (100%) rename snippets/{css => CSS}/typography/responsive-font-sizing.md (100%) rename snippets/{html => HTML}/basic-layouts/grid-layout-with-navigation.md (100%) rename snippets/{html => HTML}/basic-layouts/sticky-header-footer-layout.md (100%) rename snippets/{html => HTML}/icon.svg (100%) rename snippets/{javascript => Javascript}/array-manipulation/flatten-array.md (100%) rename snippets/{javascript => Javascript}/array-manipulation/remove-duplicates.md (100%) rename snippets/{javascript => Javascript}/array-manipulation/shuffle-array.md (100%) rename snippets/{javascript => Javascript}/array-manipulation/zip-arrays.md (100%) rename snippets/{javascript => Javascript}/basics/hello-world.md (100%) rename snippets/{javascript => Javascript}/date-and-time/add-days-to-a-date.md (100%) rename snippets/{javascript => Javascript}/date-and-time/check-leap-year.md (100%) rename snippets/{javascript => Javascript}/date-and-time/format-date.md (100%) rename snippets/{javascript => Javascript}/date-and-time/get-current-timestamp.md (100%) rename snippets/{javascript => Javascript}/date-and-time/get-day-of-the-year.md (100%) rename snippets/{javascript => Javascript}/date-and-time/get-days-in-month.md (100%) rename snippets/{javascript => Javascript}/date-and-time/get-time-difference.md (100%) rename snippets/{javascript => Javascript}/date-and-time/relative-time-formatter.md (100%) rename snippets/{javascript => Javascript}/date-and-time/start-of-the-day.md (100%) rename snippets/{javascript => Javascript}/dom-manipulation/change-element-style.md (100%) rename snippets/{javascript => Javascript}/dom-manipulation/get-element-position.md (100%) rename snippets/{javascript => Javascript}/dom-manipulation/remove-element.md (100%) rename snippets/{javascript => Javascript}/dom-manipulation/smooth-scroll-to-element.md (100%) rename snippets/{javascript => Javascript}/dom-manipulation/toggle-class.md (100%) rename snippets/{javascript => Javascript}/function-utilities/compose-functions.md (100%) rename snippets/{javascript => Javascript}/function-utilities/curry-function.md (100%) rename snippets/{javascript => Javascript}/function-utilities/debounce-function.md (100%) rename snippets/{javascript => Javascript}/function-utilities/get-contrast-color.md (100%) rename snippets/{javascript => Javascript}/function-utilities/memoize-function.md (100%) rename snippets/{javascript => Javascript}/function-utilities/once-function.md (100%) rename snippets/{javascript => Javascript}/function-utilities/rate-limit-function.md (100%) rename snippets/{javascript => Javascript}/function-utilities/repeat-function-invocation.md (100%) rename snippets/{javascript => Javascript}/function-utilities/sleep-function.md (100%) rename snippets/{javascript => Javascript}/function-utilities/throttle-function.md (100%) rename snippets/{javascript => Javascript}/icon.svg (100%) rename snippets/{javascript => Javascript}/local-storage/add-item-to-localstorage.md (100%) rename snippets/{javascript => Javascript}/local-storage/check-if-item-exists-in-localstorage.md (100%) rename snippets/{javascript => Javascript}/local-storage/clear-all-localstorage.md (100%) rename snippets/{javascript => Javascript}/local-storage/retrieve-item-from-localstorage.md (100%) rename snippets/{javascript => Javascript}/number-formatting/convert-number-to-currency.md (100%) rename snippets/{javascript => Javascript}/number-formatting/convert-number-to-roman-numerals.md (100%) rename snippets/{javascript => Javascript}/number-formatting/convert-to-scientific-notation.md (100%) rename snippets/{javascript => Javascript}/number-formatting/format-number-with-commas.md (100%) rename snippets/{javascript => Javascript}/number-formatting/number-formatter.md (100%) rename snippets/{javascript => Javascript}/number-formatting/number-to-words-converter.md (100%) rename snippets/{javascript => Javascript}/object-manipulation/check-if-object-is-empty.md (100%) rename snippets/{javascript => Javascript}/object-manipulation/clone-object-shallowly.md (100%) rename snippets/{javascript => Javascript}/object-manipulation/compare-two-objects-shallowly.md (100%) rename snippets/{javascript => Javascript}/object-manipulation/convert-object-to-query-string.md (100%) rename snippets/{javascript => Javascript}/object-manipulation/count-properties-in-object.md (100%) rename snippets/{javascript => Javascript}/object-manipulation/filter-object.md (100%) rename snippets/{javascript => Javascript}/object-manipulation/flatten-nested-object.md (100%) rename snippets/{javascript => Javascript}/object-manipulation/freeze-object.md (100%) rename snippets/{javascript => Javascript}/object-manipulation/get-nested-value.md (100%) rename snippets/{javascript => Javascript}/object-manipulation/invert-object-keys-and-values.md (100%) rename snippets/{javascript => Javascript}/object-manipulation/merge-objects-deeply.md (100%) rename snippets/{javascript => Javascript}/object-manipulation/omit-keys-from-object.md (100%) rename snippets/{javascript => Javascript}/object-manipulation/pick-keys-from-object.md (100%) rename snippets/{javascript => Javascript}/object-manipulation/unique-by-key.md (100%) rename snippets/{javascript => Javascript}/regular-expression/regex-match-utility-function.md (100%) rename snippets/{javascript => Javascript}/string-manipulation/capitalize-string.md (100%) rename snippets/{javascript => Javascript}/string-manipulation/check-if-string-is-a-palindrome.md (100%) rename snippets/{javascript => Javascript}/string-manipulation/convert-string-to-camel-case.md (100%) rename snippets/{javascript => Javascript}/string-manipulation/convert-string-to-param-case.md (100%) rename snippets/{javascript => Javascript}/string-manipulation/convert-string-to-pascal-case.md (100%) rename snippets/{javascript => Javascript}/string-manipulation/convert-string-to-snake-case.md (100%) rename snippets/{javascript => Javascript}/string-manipulation/convert-string-to-title-case.md (100%) rename snippets/{javascript => Javascript}/string-manipulation/convert-tabs-to-spaces.md (100%) rename snippets/{javascript => Javascript}/string-manipulation/count-words-in-a-string.md (100%) rename snippets/{javascript => Javascript}/string-manipulation/data-with-prefix.md (100%) rename snippets/{javascript => Javascript}/string-manipulation/extract-initials-from-name.md (100%) rename snippets/{javascript => Javascript}/string-manipulation/mask-sensitive-information.md (100%) rename snippets/{javascript => Javascript}/string-manipulation/pad-string-on-both-sides.md (100%) rename snippets/{javascript => Javascript}/string-manipulation/random-string.md (100%) rename snippets/{javascript => Javascript}/string-manipulation/remove-all-whitespace.md (100%) rename snippets/{javascript => Javascript}/string-manipulation/remove-vowels-from-a-string.md (100%) rename snippets/{javascript => Javascript}/string-manipulation/reverse-string.md (100%) rename snippets/{javascript => Javascript}/string-manipulation/slugify-string.md (100%) rename snippets/{javascript => Javascript}/string-manipulation/truncate-text.md (100%) rename snippets/{python => Python}/basics/hello-world.md (100%) rename snippets/{python => Python}/datetime-utilities/calculate-date-difference-in-milliseconds.md (100%) rename snippets/{python => Python}/datetime-utilities/check-if-date-is-a-weekend.md (100%) rename snippets/{python => Python}/datetime-utilities/determine-day-of-the-week.md (100%) rename snippets/{python => Python}/datetime-utilities/generate-date-range-list.md (100%) rename snippets/{python => Python}/datetime-utilities/get-current-date-and-time-string.md (100%) rename snippets/{python => Python}/datetime-utilities/get-number-of-days-in-a-month.md (100%) rename snippets/{python => Python}/error-handling/handle-file-not-found-error.md (100%) rename snippets/{python => Python}/error-handling/retry-function-execution-on-exception.md (100%) rename snippets/{python => Python}/error-handling/safe-division.md (100%) rename snippets/{python => Python}/error-handling/validate-input-with-exception-handling.md (100%) rename snippets/{python => Python}/file-handling/append-to-file.md (100%) rename snippets/{python => Python}/file-handling/check-if-file-exists.md (100%) rename snippets/{python => Python}/file-handling/copy-file.md (100%) rename snippets/{python => Python}/file-handling/delete-file.md (100%) rename snippets/{python => Python}/file-handling/find-files.md (100%) rename snippets/{python => Python}/file-handling/get-file-extension.md (100%) rename snippets/{python => Python}/file-handling/list-files-in-directory.md (100%) rename snippets/{python => Python}/file-handling/read-file-in-chunks.md (100%) rename snippets/{python => Python}/file-handling/read-file-lines.md (100%) rename snippets/{python => Python}/file-handling/write-to-file.md (100%) rename snippets/{python => Python}/icon.svg (100%) rename snippets/{python => Python}/json-manipulation/filter-json-data.md (100%) rename snippets/{python => Python}/json-manipulation/flatten-nested-json.md (100%) rename snippets/{python => Python}/json-manipulation/merge-multiple-json-files.md (100%) rename snippets/{python => Python}/json-manipulation/read-json-file.md (100%) rename snippets/{python => Python}/json-manipulation/update-json-file.md (100%) rename snippets/{python => Python}/json-manipulation/validate-json-schema.md (100%) rename snippets/{python => Python}/json-manipulation/write-json-file.md (100%) rename snippets/{python => Python}/list-manipulation/find-duplicates-in-a-list.md (100%) rename snippets/{python => Python}/list-manipulation/find-intersection-of-two-lists.md (100%) rename snippets/{python => Python}/list-manipulation/find-maximum-difference-in-list.md (100%) rename snippets/{python => Python}/list-manipulation/flatten-nested-list.md (100%) rename snippets/{python => Python}/list-manipulation/flatten-unevenly-nested-lists.md (100%) rename snippets/{python => Python}/list-manipulation/partition-list.md (100%) rename snippets/{python => Python}/list-manipulation/remove-duplicates.md (100%) rename snippets/{python => Python}/math-and-numbers/calculate-compound-interest.md (100%) rename snippets/{python => Python}/math-and-numbers/check-perfect-square.md (100%) rename snippets/{python => Python}/math-and-numbers/check-prime-number.md (100%) rename snippets/{python => Python}/math-and-numbers/convert-binary-to-decimal.md (100%) rename snippets/{python => Python}/math-and-numbers/find-factorial.md (100%) rename snippets/{python => Python}/math-and-numbers/find-lcm-least-common-multiple.md (100%) rename snippets/{python => Python}/math-and-numbers/solve-quadratic-equation.md (100%) rename snippets/{python => Python}/sqlite-database/create-sqlite-database-table.md (100%) rename snippets/{python => Python}/sqlite-database/insert-data-into-sqlite-table.md (100%) rename snippets/{python => Python}/string-manipulation/capitalize-words.md (100%) rename snippets/{python => Python}/string-manipulation/check-anagram.md (100%) rename snippets/{python => Python}/string-manipulation/check-palindrome.md (100%) rename snippets/{python => Python}/string-manipulation/convert-snake-case-to-camel-case.md (100%) rename snippets/{python => Python}/string-manipulation/convert-string-to-ascii.md (100%) rename snippets/{python => Python}/string-manipulation/count-character-frequency.md (100%) rename snippets/{python => Python}/string-manipulation/count-vowels.md (100%) rename snippets/{python => Python}/string-manipulation/count-words.md (100%) rename snippets/{python => Python}/string-manipulation/find-all-substrings.md (100%) rename snippets/{python => Python}/string-manipulation/find-longest-word.md (100%) rename snippets/{python => Python}/string-manipulation/find-unique-characters.md (100%) rename snippets/{python => Python}/string-manipulation/remove-duplicate-characters.md (100%) rename snippets/{python => Python}/string-manipulation/remove-punctuation.md (100%) rename snippets/{python => Python}/string-manipulation/remove-specific-characters.md (100%) rename snippets/{python => Python}/string-manipulation/remove-whitespace.md (100%) rename snippets/{python => Python}/string-manipulation/reverse-string.md (100%) rename snippets/{python => Python}/string-manipulation/split-camel-case.md (100%) rename snippets/{python => Python}/string-manipulation/truncate-string.md (100%) rename snippets/{python => Python}/utilities/convert-bytes-to-human-readable-format.md (100%) rename snippets/{python => Python}/utilities/generate-random-string.md (100%) rename snippets/{python => Python}/utilities/measure-execution-time.md (100%) rename snippets/{rust => Rust}/basics/hello-world.md (100%) rename snippets/{rust => Rust}/file-handling/find-files.md (100%) rename snippets/{rust => Rust}/file-handling/read-file-lines.md (100%) rename snippets/{rust => Rust}/icon.svg (100%) rename snippets/{rust => Rust}/string-manipulation/capitalize-string.md (100%) rename snippets/{scss => SCSS}/animations/fade-in-animation.md (100%) rename snippets/{scss => SCSS}/animations/slide-in-from-left.md (100%) rename snippets/{scss => SCSS}/borders-shadows/border-radius-helper.md (100%) rename snippets/{scss => SCSS}/borders-shadows/box-shadow-helper.md (100%) rename snippets/{scss => SCSS}/components/primary-button.md (100%) rename snippets/{scss => SCSS}/icon.svg (100%) rename snippets/{scss => SCSS}/layouts/aspect-ratio.md (100%) rename snippets/{scss => SCSS}/layouts/flex-center.md (100%) rename snippets/{scss => SCSS}/layouts/grid-container.md (100%) rename snippets/{scss => SCSS}/typography/font-import-helper.md (100%) rename snippets/{scss => SCSS}/typography/line-clamp-mixin.md (100%) rename snippets/{scss => SCSS}/typography/text-gradient.md (100%) rename snippets/{scss => SCSS}/typography/text-overflow-ellipsis.md (100%) rename snippets/{scss => SCSS}/utilities/clearfix.md (100%) rename snippets/{scss => SCSS}/utilities/responsive-breakpoints.md (100%) diff --git a/public/data/_index.json b/public/data/_index.json index 941d99f0..00e794bb 100644 --- a/public/data/_index.json +++ b/public/data/_index.json @@ -4,15 +4,15 @@ "icon": "/icons/c.svg" }, { - "lang": "Cpp", + "lang": "CPP", "icon": "/icons/cpp.svg" }, { - "lang": "Css", + "lang": "CSS", "icon": "/icons/css.svg" }, { - "lang": "Html", + "lang": "HTML", "icon": "/icons/html.svg" }, { @@ -28,7 +28,7 @@ "icon": "/icons/rust.svg" }, { - "lang": "Scss", + "lang": "SCSS", "icon": "/icons/scss.svg" } ] \ No newline at end of file diff --git a/snippets/c/basics/hello-world.md b/snippets/C/basics/hello-world.md similarity index 100% rename from snippets/c/basics/hello-world.md rename to snippets/C/basics/hello-world.md diff --git a/snippets/c/icon.svg b/snippets/C/icon.svg similarity index 100% rename from snippets/c/icon.svg rename to snippets/C/icon.svg diff --git a/snippets/c/mathematical-functions/factorial-function.md b/snippets/C/mathematical-functions/factorial-function.md similarity index 100% rename from snippets/c/mathematical-functions/factorial-function.md rename to snippets/C/mathematical-functions/factorial-function.md diff --git a/snippets/c/mathematical-functions/power-function.md b/snippets/C/mathematical-functions/power-function.md similarity index 100% rename from snippets/c/mathematical-functions/power-function.md rename to snippets/C/mathematical-functions/power-function.md diff --git a/snippets/cpp/basics/hello-world.md b/snippets/CPP/basics/hello-world.md similarity index 100% rename from snippets/cpp/basics/hello-world.md rename to snippets/CPP/basics/hello-world.md diff --git a/snippets/cpp/icon.svg b/snippets/CPP/icon.svg similarity index 100% rename from snippets/cpp/icon.svg rename to snippets/CPP/icon.svg diff --git a/snippets/cpp/string-manipulation/reverse-string.md b/snippets/CPP/string-manipulation/reverse-string.md similarity index 100% rename from snippets/cpp/string-manipulation/reverse-string.md rename to snippets/CPP/string-manipulation/reverse-string.md diff --git a/snippets/cpp/string-manipulation/split-string.md b/snippets/CPP/string-manipulation/split-string.md similarity index 100% rename from snippets/cpp/string-manipulation/split-string.md rename to snippets/CPP/string-manipulation/split-string.md diff --git a/snippets/css/buttons/3d-button-effect.md b/snippets/CSS/buttons/3d-button-effect.md similarity index 100% rename from snippets/css/buttons/3d-button-effect.md rename to snippets/CSS/buttons/3d-button-effect.md diff --git a/snippets/css/buttons/button-hover-effect.md b/snippets/CSS/buttons/button-hover-effect.md similarity index 100% rename from snippets/css/buttons/button-hover-effect.md rename to snippets/CSS/buttons/button-hover-effect.md diff --git a/snippets/css/buttons/macos-button.md b/snippets/CSS/buttons/macos-button.md similarity index 100% rename from snippets/css/buttons/macos-button.md rename to snippets/CSS/buttons/macos-button.md diff --git a/snippets/css/effects/blur-background.md b/snippets/CSS/effects/blur-background.md similarity index 100% rename from snippets/css/effects/blur-background.md rename to snippets/CSS/effects/blur-background.md diff --git a/snippets/css/effects/hover-glow-effect.md b/snippets/CSS/effects/hover-glow-effect.md similarity index 100% rename from snippets/css/effects/hover-glow-effect.md rename to snippets/CSS/effects/hover-glow-effect.md diff --git a/snippets/css/icon.svg b/snippets/CSS/icon.svg similarity index 100% rename from snippets/css/icon.svg rename to snippets/CSS/icon.svg diff --git a/snippets/css/layouts/css-reset.md b/snippets/CSS/layouts/css-reset.md similarity index 100% rename from snippets/css/layouts/css-reset.md rename to snippets/CSS/layouts/css-reset.md diff --git a/snippets/css/layouts/equal-width-columns.md b/snippets/CSS/layouts/equal-width-columns.md similarity index 100% rename from snippets/css/layouts/equal-width-columns.md rename to snippets/CSS/layouts/equal-width-columns.md diff --git a/snippets/css/layouts/grid-layout.md b/snippets/CSS/layouts/grid-layout.md similarity index 100% rename from snippets/css/layouts/grid-layout.md rename to snippets/CSS/layouts/grid-layout.md diff --git a/snippets/css/layouts/responsive-design.md b/snippets/CSS/layouts/responsive-design.md similarity index 100% rename from snippets/css/layouts/responsive-design.md rename to snippets/CSS/layouts/responsive-design.md diff --git a/snippets/css/layouts/sticky-footer.md b/snippets/CSS/layouts/sticky-footer.md similarity index 100% rename from snippets/css/layouts/sticky-footer.md rename to snippets/CSS/layouts/sticky-footer.md diff --git a/snippets/css/typography/letter-spacing.md b/snippets/CSS/typography/letter-spacing.md similarity index 100% rename from snippets/css/typography/letter-spacing.md rename to snippets/CSS/typography/letter-spacing.md diff --git a/snippets/css/typography/responsive-font-sizing.md b/snippets/CSS/typography/responsive-font-sizing.md similarity index 100% rename from snippets/css/typography/responsive-font-sizing.md rename to snippets/CSS/typography/responsive-font-sizing.md diff --git a/snippets/html/basic-layouts/grid-layout-with-navigation.md b/snippets/HTML/basic-layouts/grid-layout-with-navigation.md similarity index 100% rename from snippets/html/basic-layouts/grid-layout-with-navigation.md rename to snippets/HTML/basic-layouts/grid-layout-with-navigation.md diff --git a/snippets/html/basic-layouts/sticky-header-footer-layout.md b/snippets/HTML/basic-layouts/sticky-header-footer-layout.md similarity index 100% rename from snippets/html/basic-layouts/sticky-header-footer-layout.md rename to snippets/HTML/basic-layouts/sticky-header-footer-layout.md diff --git a/snippets/html/icon.svg b/snippets/HTML/icon.svg similarity index 100% rename from snippets/html/icon.svg rename to snippets/HTML/icon.svg diff --git a/snippets/javascript/array-manipulation/flatten-array.md b/snippets/Javascript/array-manipulation/flatten-array.md similarity index 100% rename from snippets/javascript/array-manipulation/flatten-array.md rename to snippets/Javascript/array-manipulation/flatten-array.md diff --git a/snippets/javascript/array-manipulation/remove-duplicates.md b/snippets/Javascript/array-manipulation/remove-duplicates.md similarity index 100% rename from snippets/javascript/array-manipulation/remove-duplicates.md rename to snippets/Javascript/array-manipulation/remove-duplicates.md diff --git a/snippets/javascript/array-manipulation/shuffle-array.md b/snippets/Javascript/array-manipulation/shuffle-array.md similarity index 100% rename from snippets/javascript/array-manipulation/shuffle-array.md rename to snippets/Javascript/array-manipulation/shuffle-array.md diff --git a/snippets/javascript/array-manipulation/zip-arrays.md b/snippets/Javascript/array-manipulation/zip-arrays.md similarity index 100% rename from snippets/javascript/array-manipulation/zip-arrays.md rename to snippets/Javascript/array-manipulation/zip-arrays.md diff --git a/snippets/javascript/basics/hello-world.md b/snippets/Javascript/basics/hello-world.md similarity index 100% rename from snippets/javascript/basics/hello-world.md rename to snippets/Javascript/basics/hello-world.md 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 similarity index 100% rename from snippets/javascript/date-and-time/add-days-to-a-date.md rename to snippets/Javascript/date-and-time/add-days-to-a-date.md diff --git a/snippets/javascript/date-and-time/check-leap-year.md b/snippets/Javascript/date-and-time/check-leap-year.md similarity index 100% rename from snippets/javascript/date-and-time/check-leap-year.md rename to snippets/Javascript/date-and-time/check-leap-year.md diff --git a/snippets/javascript/date-and-time/format-date.md b/snippets/Javascript/date-and-time/format-date.md similarity index 100% rename from snippets/javascript/date-and-time/format-date.md rename to snippets/Javascript/date-and-time/format-date.md diff --git a/snippets/javascript/date-and-time/get-current-timestamp.md b/snippets/Javascript/date-and-time/get-current-timestamp.md similarity index 100% rename from snippets/javascript/date-and-time/get-current-timestamp.md rename to snippets/Javascript/date-and-time/get-current-timestamp.md 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 similarity index 100% rename from snippets/javascript/date-and-time/get-day-of-the-year.md rename to snippets/Javascript/date-and-time/get-day-of-the-year.md diff --git a/snippets/javascript/date-and-time/get-days-in-month.md b/snippets/Javascript/date-and-time/get-days-in-month.md similarity index 100% rename from snippets/javascript/date-and-time/get-days-in-month.md rename to snippets/Javascript/date-and-time/get-days-in-month.md diff --git a/snippets/javascript/date-and-time/get-time-difference.md b/snippets/Javascript/date-and-time/get-time-difference.md similarity index 100% rename from snippets/javascript/date-and-time/get-time-difference.md rename to snippets/Javascript/date-and-time/get-time-difference.md diff --git a/snippets/javascript/date-and-time/relative-time-formatter.md b/snippets/Javascript/date-and-time/relative-time-formatter.md similarity index 100% rename from snippets/javascript/date-and-time/relative-time-formatter.md rename to snippets/Javascript/date-and-time/relative-time-formatter.md diff --git a/snippets/javascript/date-and-time/start-of-the-day.md b/snippets/Javascript/date-and-time/start-of-the-day.md similarity index 100% rename from snippets/javascript/date-and-time/start-of-the-day.md rename to snippets/Javascript/date-and-time/start-of-the-day.md diff --git a/snippets/javascript/dom-manipulation/change-element-style.md b/snippets/Javascript/dom-manipulation/change-element-style.md similarity index 100% rename from snippets/javascript/dom-manipulation/change-element-style.md rename to snippets/Javascript/dom-manipulation/change-element-style.md diff --git a/snippets/javascript/dom-manipulation/get-element-position.md b/snippets/Javascript/dom-manipulation/get-element-position.md similarity index 100% rename from snippets/javascript/dom-manipulation/get-element-position.md rename to snippets/Javascript/dom-manipulation/get-element-position.md diff --git a/snippets/javascript/dom-manipulation/remove-element.md b/snippets/Javascript/dom-manipulation/remove-element.md similarity index 100% rename from snippets/javascript/dom-manipulation/remove-element.md rename to snippets/Javascript/dom-manipulation/remove-element.md diff --git a/snippets/javascript/dom-manipulation/smooth-scroll-to-element.md b/snippets/Javascript/dom-manipulation/smooth-scroll-to-element.md similarity index 100% rename from snippets/javascript/dom-manipulation/smooth-scroll-to-element.md rename to snippets/Javascript/dom-manipulation/smooth-scroll-to-element.md diff --git a/snippets/javascript/dom-manipulation/toggle-class.md b/snippets/Javascript/dom-manipulation/toggle-class.md similarity index 100% rename from snippets/javascript/dom-manipulation/toggle-class.md rename to snippets/Javascript/dom-manipulation/toggle-class.md diff --git a/snippets/javascript/function-utilities/compose-functions.md b/snippets/Javascript/function-utilities/compose-functions.md similarity index 100% rename from snippets/javascript/function-utilities/compose-functions.md rename to snippets/Javascript/function-utilities/compose-functions.md diff --git a/snippets/javascript/function-utilities/curry-function.md b/snippets/Javascript/function-utilities/curry-function.md similarity index 100% rename from snippets/javascript/function-utilities/curry-function.md rename to snippets/Javascript/function-utilities/curry-function.md diff --git a/snippets/javascript/function-utilities/debounce-function.md b/snippets/Javascript/function-utilities/debounce-function.md similarity index 100% rename from snippets/javascript/function-utilities/debounce-function.md rename to snippets/Javascript/function-utilities/debounce-function.md diff --git a/snippets/javascript/function-utilities/get-contrast-color.md b/snippets/Javascript/function-utilities/get-contrast-color.md similarity index 100% rename from snippets/javascript/function-utilities/get-contrast-color.md rename to snippets/Javascript/function-utilities/get-contrast-color.md diff --git a/snippets/javascript/function-utilities/memoize-function.md b/snippets/Javascript/function-utilities/memoize-function.md similarity index 100% rename from snippets/javascript/function-utilities/memoize-function.md rename to snippets/Javascript/function-utilities/memoize-function.md diff --git a/snippets/javascript/function-utilities/once-function.md b/snippets/Javascript/function-utilities/once-function.md similarity index 100% rename from snippets/javascript/function-utilities/once-function.md rename to snippets/Javascript/function-utilities/once-function.md diff --git a/snippets/javascript/function-utilities/rate-limit-function.md b/snippets/Javascript/function-utilities/rate-limit-function.md similarity index 100% rename from snippets/javascript/function-utilities/rate-limit-function.md rename to snippets/Javascript/function-utilities/rate-limit-function.md diff --git a/snippets/javascript/function-utilities/repeat-function-invocation.md b/snippets/Javascript/function-utilities/repeat-function-invocation.md similarity index 100% rename from snippets/javascript/function-utilities/repeat-function-invocation.md rename to snippets/Javascript/function-utilities/repeat-function-invocation.md diff --git a/snippets/javascript/function-utilities/sleep-function.md b/snippets/Javascript/function-utilities/sleep-function.md similarity index 100% rename from snippets/javascript/function-utilities/sleep-function.md rename to snippets/Javascript/function-utilities/sleep-function.md diff --git a/snippets/javascript/function-utilities/throttle-function.md b/snippets/Javascript/function-utilities/throttle-function.md similarity index 100% rename from snippets/javascript/function-utilities/throttle-function.md rename to snippets/Javascript/function-utilities/throttle-function.md diff --git a/snippets/javascript/icon.svg b/snippets/Javascript/icon.svg similarity index 100% rename from snippets/javascript/icon.svg rename to snippets/Javascript/icon.svg diff --git a/snippets/javascript/local-storage/add-item-to-localstorage.md b/snippets/Javascript/local-storage/add-item-to-localstorage.md similarity index 100% rename from snippets/javascript/local-storage/add-item-to-localstorage.md rename to snippets/Javascript/local-storage/add-item-to-localstorage.md 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 similarity index 100% rename from snippets/javascript/local-storage/check-if-item-exists-in-localstorage.md rename to snippets/Javascript/local-storage/check-if-item-exists-in-localstorage.md diff --git a/snippets/javascript/local-storage/clear-all-localstorage.md b/snippets/Javascript/local-storage/clear-all-localstorage.md similarity index 100% rename from snippets/javascript/local-storage/clear-all-localstorage.md rename to snippets/Javascript/local-storage/clear-all-localstorage.md diff --git a/snippets/javascript/local-storage/retrieve-item-from-localstorage.md b/snippets/Javascript/local-storage/retrieve-item-from-localstorage.md similarity index 100% rename from snippets/javascript/local-storage/retrieve-item-from-localstorage.md rename to snippets/Javascript/local-storage/retrieve-item-from-localstorage.md diff --git a/snippets/javascript/number-formatting/convert-number-to-currency.md b/snippets/Javascript/number-formatting/convert-number-to-currency.md similarity index 100% rename from snippets/javascript/number-formatting/convert-number-to-currency.md rename to snippets/Javascript/number-formatting/convert-number-to-currency.md diff --git a/snippets/javascript/number-formatting/convert-number-to-roman-numerals.md b/snippets/Javascript/number-formatting/convert-number-to-roman-numerals.md similarity index 100% rename from snippets/javascript/number-formatting/convert-number-to-roman-numerals.md rename to snippets/Javascript/number-formatting/convert-number-to-roman-numerals.md diff --git a/snippets/javascript/number-formatting/convert-to-scientific-notation.md b/snippets/Javascript/number-formatting/convert-to-scientific-notation.md similarity index 100% rename from snippets/javascript/number-formatting/convert-to-scientific-notation.md rename to snippets/Javascript/number-formatting/convert-to-scientific-notation.md diff --git a/snippets/javascript/number-formatting/format-number-with-commas.md b/snippets/Javascript/number-formatting/format-number-with-commas.md similarity index 100% rename from snippets/javascript/number-formatting/format-number-with-commas.md rename to snippets/Javascript/number-formatting/format-number-with-commas.md diff --git a/snippets/javascript/number-formatting/number-formatter.md b/snippets/Javascript/number-formatting/number-formatter.md similarity index 100% rename from snippets/javascript/number-formatting/number-formatter.md rename to snippets/Javascript/number-formatting/number-formatter.md diff --git a/snippets/javascript/number-formatting/number-to-words-converter.md b/snippets/Javascript/number-formatting/number-to-words-converter.md similarity index 100% rename from snippets/javascript/number-formatting/number-to-words-converter.md rename to snippets/Javascript/number-formatting/number-to-words-converter.md diff --git a/snippets/javascript/object-manipulation/check-if-object-is-empty.md b/snippets/Javascript/object-manipulation/check-if-object-is-empty.md similarity index 100% rename from snippets/javascript/object-manipulation/check-if-object-is-empty.md rename to snippets/Javascript/object-manipulation/check-if-object-is-empty.md diff --git a/snippets/javascript/object-manipulation/clone-object-shallowly.md b/snippets/Javascript/object-manipulation/clone-object-shallowly.md similarity index 100% rename from snippets/javascript/object-manipulation/clone-object-shallowly.md rename to snippets/Javascript/object-manipulation/clone-object-shallowly.md diff --git a/snippets/javascript/object-manipulation/compare-two-objects-shallowly.md b/snippets/Javascript/object-manipulation/compare-two-objects-shallowly.md similarity index 100% rename from snippets/javascript/object-manipulation/compare-two-objects-shallowly.md rename to snippets/Javascript/object-manipulation/compare-two-objects-shallowly.md diff --git a/snippets/javascript/object-manipulation/convert-object-to-query-string.md b/snippets/Javascript/object-manipulation/convert-object-to-query-string.md similarity index 100% rename from snippets/javascript/object-manipulation/convert-object-to-query-string.md rename to snippets/Javascript/object-manipulation/convert-object-to-query-string.md diff --git a/snippets/javascript/object-manipulation/count-properties-in-object.md b/snippets/Javascript/object-manipulation/count-properties-in-object.md similarity index 100% rename from snippets/javascript/object-manipulation/count-properties-in-object.md rename to snippets/Javascript/object-manipulation/count-properties-in-object.md diff --git a/snippets/javascript/object-manipulation/filter-object.md b/snippets/Javascript/object-manipulation/filter-object.md similarity index 100% rename from snippets/javascript/object-manipulation/filter-object.md rename to snippets/Javascript/object-manipulation/filter-object.md diff --git a/snippets/javascript/object-manipulation/flatten-nested-object.md b/snippets/Javascript/object-manipulation/flatten-nested-object.md similarity index 100% rename from snippets/javascript/object-manipulation/flatten-nested-object.md rename to snippets/Javascript/object-manipulation/flatten-nested-object.md diff --git a/snippets/javascript/object-manipulation/freeze-object.md b/snippets/Javascript/object-manipulation/freeze-object.md similarity index 100% rename from snippets/javascript/object-manipulation/freeze-object.md rename to snippets/Javascript/object-manipulation/freeze-object.md diff --git a/snippets/javascript/object-manipulation/get-nested-value.md b/snippets/Javascript/object-manipulation/get-nested-value.md similarity index 100% rename from snippets/javascript/object-manipulation/get-nested-value.md rename to snippets/Javascript/object-manipulation/get-nested-value.md diff --git a/snippets/javascript/object-manipulation/invert-object-keys-and-values.md b/snippets/Javascript/object-manipulation/invert-object-keys-and-values.md similarity index 100% rename from snippets/javascript/object-manipulation/invert-object-keys-and-values.md rename to snippets/Javascript/object-manipulation/invert-object-keys-and-values.md diff --git a/snippets/javascript/object-manipulation/merge-objects-deeply.md b/snippets/Javascript/object-manipulation/merge-objects-deeply.md similarity index 100% rename from snippets/javascript/object-manipulation/merge-objects-deeply.md rename to snippets/Javascript/object-manipulation/merge-objects-deeply.md diff --git a/snippets/javascript/object-manipulation/omit-keys-from-object.md b/snippets/Javascript/object-manipulation/omit-keys-from-object.md similarity index 100% rename from snippets/javascript/object-manipulation/omit-keys-from-object.md rename to snippets/Javascript/object-manipulation/omit-keys-from-object.md diff --git a/snippets/javascript/object-manipulation/pick-keys-from-object.md b/snippets/Javascript/object-manipulation/pick-keys-from-object.md similarity index 100% rename from snippets/javascript/object-manipulation/pick-keys-from-object.md rename to snippets/Javascript/object-manipulation/pick-keys-from-object.md diff --git a/snippets/javascript/object-manipulation/unique-by-key.md b/snippets/Javascript/object-manipulation/unique-by-key.md similarity index 100% rename from snippets/javascript/object-manipulation/unique-by-key.md rename to snippets/Javascript/object-manipulation/unique-by-key.md diff --git a/snippets/javascript/regular-expression/regex-match-utility-function.md b/snippets/Javascript/regular-expression/regex-match-utility-function.md similarity index 100% rename from snippets/javascript/regular-expression/regex-match-utility-function.md rename to snippets/Javascript/regular-expression/regex-match-utility-function.md diff --git a/snippets/javascript/string-manipulation/capitalize-string.md b/snippets/Javascript/string-manipulation/capitalize-string.md similarity index 100% rename from snippets/javascript/string-manipulation/capitalize-string.md rename to snippets/Javascript/string-manipulation/capitalize-string.md 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 similarity index 100% rename from snippets/javascript/string-manipulation/check-if-string-is-a-palindrome.md rename to snippets/Javascript/string-manipulation/check-if-string-is-a-palindrome.md diff --git a/snippets/javascript/string-manipulation/convert-string-to-camel-case.md b/snippets/Javascript/string-manipulation/convert-string-to-camel-case.md similarity index 100% rename from snippets/javascript/string-manipulation/convert-string-to-camel-case.md rename to snippets/Javascript/string-manipulation/convert-string-to-camel-case.md diff --git a/snippets/javascript/string-manipulation/convert-string-to-param-case.md b/snippets/Javascript/string-manipulation/convert-string-to-param-case.md similarity index 100% rename from snippets/javascript/string-manipulation/convert-string-to-param-case.md rename to snippets/Javascript/string-manipulation/convert-string-to-param-case.md diff --git a/snippets/javascript/string-manipulation/convert-string-to-pascal-case.md b/snippets/Javascript/string-manipulation/convert-string-to-pascal-case.md similarity index 100% rename from snippets/javascript/string-manipulation/convert-string-to-pascal-case.md rename to snippets/Javascript/string-manipulation/convert-string-to-pascal-case.md diff --git a/snippets/javascript/string-manipulation/convert-string-to-snake-case.md b/snippets/Javascript/string-manipulation/convert-string-to-snake-case.md similarity index 100% rename from snippets/javascript/string-manipulation/convert-string-to-snake-case.md rename to snippets/Javascript/string-manipulation/convert-string-to-snake-case.md diff --git a/snippets/javascript/string-manipulation/convert-string-to-title-case.md b/snippets/Javascript/string-manipulation/convert-string-to-title-case.md similarity index 100% rename from snippets/javascript/string-manipulation/convert-string-to-title-case.md rename to snippets/Javascript/string-manipulation/convert-string-to-title-case.md diff --git a/snippets/javascript/string-manipulation/convert-tabs-to-spaces.md b/snippets/Javascript/string-manipulation/convert-tabs-to-spaces.md similarity index 100% rename from snippets/javascript/string-manipulation/convert-tabs-to-spaces.md rename to snippets/Javascript/string-manipulation/convert-tabs-to-spaces.md diff --git a/snippets/javascript/string-manipulation/count-words-in-a-string.md b/snippets/Javascript/string-manipulation/count-words-in-a-string.md similarity index 100% rename from snippets/javascript/string-manipulation/count-words-in-a-string.md rename to snippets/Javascript/string-manipulation/count-words-in-a-string.md diff --git a/snippets/javascript/string-manipulation/data-with-prefix.md b/snippets/Javascript/string-manipulation/data-with-prefix.md similarity index 100% rename from snippets/javascript/string-manipulation/data-with-prefix.md rename to snippets/Javascript/string-manipulation/data-with-prefix.md diff --git a/snippets/javascript/string-manipulation/extract-initials-from-name.md b/snippets/Javascript/string-manipulation/extract-initials-from-name.md similarity index 100% rename from snippets/javascript/string-manipulation/extract-initials-from-name.md rename to snippets/Javascript/string-manipulation/extract-initials-from-name.md diff --git a/snippets/javascript/string-manipulation/mask-sensitive-information.md b/snippets/Javascript/string-manipulation/mask-sensitive-information.md similarity index 100% rename from snippets/javascript/string-manipulation/mask-sensitive-information.md rename to snippets/Javascript/string-manipulation/mask-sensitive-information.md diff --git a/snippets/javascript/string-manipulation/pad-string-on-both-sides.md b/snippets/Javascript/string-manipulation/pad-string-on-both-sides.md similarity index 100% rename from snippets/javascript/string-manipulation/pad-string-on-both-sides.md rename to snippets/Javascript/string-manipulation/pad-string-on-both-sides.md diff --git a/snippets/javascript/string-manipulation/random-string.md b/snippets/Javascript/string-manipulation/random-string.md similarity index 100% rename from snippets/javascript/string-manipulation/random-string.md rename to snippets/Javascript/string-manipulation/random-string.md diff --git a/snippets/javascript/string-manipulation/remove-all-whitespace.md b/snippets/Javascript/string-manipulation/remove-all-whitespace.md similarity index 100% rename from snippets/javascript/string-manipulation/remove-all-whitespace.md rename to snippets/Javascript/string-manipulation/remove-all-whitespace.md diff --git a/snippets/javascript/string-manipulation/remove-vowels-from-a-string.md b/snippets/Javascript/string-manipulation/remove-vowels-from-a-string.md similarity index 100% rename from snippets/javascript/string-manipulation/remove-vowels-from-a-string.md rename to snippets/Javascript/string-manipulation/remove-vowels-from-a-string.md diff --git a/snippets/javascript/string-manipulation/reverse-string.md b/snippets/Javascript/string-manipulation/reverse-string.md similarity index 100% rename from snippets/javascript/string-manipulation/reverse-string.md rename to snippets/Javascript/string-manipulation/reverse-string.md diff --git a/snippets/javascript/string-manipulation/slugify-string.md b/snippets/Javascript/string-manipulation/slugify-string.md similarity index 100% rename from snippets/javascript/string-manipulation/slugify-string.md rename to snippets/Javascript/string-manipulation/slugify-string.md diff --git a/snippets/javascript/string-manipulation/truncate-text.md b/snippets/Javascript/string-manipulation/truncate-text.md similarity index 100% rename from snippets/javascript/string-manipulation/truncate-text.md rename to snippets/Javascript/string-manipulation/truncate-text.md diff --git a/snippets/python/basics/hello-world.md b/snippets/Python/basics/hello-world.md similarity index 100% rename from snippets/python/basics/hello-world.md rename to snippets/Python/basics/hello-world.md diff --git a/snippets/python/datetime-utilities/calculate-date-difference-in-milliseconds.md b/snippets/Python/datetime-utilities/calculate-date-difference-in-milliseconds.md similarity index 100% rename from snippets/python/datetime-utilities/calculate-date-difference-in-milliseconds.md rename to snippets/Python/datetime-utilities/calculate-date-difference-in-milliseconds.md 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 similarity index 100% rename from snippets/python/datetime-utilities/check-if-date-is-a-weekend.md rename to snippets/Python/datetime-utilities/check-if-date-is-a-weekend.md diff --git a/snippets/python/datetime-utilities/determine-day-of-the-week.md b/snippets/Python/datetime-utilities/determine-day-of-the-week.md similarity index 100% rename from snippets/python/datetime-utilities/determine-day-of-the-week.md rename to snippets/Python/datetime-utilities/determine-day-of-the-week.md diff --git a/snippets/python/datetime-utilities/generate-date-range-list.md b/snippets/Python/datetime-utilities/generate-date-range-list.md similarity index 100% rename from snippets/python/datetime-utilities/generate-date-range-list.md rename to snippets/Python/datetime-utilities/generate-date-range-list.md diff --git a/snippets/python/datetime-utilities/get-current-date-and-time-string.md b/snippets/Python/datetime-utilities/get-current-date-and-time-string.md similarity index 100% rename from snippets/python/datetime-utilities/get-current-date-and-time-string.md rename to snippets/Python/datetime-utilities/get-current-date-and-time-string.md 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 similarity index 100% rename from snippets/python/datetime-utilities/get-number-of-days-in-a-month.md rename to snippets/Python/datetime-utilities/get-number-of-days-in-a-month.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 similarity index 100% rename from snippets/python/error-handling/handle-file-not-found-error.md rename to snippets/Python/error-handling/handle-file-not-found-error.md diff --git a/snippets/python/error-handling/retry-function-execution-on-exception.md b/snippets/Python/error-handling/retry-function-execution-on-exception.md similarity index 100% rename from snippets/python/error-handling/retry-function-execution-on-exception.md rename to snippets/Python/error-handling/retry-function-execution-on-exception.md diff --git a/snippets/python/error-handling/safe-division.md b/snippets/Python/error-handling/safe-division.md similarity index 100% rename from snippets/python/error-handling/safe-division.md rename to snippets/Python/error-handling/safe-division.md diff --git a/snippets/python/error-handling/validate-input-with-exception-handling.md b/snippets/Python/error-handling/validate-input-with-exception-handling.md similarity index 100% rename from snippets/python/error-handling/validate-input-with-exception-handling.md rename to snippets/Python/error-handling/validate-input-with-exception-handling.md diff --git a/snippets/python/file-handling/append-to-file.md b/snippets/Python/file-handling/append-to-file.md similarity index 100% rename from snippets/python/file-handling/append-to-file.md rename to snippets/Python/file-handling/append-to-file.md diff --git a/snippets/python/file-handling/check-if-file-exists.md b/snippets/Python/file-handling/check-if-file-exists.md similarity index 100% rename from snippets/python/file-handling/check-if-file-exists.md rename to snippets/Python/file-handling/check-if-file-exists.md diff --git a/snippets/python/file-handling/copy-file.md b/snippets/Python/file-handling/copy-file.md similarity index 100% rename from snippets/python/file-handling/copy-file.md rename to snippets/Python/file-handling/copy-file.md diff --git a/snippets/python/file-handling/delete-file.md b/snippets/Python/file-handling/delete-file.md similarity index 100% rename from snippets/python/file-handling/delete-file.md rename to snippets/Python/file-handling/delete-file.md diff --git a/snippets/python/file-handling/find-files.md b/snippets/Python/file-handling/find-files.md similarity index 100% rename from snippets/python/file-handling/find-files.md rename to snippets/Python/file-handling/find-files.md diff --git a/snippets/python/file-handling/get-file-extension.md b/snippets/Python/file-handling/get-file-extension.md similarity index 100% rename from snippets/python/file-handling/get-file-extension.md rename to snippets/Python/file-handling/get-file-extension.md diff --git a/snippets/python/file-handling/list-files-in-directory.md b/snippets/Python/file-handling/list-files-in-directory.md similarity index 100% rename from snippets/python/file-handling/list-files-in-directory.md rename to snippets/Python/file-handling/list-files-in-directory.md diff --git a/snippets/python/file-handling/read-file-in-chunks.md b/snippets/Python/file-handling/read-file-in-chunks.md similarity index 100% rename from snippets/python/file-handling/read-file-in-chunks.md rename to snippets/Python/file-handling/read-file-in-chunks.md diff --git a/snippets/python/file-handling/read-file-lines.md b/snippets/Python/file-handling/read-file-lines.md similarity index 100% rename from snippets/python/file-handling/read-file-lines.md rename to snippets/Python/file-handling/read-file-lines.md diff --git a/snippets/python/file-handling/write-to-file.md b/snippets/Python/file-handling/write-to-file.md similarity index 100% rename from snippets/python/file-handling/write-to-file.md rename to snippets/Python/file-handling/write-to-file.md diff --git a/snippets/python/icon.svg b/snippets/Python/icon.svg similarity index 100% rename from snippets/python/icon.svg rename to snippets/Python/icon.svg diff --git a/snippets/python/json-manipulation/filter-json-data.md b/snippets/Python/json-manipulation/filter-json-data.md similarity index 100% rename from snippets/python/json-manipulation/filter-json-data.md rename to snippets/Python/json-manipulation/filter-json-data.md diff --git a/snippets/python/json-manipulation/flatten-nested-json.md b/snippets/Python/json-manipulation/flatten-nested-json.md similarity index 100% rename from snippets/python/json-manipulation/flatten-nested-json.md rename to snippets/Python/json-manipulation/flatten-nested-json.md diff --git a/snippets/python/json-manipulation/merge-multiple-json-files.md b/snippets/Python/json-manipulation/merge-multiple-json-files.md similarity index 100% rename from snippets/python/json-manipulation/merge-multiple-json-files.md rename to snippets/Python/json-manipulation/merge-multiple-json-files.md diff --git a/snippets/python/json-manipulation/read-json-file.md b/snippets/Python/json-manipulation/read-json-file.md similarity index 100% rename from snippets/python/json-manipulation/read-json-file.md rename to snippets/Python/json-manipulation/read-json-file.md diff --git a/snippets/python/json-manipulation/update-json-file.md b/snippets/Python/json-manipulation/update-json-file.md similarity index 100% rename from snippets/python/json-manipulation/update-json-file.md rename to snippets/Python/json-manipulation/update-json-file.md diff --git a/snippets/python/json-manipulation/validate-json-schema.md b/snippets/Python/json-manipulation/validate-json-schema.md similarity index 100% rename from snippets/python/json-manipulation/validate-json-schema.md rename to snippets/Python/json-manipulation/validate-json-schema.md diff --git a/snippets/python/json-manipulation/write-json-file.md b/snippets/Python/json-manipulation/write-json-file.md similarity index 100% rename from snippets/python/json-manipulation/write-json-file.md rename to snippets/Python/json-manipulation/write-json-file.md diff --git a/snippets/python/list-manipulation/find-duplicates-in-a-list.md b/snippets/Python/list-manipulation/find-duplicates-in-a-list.md similarity index 100% rename from snippets/python/list-manipulation/find-duplicates-in-a-list.md rename to snippets/Python/list-manipulation/find-duplicates-in-a-list.md diff --git a/snippets/python/list-manipulation/find-intersection-of-two-lists.md b/snippets/Python/list-manipulation/find-intersection-of-two-lists.md similarity index 100% rename from snippets/python/list-manipulation/find-intersection-of-two-lists.md rename to snippets/Python/list-manipulation/find-intersection-of-two-lists.md diff --git a/snippets/python/list-manipulation/find-maximum-difference-in-list.md b/snippets/Python/list-manipulation/find-maximum-difference-in-list.md similarity index 100% rename from snippets/python/list-manipulation/find-maximum-difference-in-list.md rename to snippets/Python/list-manipulation/find-maximum-difference-in-list.md diff --git a/snippets/python/list-manipulation/flatten-nested-list.md b/snippets/Python/list-manipulation/flatten-nested-list.md similarity index 100% rename from snippets/python/list-manipulation/flatten-nested-list.md rename to snippets/Python/list-manipulation/flatten-nested-list.md diff --git a/snippets/python/list-manipulation/flatten-unevenly-nested-lists.md b/snippets/Python/list-manipulation/flatten-unevenly-nested-lists.md similarity index 100% rename from snippets/python/list-manipulation/flatten-unevenly-nested-lists.md rename to snippets/Python/list-manipulation/flatten-unevenly-nested-lists.md diff --git a/snippets/python/list-manipulation/partition-list.md b/snippets/Python/list-manipulation/partition-list.md similarity index 100% rename from snippets/python/list-manipulation/partition-list.md rename to snippets/Python/list-manipulation/partition-list.md diff --git a/snippets/python/list-manipulation/remove-duplicates.md b/snippets/Python/list-manipulation/remove-duplicates.md similarity index 100% rename from snippets/python/list-manipulation/remove-duplicates.md rename to snippets/Python/list-manipulation/remove-duplicates.md diff --git a/snippets/python/math-and-numbers/calculate-compound-interest.md b/snippets/Python/math-and-numbers/calculate-compound-interest.md similarity index 100% rename from snippets/python/math-and-numbers/calculate-compound-interest.md rename to snippets/Python/math-and-numbers/calculate-compound-interest.md diff --git a/snippets/python/math-and-numbers/check-perfect-square.md b/snippets/Python/math-and-numbers/check-perfect-square.md similarity index 100% rename from snippets/python/math-and-numbers/check-perfect-square.md rename to snippets/Python/math-and-numbers/check-perfect-square.md diff --git a/snippets/python/math-and-numbers/check-prime-number.md b/snippets/Python/math-and-numbers/check-prime-number.md similarity index 100% rename from snippets/python/math-and-numbers/check-prime-number.md rename to snippets/Python/math-and-numbers/check-prime-number.md diff --git a/snippets/python/math-and-numbers/convert-binary-to-decimal.md b/snippets/Python/math-and-numbers/convert-binary-to-decimal.md similarity index 100% rename from snippets/python/math-and-numbers/convert-binary-to-decimal.md rename to snippets/Python/math-and-numbers/convert-binary-to-decimal.md diff --git a/snippets/python/math-and-numbers/find-factorial.md b/snippets/Python/math-and-numbers/find-factorial.md similarity index 100% rename from snippets/python/math-and-numbers/find-factorial.md rename to snippets/Python/math-and-numbers/find-factorial.md 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 similarity index 100% rename from snippets/python/math-and-numbers/find-lcm-least-common-multiple.md rename to snippets/Python/math-and-numbers/find-lcm-least-common-multiple.md diff --git a/snippets/python/math-and-numbers/solve-quadratic-equation.md b/snippets/Python/math-and-numbers/solve-quadratic-equation.md similarity index 100% rename from snippets/python/math-and-numbers/solve-quadratic-equation.md rename to snippets/Python/math-and-numbers/solve-quadratic-equation.md diff --git a/snippets/python/sqlite-database/create-sqlite-database-table.md b/snippets/Python/sqlite-database/create-sqlite-database-table.md similarity index 100% rename from snippets/python/sqlite-database/create-sqlite-database-table.md rename to snippets/Python/sqlite-database/create-sqlite-database-table.md diff --git a/snippets/python/sqlite-database/insert-data-into-sqlite-table.md b/snippets/Python/sqlite-database/insert-data-into-sqlite-table.md similarity index 100% rename from snippets/python/sqlite-database/insert-data-into-sqlite-table.md rename to snippets/Python/sqlite-database/insert-data-into-sqlite-table.md diff --git a/snippets/python/string-manipulation/capitalize-words.md b/snippets/Python/string-manipulation/capitalize-words.md similarity index 100% rename from snippets/python/string-manipulation/capitalize-words.md rename to snippets/Python/string-manipulation/capitalize-words.md diff --git a/snippets/python/string-manipulation/check-anagram.md b/snippets/Python/string-manipulation/check-anagram.md similarity index 100% rename from snippets/python/string-manipulation/check-anagram.md rename to snippets/Python/string-manipulation/check-anagram.md diff --git a/snippets/python/string-manipulation/check-palindrome.md b/snippets/Python/string-manipulation/check-palindrome.md similarity index 100% rename from snippets/python/string-manipulation/check-palindrome.md rename to snippets/Python/string-manipulation/check-palindrome.md 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 similarity index 100% rename from snippets/python/string-manipulation/convert-snake-case-to-camel-case.md rename to snippets/Python/string-manipulation/convert-snake-case-to-camel-case.md diff --git a/snippets/python/string-manipulation/convert-string-to-ascii.md b/snippets/Python/string-manipulation/convert-string-to-ascii.md similarity index 100% rename from snippets/python/string-manipulation/convert-string-to-ascii.md rename to snippets/Python/string-manipulation/convert-string-to-ascii.md diff --git a/snippets/python/string-manipulation/count-character-frequency.md b/snippets/Python/string-manipulation/count-character-frequency.md similarity index 100% rename from snippets/python/string-manipulation/count-character-frequency.md rename to snippets/Python/string-manipulation/count-character-frequency.md diff --git a/snippets/python/string-manipulation/count-vowels.md b/snippets/Python/string-manipulation/count-vowels.md similarity index 100% rename from snippets/python/string-manipulation/count-vowels.md rename to snippets/Python/string-manipulation/count-vowels.md diff --git a/snippets/python/string-manipulation/count-words.md b/snippets/Python/string-manipulation/count-words.md similarity index 100% rename from snippets/python/string-manipulation/count-words.md rename to snippets/Python/string-manipulation/count-words.md diff --git a/snippets/python/string-manipulation/find-all-substrings.md b/snippets/Python/string-manipulation/find-all-substrings.md similarity index 100% rename from snippets/python/string-manipulation/find-all-substrings.md rename to snippets/Python/string-manipulation/find-all-substrings.md diff --git a/snippets/python/string-manipulation/find-longest-word.md b/snippets/Python/string-manipulation/find-longest-word.md similarity index 100% rename from snippets/python/string-manipulation/find-longest-word.md rename to snippets/Python/string-manipulation/find-longest-word.md diff --git a/snippets/python/string-manipulation/find-unique-characters.md b/snippets/Python/string-manipulation/find-unique-characters.md similarity index 100% rename from snippets/python/string-manipulation/find-unique-characters.md rename to snippets/Python/string-manipulation/find-unique-characters.md diff --git a/snippets/python/string-manipulation/remove-duplicate-characters.md b/snippets/Python/string-manipulation/remove-duplicate-characters.md similarity index 100% rename from snippets/python/string-manipulation/remove-duplicate-characters.md rename to snippets/Python/string-manipulation/remove-duplicate-characters.md diff --git a/snippets/python/string-manipulation/remove-punctuation.md b/snippets/Python/string-manipulation/remove-punctuation.md similarity index 100% rename from snippets/python/string-manipulation/remove-punctuation.md rename to snippets/Python/string-manipulation/remove-punctuation.md diff --git a/snippets/python/string-manipulation/remove-specific-characters.md b/snippets/Python/string-manipulation/remove-specific-characters.md similarity index 100% rename from snippets/python/string-manipulation/remove-specific-characters.md rename to snippets/Python/string-manipulation/remove-specific-characters.md diff --git a/snippets/python/string-manipulation/remove-whitespace.md b/snippets/Python/string-manipulation/remove-whitespace.md similarity index 100% rename from snippets/python/string-manipulation/remove-whitespace.md rename to snippets/Python/string-manipulation/remove-whitespace.md diff --git a/snippets/python/string-manipulation/reverse-string.md b/snippets/Python/string-manipulation/reverse-string.md similarity index 100% rename from snippets/python/string-manipulation/reverse-string.md rename to snippets/Python/string-manipulation/reverse-string.md diff --git a/snippets/python/string-manipulation/split-camel-case.md b/snippets/Python/string-manipulation/split-camel-case.md similarity index 100% rename from snippets/python/string-manipulation/split-camel-case.md rename to snippets/Python/string-manipulation/split-camel-case.md diff --git a/snippets/python/string-manipulation/truncate-string.md b/snippets/Python/string-manipulation/truncate-string.md similarity index 100% rename from snippets/python/string-manipulation/truncate-string.md rename to snippets/Python/string-manipulation/truncate-string.md diff --git a/snippets/python/utilities/convert-bytes-to-human-readable-format.md b/snippets/Python/utilities/convert-bytes-to-human-readable-format.md similarity index 100% rename from snippets/python/utilities/convert-bytes-to-human-readable-format.md rename to snippets/Python/utilities/convert-bytes-to-human-readable-format.md diff --git a/snippets/python/utilities/generate-random-string.md b/snippets/Python/utilities/generate-random-string.md similarity index 100% rename from snippets/python/utilities/generate-random-string.md rename to snippets/Python/utilities/generate-random-string.md diff --git a/snippets/python/utilities/measure-execution-time.md b/snippets/Python/utilities/measure-execution-time.md similarity index 100% rename from snippets/python/utilities/measure-execution-time.md rename to snippets/Python/utilities/measure-execution-time.md diff --git a/snippets/rust/basics/hello-world.md b/snippets/Rust/basics/hello-world.md similarity index 100% rename from snippets/rust/basics/hello-world.md rename to snippets/Rust/basics/hello-world.md diff --git a/snippets/rust/file-handling/find-files.md b/snippets/Rust/file-handling/find-files.md similarity index 100% rename from snippets/rust/file-handling/find-files.md rename to snippets/Rust/file-handling/find-files.md diff --git a/snippets/rust/file-handling/read-file-lines.md b/snippets/Rust/file-handling/read-file-lines.md similarity index 100% rename from snippets/rust/file-handling/read-file-lines.md rename to snippets/Rust/file-handling/read-file-lines.md diff --git a/snippets/rust/icon.svg b/snippets/Rust/icon.svg similarity index 100% rename from snippets/rust/icon.svg rename to snippets/Rust/icon.svg diff --git a/snippets/rust/string-manipulation/capitalize-string.md b/snippets/Rust/string-manipulation/capitalize-string.md similarity index 100% rename from snippets/rust/string-manipulation/capitalize-string.md rename to snippets/Rust/string-manipulation/capitalize-string.md diff --git a/snippets/scss/animations/fade-in-animation.md b/snippets/SCSS/animations/fade-in-animation.md similarity index 100% rename from snippets/scss/animations/fade-in-animation.md rename to snippets/SCSS/animations/fade-in-animation.md diff --git a/snippets/scss/animations/slide-in-from-left.md b/snippets/SCSS/animations/slide-in-from-left.md similarity index 100% rename from snippets/scss/animations/slide-in-from-left.md rename to snippets/SCSS/animations/slide-in-from-left.md diff --git a/snippets/scss/borders-shadows/border-radius-helper.md b/snippets/SCSS/borders-shadows/border-radius-helper.md similarity index 100% rename from snippets/scss/borders-shadows/border-radius-helper.md rename to snippets/SCSS/borders-shadows/border-radius-helper.md diff --git a/snippets/scss/borders-shadows/box-shadow-helper.md b/snippets/SCSS/borders-shadows/box-shadow-helper.md similarity index 100% rename from snippets/scss/borders-shadows/box-shadow-helper.md rename to snippets/SCSS/borders-shadows/box-shadow-helper.md diff --git a/snippets/scss/components/primary-button.md b/snippets/SCSS/components/primary-button.md similarity index 100% rename from snippets/scss/components/primary-button.md rename to snippets/SCSS/components/primary-button.md diff --git a/snippets/scss/icon.svg b/snippets/SCSS/icon.svg similarity index 100% rename from snippets/scss/icon.svg rename to snippets/SCSS/icon.svg diff --git a/snippets/scss/layouts/aspect-ratio.md b/snippets/SCSS/layouts/aspect-ratio.md similarity index 100% rename from snippets/scss/layouts/aspect-ratio.md rename to snippets/SCSS/layouts/aspect-ratio.md diff --git a/snippets/scss/layouts/flex-center.md b/snippets/SCSS/layouts/flex-center.md similarity index 100% rename from snippets/scss/layouts/flex-center.md rename to snippets/SCSS/layouts/flex-center.md diff --git a/snippets/scss/layouts/grid-container.md b/snippets/SCSS/layouts/grid-container.md similarity index 100% rename from snippets/scss/layouts/grid-container.md rename to snippets/SCSS/layouts/grid-container.md diff --git a/snippets/scss/typography/font-import-helper.md b/snippets/SCSS/typography/font-import-helper.md similarity index 100% rename from snippets/scss/typography/font-import-helper.md rename to snippets/SCSS/typography/font-import-helper.md diff --git a/snippets/scss/typography/line-clamp-mixin.md b/snippets/SCSS/typography/line-clamp-mixin.md similarity index 100% rename from snippets/scss/typography/line-clamp-mixin.md rename to snippets/SCSS/typography/line-clamp-mixin.md diff --git a/snippets/scss/typography/text-gradient.md b/snippets/SCSS/typography/text-gradient.md similarity index 100% rename from snippets/scss/typography/text-gradient.md rename to snippets/SCSS/typography/text-gradient.md diff --git a/snippets/scss/typography/text-overflow-ellipsis.md b/snippets/SCSS/typography/text-overflow-ellipsis.md similarity index 100% rename from snippets/scss/typography/text-overflow-ellipsis.md rename to snippets/SCSS/typography/text-overflow-ellipsis.md diff --git a/snippets/scss/utilities/clearfix.md b/snippets/SCSS/utilities/clearfix.md similarity index 100% rename from snippets/scss/utilities/clearfix.md rename to snippets/SCSS/utilities/clearfix.md diff --git a/snippets/scss/utilities/responsive-breakpoints.md b/snippets/SCSS/utilities/responsive-breakpoints.md similarity index 100% rename from snippets/scss/utilities/responsive-breakpoints.md rename to snippets/SCSS/utilities/responsive-breakpoints.md diff --git a/utils/consolidateSnippets.js b/utils/consolidateSnippets.js index a55cf203..b3d50965 100644 --- a/utils/consolidateSnippets.js +++ b/utils/consolidateSnippets.js @@ -1,5 +1,5 @@ import { exit } from 'process'; -import { parseAllSnippets, reverseSlugify } from './snippetParser.js'; +import { parseAllSnippets, slugify } from './snippetParser.js'; import { join } from 'path'; import { copyFileSync, writeFileSync } from 'fs'; @@ -14,13 +14,14 @@ if(errored) exit(1); const index = []; for(const [language, categories] of Object.entries(snippets)) { + const languageSlugName = slugify(language); const languageIconPath = join(snippetsPath, language, 'icon.svg'); - copyFileSync(languageIconPath, join(iconPath, `${language}.svg`)); + copyFileSync(languageIconPath, join(iconPath, `${languageSlugName}.svg`)); - index.push({ lang: reverseSlugify(language), icon: `/icons/${language}.svg` }); + index.push({ lang: language, icon: `/icons/${languageSlugName}.svg` }); - const languageFilePath = join(dataPath, `${language}.json`); + const languageFilePath = join(dataPath, `${languageSlugName}.json`); writeFileSync(languageFilePath, JSON.stringify(categories, null, 4)); } diff --git a/utils/snippetParser.js b/utils/snippetParser.js index 0b704537..e9d4b395 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 = '') { From e322059235e5a3cd1355246755993394ba20f4ff Mon Sep 17 00:00:00 2001 From: Mathys-Gasnier Date: Wed, 1 Jan 2025 13:39:04 +0100 Subject: [PATCH 06/10] Revert "Making the language folder name, the name of the language instead of the slug name of the language" This reverts commit 63eaf1909a5cda96ff93ed05e3367edea1100339. --- public/data/_index.json | 8 ++++---- snippets/{C => c}/basics/hello-world.md | 0 snippets/{C => c}/icon.svg | 0 .../mathematical-functions/factorial-function.md | 0 .../{C => c}/mathematical-functions/power-function.md | 0 snippets/{CPP => cpp}/basics/hello-world.md | 0 snippets/{CPP => cpp}/icon.svg | 0 .../string-manipulation/reverse-string.md | 0 .../{CPP => cpp}/string-manipulation/split-string.md | 0 snippets/{CSS => css}/buttons/3d-button-effect.md | 0 snippets/{CSS => css}/buttons/button-hover-effect.md | 0 snippets/{CSS => css}/buttons/macos-button.md | 0 snippets/{CSS => css}/effects/blur-background.md | 0 snippets/{CSS => css}/effects/hover-glow-effect.md | 0 snippets/{CSS => css}/icon.svg | 0 snippets/{CSS => css}/layouts/css-reset.md | 0 snippets/{CSS => css}/layouts/equal-width-columns.md | 0 snippets/{CSS => css}/layouts/grid-layout.md | 0 snippets/{CSS => css}/layouts/responsive-design.md | 0 snippets/{CSS => css}/layouts/sticky-footer.md | 0 snippets/{CSS => css}/typography/letter-spacing.md | 0 .../{CSS => css}/typography/responsive-font-sizing.md | 0 .../basic-layouts/grid-layout-with-navigation.md | 0 .../basic-layouts/sticky-header-footer-layout.md | 0 snippets/{HTML => html}/icon.svg | 0 .../array-manipulation/flatten-array.md | 0 .../array-manipulation/remove-duplicates.md | 0 .../array-manipulation/shuffle-array.md | 0 .../array-manipulation/zip-arrays.md | 0 .../{Javascript => javascript}/basics/hello-world.md | 0 .../date-and-time/add-days-to-a-date.md | 0 .../date-and-time/check-leap-year.md | 0 .../date-and-time/format-date.md | 0 .../date-and-time/get-current-timestamp.md | 0 .../date-and-time/get-day-of-the-year.md | 0 .../date-and-time/get-days-in-month.md | 0 .../date-and-time/get-time-difference.md | 0 .../date-and-time/relative-time-formatter.md | 0 .../date-and-time/start-of-the-day.md | 0 .../dom-manipulation/change-element-style.md | 0 .../dom-manipulation/get-element-position.md | 0 .../dom-manipulation/remove-element.md | 0 .../dom-manipulation/smooth-scroll-to-element.md | 0 .../dom-manipulation/toggle-class.md | 0 .../function-utilities/compose-functions.md | 0 .../function-utilities/curry-function.md | 0 .../function-utilities/debounce-function.md | 0 .../function-utilities/get-contrast-color.md | 0 .../function-utilities/memoize-function.md | 0 .../function-utilities/once-function.md | 0 .../function-utilities/rate-limit-function.md | 0 .../function-utilities/repeat-function-invocation.md | 0 .../function-utilities/sleep-function.md | 0 .../function-utilities/throttle-function.md | 0 snippets/{Javascript => javascript}/icon.svg | 0 .../local-storage/add-item-to-localstorage.md | 0 .../check-if-item-exists-in-localstorage.md | 0 .../local-storage/clear-all-localstorage.md | 0 .../local-storage/retrieve-item-from-localstorage.md | 0 .../number-formatting/convert-number-to-currency.md | 0 .../convert-number-to-roman-numerals.md | 0 .../convert-to-scientific-notation.md | 0 .../number-formatting/format-number-with-commas.md | 0 .../number-formatting/number-formatter.md | 0 .../number-formatting/number-to-words-converter.md | 0 .../object-manipulation/check-if-object-is-empty.md | 0 .../object-manipulation/clone-object-shallowly.md | 0 .../compare-two-objects-shallowly.md | 0 .../convert-object-to-query-string.md | 0 .../object-manipulation/count-properties-in-object.md | 0 .../object-manipulation/filter-object.md | 0 .../object-manipulation/flatten-nested-object.md | 0 .../object-manipulation/freeze-object.md | 0 .../object-manipulation/get-nested-value.md | 0 .../invert-object-keys-and-values.md | 0 .../object-manipulation/merge-objects-deeply.md | 0 .../object-manipulation/omit-keys-from-object.md | 0 .../object-manipulation/pick-keys-from-object.md | 0 .../object-manipulation/unique-by-key.md | 0 .../regex-match-utility-function.md | 0 .../string-manipulation/capitalize-string.md | 0 .../check-if-string-is-a-palindrome.md | 0 .../convert-string-to-camel-case.md | 0 .../convert-string-to-param-case.md | 0 .../convert-string-to-pascal-case.md | 0 .../convert-string-to-snake-case.md | 0 .../convert-string-to-title-case.md | 0 .../string-manipulation/convert-tabs-to-spaces.md | 0 .../string-manipulation/count-words-in-a-string.md | 0 .../string-manipulation/data-with-prefix.md | 0 .../string-manipulation/extract-initials-from-name.md | 0 .../string-manipulation/mask-sensitive-information.md | 0 .../string-manipulation/pad-string-on-both-sides.md | 0 .../string-manipulation/random-string.md | 0 .../string-manipulation/remove-all-whitespace.md | 0 .../remove-vowels-from-a-string.md | 0 .../string-manipulation/reverse-string.md | 0 .../string-manipulation/slugify-string.md | 0 .../string-manipulation/truncate-text.md | 0 snippets/{Python => python}/basics/hello-world.md | 0 .../calculate-date-difference-in-milliseconds.md | 0 .../datetime-utilities/check-if-date-is-a-weekend.md | 0 .../datetime-utilities/determine-day-of-the-week.md | 0 .../datetime-utilities/generate-date-range-list.md | 0 .../get-current-date-and-time-string.md | 0 .../get-number-of-days-in-a-month.md | 0 .../error-handling/handle-file-not-found-error.md | 0 .../retry-function-execution-on-exception.md | 0 .../error-handling/safe-division.md | 0 .../validate-input-with-exception-handling.md | 0 .../file-handling/append-to-file.md | 0 .../file-handling/check-if-file-exists.md | 0 .../{Python => python}/file-handling/copy-file.md | 0 .../{Python => python}/file-handling/delete-file.md | 0 .../{Python => python}/file-handling/find-files.md | 0 .../file-handling/get-file-extension.md | 0 .../file-handling/list-files-in-directory.md | 0 .../file-handling/read-file-in-chunks.md | 0 .../file-handling/read-file-lines.md | 0 .../{Python => python}/file-handling/write-to-file.md | 0 snippets/{Python => python}/icon.svg | 0 .../json-manipulation/filter-json-data.md | 0 .../json-manipulation/flatten-nested-json.md | 0 .../json-manipulation/merge-multiple-json-files.md | 0 .../json-manipulation/read-json-file.md | 0 .../json-manipulation/update-json-file.md | 0 .../json-manipulation/validate-json-schema.md | 0 .../json-manipulation/write-json-file.md | 0 .../list-manipulation/find-duplicates-in-a-list.md | 0 .../find-intersection-of-two-lists.md | 0 .../find-maximum-difference-in-list.md | 0 .../list-manipulation/flatten-nested-list.md | 0 .../flatten-unevenly-nested-lists.md | 0 .../list-manipulation/partition-list.md | 0 .../list-manipulation/remove-duplicates.md | 0 .../math-and-numbers/calculate-compound-interest.md | 0 .../math-and-numbers/check-perfect-square.md | 0 .../math-and-numbers/check-prime-number.md | 0 .../math-and-numbers/convert-binary-to-decimal.md | 0 .../math-and-numbers/find-factorial.md | 0 .../find-lcm-least-common-multiple.md | 0 .../math-and-numbers/solve-quadratic-equation.md | 0 .../sqlite-database/create-sqlite-database-table.md | 0 .../sqlite-database/insert-data-into-sqlite-table.md | 0 .../string-manipulation/capitalize-words.md | 0 .../string-manipulation/check-anagram.md | 0 .../string-manipulation/check-palindrome.md | 0 .../convert-snake-case-to-camel-case.md | 0 .../string-manipulation/convert-string-to-ascii.md | 0 .../string-manipulation/count-character-frequency.md | 0 .../string-manipulation/count-vowels.md | 0 .../string-manipulation/count-words.md | 0 .../string-manipulation/find-all-substrings.md | 0 .../string-manipulation/find-longest-word.md | 0 .../string-manipulation/find-unique-characters.md | 0 .../remove-duplicate-characters.md | 0 .../string-manipulation/remove-punctuation.md | 0 .../string-manipulation/remove-specific-characters.md | 0 .../string-manipulation/remove-whitespace.md | 0 .../string-manipulation/reverse-string.md | 0 .../string-manipulation/split-camel-case.md | 0 .../string-manipulation/truncate-string.md | 0 .../convert-bytes-to-human-readable-format.md | 0 .../utilities/generate-random-string.md | 0 .../utilities/measure-execution-time.md | 0 snippets/{Rust => rust}/basics/hello-world.md | 0 snippets/{Rust => rust}/file-handling/find-files.md | 0 .../{Rust => rust}/file-handling/read-file-lines.md | 0 snippets/{Rust => rust}/icon.svg | 0 .../string-manipulation/capitalize-string.md | 0 .../{SCSS => scss}/animations/fade-in-animation.md | 0 .../{SCSS => scss}/animations/slide-in-from-left.md | 0 .../borders-shadows/border-radius-helper.md | 0 .../borders-shadows/box-shadow-helper.md | 0 snippets/{SCSS => scss}/components/primary-button.md | 0 snippets/{SCSS => scss}/icon.svg | 0 snippets/{SCSS => scss}/layouts/aspect-ratio.md | 0 snippets/{SCSS => scss}/layouts/flex-center.md | 0 snippets/{SCSS => scss}/layouts/grid-container.md | 0 .../{SCSS => scss}/typography/font-import-helper.md | 0 .../{SCSS => scss}/typography/line-clamp-mixin.md | 0 snippets/{SCSS => scss}/typography/text-gradient.md | 0 .../typography/text-overflow-ellipsis.md | 0 snippets/{SCSS => scss}/utilities/clearfix.md | 0 .../utilities/responsive-breakpoints.md | 0 utils/consolidateSnippets.js | 9 ++++----- utils/snippetParser.js | 11 ----------- 187 files changed, 8 insertions(+), 20 deletions(-) rename snippets/{C => c}/basics/hello-world.md (100%) rename snippets/{C => c}/icon.svg (100%) rename snippets/{C => c}/mathematical-functions/factorial-function.md (100%) rename snippets/{C => c}/mathematical-functions/power-function.md (100%) rename snippets/{CPP => cpp}/basics/hello-world.md (100%) rename snippets/{CPP => cpp}/icon.svg (100%) rename snippets/{CPP => cpp}/string-manipulation/reverse-string.md (100%) rename snippets/{CPP => cpp}/string-manipulation/split-string.md (100%) rename snippets/{CSS => css}/buttons/3d-button-effect.md (100%) rename snippets/{CSS => css}/buttons/button-hover-effect.md (100%) rename snippets/{CSS => css}/buttons/macos-button.md (100%) rename snippets/{CSS => css}/effects/blur-background.md (100%) rename snippets/{CSS => css}/effects/hover-glow-effect.md (100%) rename snippets/{CSS => css}/icon.svg (100%) rename snippets/{CSS => css}/layouts/css-reset.md (100%) rename snippets/{CSS => css}/layouts/equal-width-columns.md (100%) rename snippets/{CSS => css}/layouts/grid-layout.md (100%) rename snippets/{CSS => css}/layouts/responsive-design.md (100%) rename snippets/{CSS => css}/layouts/sticky-footer.md (100%) rename snippets/{CSS => css}/typography/letter-spacing.md (100%) rename snippets/{CSS => css}/typography/responsive-font-sizing.md (100%) rename snippets/{HTML => html}/basic-layouts/grid-layout-with-navigation.md (100%) rename snippets/{HTML => html}/basic-layouts/sticky-header-footer-layout.md (100%) rename snippets/{HTML => html}/icon.svg (100%) rename snippets/{Javascript => javascript}/array-manipulation/flatten-array.md (100%) rename snippets/{Javascript => javascript}/array-manipulation/remove-duplicates.md (100%) rename snippets/{Javascript => javascript}/array-manipulation/shuffle-array.md (100%) rename snippets/{Javascript => javascript}/array-manipulation/zip-arrays.md (100%) rename snippets/{Javascript => javascript}/basics/hello-world.md (100%) rename snippets/{Javascript => javascript}/date-and-time/add-days-to-a-date.md (100%) rename snippets/{Javascript => javascript}/date-and-time/check-leap-year.md (100%) rename snippets/{Javascript => javascript}/date-and-time/format-date.md (100%) rename snippets/{Javascript => javascript}/date-and-time/get-current-timestamp.md (100%) rename snippets/{Javascript => javascript}/date-and-time/get-day-of-the-year.md (100%) rename snippets/{Javascript => javascript}/date-and-time/get-days-in-month.md (100%) rename snippets/{Javascript => javascript}/date-and-time/get-time-difference.md (100%) rename snippets/{Javascript => javascript}/date-and-time/relative-time-formatter.md (100%) rename snippets/{Javascript => javascript}/date-and-time/start-of-the-day.md (100%) rename snippets/{Javascript => javascript}/dom-manipulation/change-element-style.md (100%) rename snippets/{Javascript => javascript}/dom-manipulation/get-element-position.md (100%) rename snippets/{Javascript => javascript}/dom-manipulation/remove-element.md (100%) rename snippets/{Javascript => javascript}/dom-manipulation/smooth-scroll-to-element.md (100%) rename snippets/{Javascript => javascript}/dom-manipulation/toggle-class.md (100%) rename snippets/{Javascript => javascript}/function-utilities/compose-functions.md (100%) rename snippets/{Javascript => javascript}/function-utilities/curry-function.md (100%) rename snippets/{Javascript => javascript}/function-utilities/debounce-function.md (100%) rename snippets/{Javascript => javascript}/function-utilities/get-contrast-color.md (100%) rename snippets/{Javascript => javascript}/function-utilities/memoize-function.md (100%) rename snippets/{Javascript => javascript}/function-utilities/once-function.md (100%) rename snippets/{Javascript => javascript}/function-utilities/rate-limit-function.md (100%) rename snippets/{Javascript => javascript}/function-utilities/repeat-function-invocation.md (100%) rename snippets/{Javascript => javascript}/function-utilities/sleep-function.md (100%) rename snippets/{Javascript => javascript}/function-utilities/throttle-function.md (100%) rename snippets/{Javascript => javascript}/icon.svg (100%) rename snippets/{Javascript => javascript}/local-storage/add-item-to-localstorage.md (100%) rename snippets/{Javascript => javascript}/local-storage/check-if-item-exists-in-localstorage.md (100%) rename snippets/{Javascript => javascript}/local-storage/clear-all-localstorage.md (100%) rename snippets/{Javascript => javascript}/local-storage/retrieve-item-from-localstorage.md (100%) rename snippets/{Javascript => javascript}/number-formatting/convert-number-to-currency.md (100%) rename snippets/{Javascript => javascript}/number-formatting/convert-number-to-roman-numerals.md (100%) rename snippets/{Javascript => javascript}/number-formatting/convert-to-scientific-notation.md (100%) rename snippets/{Javascript => javascript}/number-formatting/format-number-with-commas.md (100%) rename snippets/{Javascript => javascript}/number-formatting/number-formatter.md (100%) rename snippets/{Javascript => javascript}/number-formatting/number-to-words-converter.md (100%) rename snippets/{Javascript => javascript}/object-manipulation/check-if-object-is-empty.md (100%) rename snippets/{Javascript => javascript}/object-manipulation/clone-object-shallowly.md (100%) rename snippets/{Javascript => javascript}/object-manipulation/compare-two-objects-shallowly.md (100%) rename snippets/{Javascript => javascript}/object-manipulation/convert-object-to-query-string.md (100%) rename snippets/{Javascript => javascript}/object-manipulation/count-properties-in-object.md (100%) rename snippets/{Javascript => javascript}/object-manipulation/filter-object.md (100%) rename snippets/{Javascript => javascript}/object-manipulation/flatten-nested-object.md (100%) rename snippets/{Javascript => javascript}/object-manipulation/freeze-object.md (100%) rename snippets/{Javascript => javascript}/object-manipulation/get-nested-value.md (100%) rename snippets/{Javascript => javascript}/object-manipulation/invert-object-keys-and-values.md (100%) rename snippets/{Javascript => javascript}/object-manipulation/merge-objects-deeply.md (100%) rename snippets/{Javascript => javascript}/object-manipulation/omit-keys-from-object.md (100%) rename snippets/{Javascript => javascript}/object-manipulation/pick-keys-from-object.md (100%) rename snippets/{Javascript => javascript}/object-manipulation/unique-by-key.md (100%) rename snippets/{Javascript => javascript}/regular-expression/regex-match-utility-function.md (100%) rename snippets/{Javascript => javascript}/string-manipulation/capitalize-string.md (100%) rename snippets/{Javascript => javascript}/string-manipulation/check-if-string-is-a-palindrome.md (100%) rename snippets/{Javascript => javascript}/string-manipulation/convert-string-to-camel-case.md (100%) rename snippets/{Javascript => javascript}/string-manipulation/convert-string-to-param-case.md (100%) rename snippets/{Javascript => javascript}/string-manipulation/convert-string-to-pascal-case.md (100%) rename snippets/{Javascript => javascript}/string-manipulation/convert-string-to-snake-case.md (100%) rename snippets/{Javascript => javascript}/string-manipulation/convert-string-to-title-case.md (100%) rename snippets/{Javascript => javascript}/string-manipulation/convert-tabs-to-spaces.md (100%) rename snippets/{Javascript => javascript}/string-manipulation/count-words-in-a-string.md (100%) rename snippets/{Javascript => javascript}/string-manipulation/data-with-prefix.md (100%) rename snippets/{Javascript => javascript}/string-manipulation/extract-initials-from-name.md (100%) rename snippets/{Javascript => javascript}/string-manipulation/mask-sensitive-information.md (100%) rename snippets/{Javascript => javascript}/string-manipulation/pad-string-on-both-sides.md (100%) rename snippets/{Javascript => javascript}/string-manipulation/random-string.md (100%) rename snippets/{Javascript => javascript}/string-manipulation/remove-all-whitespace.md (100%) rename snippets/{Javascript => javascript}/string-manipulation/remove-vowels-from-a-string.md (100%) rename snippets/{Javascript => javascript}/string-manipulation/reverse-string.md (100%) rename snippets/{Javascript => javascript}/string-manipulation/slugify-string.md (100%) rename snippets/{Javascript => javascript}/string-manipulation/truncate-text.md (100%) rename snippets/{Python => python}/basics/hello-world.md (100%) rename snippets/{Python => python}/datetime-utilities/calculate-date-difference-in-milliseconds.md (100%) rename snippets/{Python => python}/datetime-utilities/check-if-date-is-a-weekend.md (100%) rename snippets/{Python => python}/datetime-utilities/determine-day-of-the-week.md (100%) rename snippets/{Python => python}/datetime-utilities/generate-date-range-list.md (100%) rename snippets/{Python => python}/datetime-utilities/get-current-date-and-time-string.md (100%) rename snippets/{Python => python}/datetime-utilities/get-number-of-days-in-a-month.md (100%) rename snippets/{Python => python}/error-handling/handle-file-not-found-error.md (100%) rename snippets/{Python => python}/error-handling/retry-function-execution-on-exception.md (100%) rename snippets/{Python => python}/error-handling/safe-division.md (100%) rename snippets/{Python => python}/error-handling/validate-input-with-exception-handling.md (100%) rename snippets/{Python => python}/file-handling/append-to-file.md (100%) rename snippets/{Python => python}/file-handling/check-if-file-exists.md (100%) rename snippets/{Python => python}/file-handling/copy-file.md (100%) rename snippets/{Python => python}/file-handling/delete-file.md (100%) rename snippets/{Python => python}/file-handling/find-files.md (100%) rename snippets/{Python => python}/file-handling/get-file-extension.md (100%) rename snippets/{Python => python}/file-handling/list-files-in-directory.md (100%) rename snippets/{Python => python}/file-handling/read-file-in-chunks.md (100%) rename snippets/{Python => python}/file-handling/read-file-lines.md (100%) rename snippets/{Python => python}/file-handling/write-to-file.md (100%) rename snippets/{Python => python}/icon.svg (100%) rename snippets/{Python => python}/json-manipulation/filter-json-data.md (100%) rename snippets/{Python => python}/json-manipulation/flatten-nested-json.md (100%) rename snippets/{Python => python}/json-manipulation/merge-multiple-json-files.md (100%) rename snippets/{Python => python}/json-manipulation/read-json-file.md (100%) rename snippets/{Python => python}/json-manipulation/update-json-file.md (100%) rename snippets/{Python => python}/json-manipulation/validate-json-schema.md (100%) rename snippets/{Python => python}/json-manipulation/write-json-file.md (100%) rename snippets/{Python => python}/list-manipulation/find-duplicates-in-a-list.md (100%) rename snippets/{Python => python}/list-manipulation/find-intersection-of-two-lists.md (100%) rename snippets/{Python => python}/list-manipulation/find-maximum-difference-in-list.md (100%) rename snippets/{Python => python}/list-manipulation/flatten-nested-list.md (100%) rename snippets/{Python => python}/list-manipulation/flatten-unevenly-nested-lists.md (100%) rename snippets/{Python => python}/list-manipulation/partition-list.md (100%) rename snippets/{Python => python}/list-manipulation/remove-duplicates.md (100%) rename snippets/{Python => python}/math-and-numbers/calculate-compound-interest.md (100%) rename snippets/{Python => python}/math-and-numbers/check-perfect-square.md (100%) rename snippets/{Python => python}/math-and-numbers/check-prime-number.md (100%) rename snippets/{Python => python}/math-and-numbers/convert-binary-to-decimal.md (100%) rename snippets/{Python => python}/math-and-numbers/find-factorial.md (100%) rename snippets/{Python => python}/math-and-numbers/find-lcm-least-common-multiple.md (100%) rename snippets/{Python => python}/math-and-numbers/solve-quadratic-equation.md (100%) rename snippets/{Python => python}/sqlite-database/create-sqlite-database-table.md (100%) rename snippets/{Python => python}/sqlite-database/insert-data-into-sqlite-table.md (100%) rename snippets/{Python => python}/string-manipulation/capitalize-words.md (100%) rename snippets/{Python => python}/string-manipulation/check-anagram.md (100%) rename snippets/{Python => python}/string-manipulation/check-palindrome.md (100%) rename snippets/{Python => python}/string-manipulation/convert-snake-case-to-camel-case.md (100%) rename snippets/{Python => python}/string-manipulation/convert-string-to-ascii.md (100%) rename snippets/{Python => python}/string-manipulation/count-character-frequency.md (100%) rename snippets/{Python => python}/string-manipulation/count-vowels.md (100%) rename snippets/{Python => python}/string-manipulation/count-words.md (100%) rename snippets/{Python => python}/string-manipulation/find-all-substrings.md (100%) rename snippets/{Python => python}/string-manipulation/find-longest-word.md (100%) rename snippets/{Python => python}/string-manipulation/find-unique-characters.md (100%) rename snippets/{Python => python}/string-manipulation/remove-duplicate-characters.md (100%) rename snippets/{Python => python}/string-manipulation/remove-punctuation.md (100%) rename snippets/{Python => python}/string-manipulation/remove-specific-characters.md (100%) rename snippets/{Python => python}/string-manipulation/remove-whitespace.md (100%) rename snippets/{Python => python}/string-manipulation/reverse-string.md (100%) rename snippets/{Python => python}/string-manipulation/split-camel-case.md (100%) rename snippets/{Python => python}/string-manipulation/truncate-string.md (100%) rename snippets/{Python => python}/utilities/convert-bytes-to-human-readable-format.md (100%) rename snippets/{Python => python}/utilities/generate-random-string.md (100%) rename snippets/{Python => python}/utilities/measure-execution-time.md (100%) rename snippets/{Rust => rust}/basics/hello-world.md (100%) rename snippets/{Rust => rust}/file-handling/find-files.md (100%) rename snippets/{Rust => rust}/file-handling/read-file-lines.md (100%) rename snippets/{Rust => rust}/icon.svg (100%) rename snippets/{Rust => rust}/string-manipulation/capitalize-string.md (100%) rename snippets/{SCSS => scss}/animations/fade-in-animation.md (100%) rename snippets/{SCSS => scss}/animations/slide-in-from-left.md (100%) rename snippets/{SCSS => scss}/borders-shadows/border-radius-helper.md (100%) rename snippets/{SCSS => scss}/borders-shadows/box-shadow-helper.md (100%) rename snippets/{SCSS => scss}/components/primary-button.md (100%) rename snippets/{SCSS => scss}/icon.svg (100%) rename snippets/{SCSS => scss}/layouts/aspect-ratio.md (100%) rename snippets/{SCSS => scss}/layouts/flex-center.md (100%) rename snippets/{SCSS => scss}/layouts/grid-container.md (100%) rename snippets/{SCSS => scss}/typography/font-import-helper.md (100%) rename snippets/{SCSS => scss}/typography/line-clamp-mixin.md (100%) rename snippets/{SCSS => scss}/typography/text-gradient.md (100%) rename snippets/{SCSS => scss}/typography/text-overflow-ellipsis.md (100%) rename snippets/{SCSS => scss}/utilities/clearfix.md (100%) rename snippets/{SCSS => scss}/utilities/responsive-breakpoints.md (100%) diff --git a/public/data/_index.json b/public/data/_index.json index 00e794bb..941d99f0 100644 --- a/public/data/_index.json +++ b/public/data/_index.json @@ -4,15 +4,15 @@ "icon": "/icons/c.svg" }, { - "lang": "CPP", + "lang": "Cpp", "icon": "/icons/cpp.svg" }, { - "lang": "CSS", + "lang": "Css", "icon": "/icons/css.svg" }, { - "lang": "HTML", + "lang": "Html", "icon": "/icons/html.svg" }, { @@ -28,7 +28,7 @@ "icon": "/icons/rust.svg" }, { - "lang": "SCSS", + "lang": "Scss", "icon": "/icons/scss.svg" } ] \ No newline at end of file diff --git a/snippets/C/basics/hello-world.md b/snippets/c/basics/hello-world.md similarity index 100% rename from snippets/C/basics/hello-world.md rename to snippets/c/basics/hello-world.md diff --git a/snippets/C/icon.svg b/snippets/c/icon.svg similarity index 100% rename from snippets/C/icon.svg rename to snippets/c/icon.svg diff --git a/snippets/C/mathematical-functions/factorial-function.md b/snippets/c/mathematical-functions/factorial-function.md similarity index 100% rename from snippets/C/mathematical-functions/factorial-function.md rename to snippets/c/mathematical-functions/factorial-function.md diff --git a/snippets/C/mathematical-functions/power-function.md b/snippets/c/mathematical-functions/power-function.md similarity index 100% rename from snippets/C/mathematical-functions/power-function.md rename to snippets/c/mathematical-functions/power-function.md diff --git a/snippets/CPP/basics/hello-world.md b/snippets/cpp/basics/hello-world.md similarity index 100% rename from snippets/CPP/basics/hello-world.md rename to snippets/cpp/basics/hello-world.md diff --git a/snippets/CPP/icon.svg b/snippets/cpp/icon.svg similarity index 100% rename from snippets/CPP/icon.svg rename to snippets/cpp/icon.svg diff --git a/snippets/CPP/string-manipulation/reverse-string.md b/snippets/cpp/string-manipulation/reverse-string.md similarity index 100% rename from snippets/CPP/string-manipulation/reverse-string.md rename to snippets/cpp/string-manipulation/reverse-string.md diff --git a/snippets/CPP/string-manipulation/split-string.md b/snippets/cpp/string-manipulation/split-string.md similarity index 100% rename from snippets/CPP/string-manipulation/split-string.md rename to snippets/cpp/string-manipulation/split-string.md diff --git a/snippets/CSS/buttons/3d-button-effect.md b/snippets/css/buttons/3d-button-effect.md similarity index 100% rename from snippets/CSS/buttons/3d-button-effect.md rename to snippets/css/buttons/3d-button-effect.md diff --git a/snippets/CSS/buttons/button-hover-effect.md b/snippets/css/buttons/button-hover-effect.md similarity index 100% rename from snippets/CSS/buttons/button-hover-effect.md rename to snippets/css/buttons/button-hover-effect.md diff --git a/snippets/CSS/buttons/macos-button.md b/snippets/css/buttons/macos-button.md similarity index 100% rename from snippets/CSS/buttons/macos-button.md rename to snippets/css/buttons/macos-button.md diff --git a/snippets/CSS/effects/blur-background.md b/snippets/css/effects/blur-background.md similarity index 100% rename from snippets/CSS/effects/blur-background.md rename to snippets/css/effects/blur-background.md diff --git a/snippets/CSS/effects/hover-glow-effect.md b/snippets/css/effects/hover-glow-effect.md similarity index 100% rename from snippets/CSS/effects/hover-glow-effect.md rename to snippets/css/effects/hover-glow-effect.md diff --git a/snippets/CSS/icon.svg b/snippets/css/icon.svg similarity index 100% rename from snippets/CSS/icon.svg rename to snippets/css/icon.svg diff --git a/snippets/CSS/layouts/css-reset.md b/snippets/css/layouts/css-reset.md similarity index 100% rename from snippets/CSS/layouts/css-reset.md rename to snippets/css/layouts/css-reset.md diff --git a/snippets/CSS/layouts/equal-width-columns.md b/snippets/css/layouts/equal-width-columns.md similarity index 100% rename from snippets/CSS/layouts/equal-width-columns.md rename to snippets/css/layouts/equal-width-columns.md diff --git a/snippets/CSS/layouts/grid-layout.md b/snippets/css/layouts/grid-layout.md similarity index 100% rename from snippets/CSS/layouts/grid-layout.md rename to snippets/css/layouts/grid-layout.md diff --git a/snippets/CSS/layouts/responsive-design.md b/snippets/css/layouts/responsive-design.md similarity index 100% rename from snippets/CSS/layouts/responsive-design.md rename to snippets/css/layouts/responsive-design.md diff --git a/snippets/CSS/layouts/sticky-footer.md b/snippets/css/layouts/sticky-footer.md similarity index 100% rename from snippets/CSS/layouts/sticky-footer.md rename to snippets/css/layouts/sticky-footer.md diff --git a/snippets/CSS/typography/letter-spacing.md b/snippets/css/typography/letter-spacing.md similarity index 100% rename from snippets/CSS/typography/letter-spacing.md rename to snippets/css/typography/letter-spacing.md diff --git a/snippets/CSS/typography/responsive-font-sizing.md b/snippets/css/typography/responsive-font-sizing.md similarity index 100% rename from snippets/CSS/typography/responsive-font-sizing.md rename to snippets/css/typography/responsive-font-sizing.md diff --git a/snippets/HTML/basic-layouts/grid-layout-with-navigation.md b/snippets/html/basic-layouts/grid-layout-with-navigation.md similarity index 100% rename from snippets/HTML/basic-layouts/grid-layout-with-navigation.md rename to snippets/html/basic-layouts/grid-layout-with-navigation.md diff --git a/snippets/HTML/basic-layouts/sticky-header-footer-layout.md b/snippets/html/basic-layouts/sticky-header-footer-layout.md similarity index 100% rename from snippets/HTML/basic-layouts/sticky-header-footer-layout.md rename to snippets/html/basic-layouts/sticky-header-footer-layout.md diff --git a/snippets/HTML/icon.svg b/snippets/html/icon.svg similarity index 100% rename from snippets/HTML/icon.svg rename to snippets/html/icon.svg diff --git a/snippets/Javascript/array-manipulation/flatten-array.md b/snippets/javascript/array-manipulation/flatten-array.md similarity index 100% rename from snippets/Javascript/array-manipulation/flatten-array.md rename to snippets/javascript/array-manipulation/flatten-array.md diff --git a/snippets/Javascript/array-manipulation/remove-duplicates.md b/snippets/javascript/array-manipulation/remove-duplicates.md similarity index 100% rename from snippets/Javascript/array-manipulation/remove-duplicates.md rename to snippets/javascript/array-manipulation/remove-duplicates.md diff --git a/snippets/Javascript/array-manipulation/shuffle-array.md b/snippets/javascript/array-manipulation/shuffle-array.md similarity index 100% rename from snippets/Javascript/array-manipulation/shuffle-array.md rename to snippets/javascript/array-manipulation/shuffle-array.md diff --git a/snippets/Javascript/array-manipulation/zip-arrays.md b/snippets/javascript/array-manipulation/zip-arrays.md similarity index 100% rename from snippets/Javascript/array-manipulation/zip-arrays.md rename to snippets/javascript/array-manipulation/zip-arrays.md diff --git a/snippets/Javascript/basics/hello-world.md b/snippets/javascript/basics/hello-world.md similarity index 100% rename from snippets/Javascript/basics/hello-world.md rename to snippets/javascript/basics/hello-world.md 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 similarity index 100% rename from snippets/Javascript/date-and-time/add-days-to-a-date.md rename to snippets/javascript/date-and-time/add-days-to-a-date.md diff --git a/snippets/Javascript/date-and-time/check-leap-year.md b/snippets/javascript/date-and-time/check-leap-year.md similarity index 100% rename from snippets/Javascript/date-and-time/check-leap-year.md rename to snippets/javascript/date-and-time/check-leap-year.md diff --git a/snippets/Javascript/date-and-time/format-date.md b/snippets/javascript/date-and-time/format-date.md similarity index 100% rename from snippets/Javascript/date-and-time/format-date.md rename to snippets/javascript/date-and-time/format-date.md diff --git a/snippets/Javascript/date-and-time/get-current-timestamp.md b/snippets/javascript/date-and-time/get-current-timestamp.md similarity index 100% rename from snippets/Javascript/date-and-time/get-current-timestamp.md rename to snippets/javascript/date-and-time/get-current-timestamp.md 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 similarity index 100% rename from snippets/Javascript/date-and-time/get-day-of-the-year.md rename to snippets/javascript/date-and-time/get-day-of-the-year.md diff --git a/snippets/Javascript/date-and-time/get-days-in-month.md b/snippets/javascript/date-and-time/get-days-in-month.md similarity index 100% rename from snippets/Javascript/date-and-time/get-days-in-month.md rename to snippets/javascript/date-and-time/get-days-in-month.md diff --git a/snippets/Javascript/date-and-time/get-time-difference.md b/snippets/javascript/date-and-time/get-time-difference.md similarity index 100% rename from snippets/Javascript/date-and-time/get-time-difference.md rename to snippets/javascript/date-and-time/get-time-difference.md diff --git a/snippets/Javascript/date-and-time/relative-time-formatter.md b/snippets/javascript/date-and-time/relative-time-formatter.md similarity index 100% rename from snippets/Javascript/date-and-time/relative-time-formatter.md rename to snippets/javascript/date-and-time/relative-time-formatter.md diff --git a/snippets/Javascript/date-and-time/start-of-the-day.md b/snippets/javascript/date-and-time/start-of-the-day.md similarity index 100% rename from snippets/Javascript/date-and-time/start-of-the-day.md rename to snippets/javascript/date-and-time/start-of-the-day.md diff --git a/snippets/Javascript/dom-manipulation/change-element-style.md b/snippets/javascript/dom-manipulation/change-element-style.md similarity index 100% rename from snippets/Javascript/dom-manipulation/change-element-style.md rename to snippets/javascript/dom-manipulation/change-element-style.md diff --git a/snippets/Javascript/dom-manipulation/get-element-position.md b/snippets/javascript/dom-manipulation/get-element-position.md similarity index 100% rename from snippets/Javascript/dom-manipulation/get-element-position.md rename to snippets/javascript/dom-manipulation/get-element-position.md diff --git a/snippets/Javascript/dom-manipulation/remove-element.md b/snippets/javascript/dom-manipulation/remove-element.md similarity index 100% rename from snippets/Javascript/dom-manipulation/remove-element.md rename to snippets/javascript/dom-manipulation/remove-element.md diff --git a/snippets/Javascript/dom-manipulation/smooth-scroll-to-element.md b/snippets/javascript/dom-manipulation/smooth-scroll-to-element.md similarity index 100% rename from snippets/Javascript/dom-manipulation/smooth-scroll-to-element.md rename to snippets/javascript/dom-manipulation/smooth-scroll-to-element.md diff --git a/snippets/Javascript/dom-manipulation/toggle-class.md b/snippets/javascript/dom-manipulation/toggle-class.md similarity index 100% rename from snippets/Javascript/dom-manipulation/toggle-class.md rename to snippets/javascript/dom-manipulation/toggle-class.md diff --git a/snippets/Javascript/function-utilities/compose-functions.md b/snippets/javascript/function-utilities/compose-functions.md similarity index 100% rename from snippets/Javascript/function-utilities/compose-functions.md rename to snippets/javascript/function-utilities/compose-functions.md diff --git a/snippets/Javascript/function-utilities/curry-function.md b/snippets/javascript/function-utilities/curry-function.md similarity index 100% rename from snippets/Javascript/function-utilities/curry-function.md rename to snippets/javascript/function-utilities/curry-function.md diff --git a/snippets/Javascript/function-utilities/debounce-function.md b/snippets/javascript/function-utilities/debounce-function.md similarity index 100% rename from snippets/Javascript/function-utilities/debounce-function.md rename to snippets/javascript/function-utilities/debounce-function.md diff --git a/snippets/Javascript/function-utilities/get-contrast-color.md b/snippets/javascript/function-utilities/get-contrast-color.md similarity index 100% rename from snippets/Javascript/function-utilities/get-contrast-color.md rename to snippets/javascript/function-utilities/get-contrast-color.md diff --git a/snippets/Javascript/function-utilities/memoize-function.md b/snippets/javascript/function-utilities/memoize-function.md similarity index 100% rename from snippets/Javascript/function-utilities/memoize-function.md rename to snippets/javascript/function-utilities/memoize-function.md diff --git a/snippets/Javascript/function-utilities/once-function.md b/snippets/javascript/function-utilities/once-function.md similarity index 100% rename from snippets/Javascript/function-utilities/once-function.md rename to snippets/javascript/function-utilities/once-function.md diff --git a/snippets/Javascript/function-utilities/rate-limit-function.md b/snippets/javascript/function-utilities/rate-limit-function.md similarity index 100% rename from snippets/Javascript/function-utilities/rate-limit-function.md rename to snippets/javascript/function-utilities/rate-limit-function.md diff --git a/snippets/Javascript/function-utilities/repeat-function-invocation.md b/snippets/javascript/function-utilities/repeat-function-invocation.md similarity index 100% rename from snippets/Javascript/function-utilities/repeat-function-invocation.md rename to snippets/javascript/function-utilities/repeat-function-invocation.md diff --git a/snippets/Javascript/function-utilities/sleep-function.md b/snippets/javascript/function-utilities/sleep-function.md similarity index 100% rename from snippets/Javascript/function-utilities/sleep-function.md rename to snippets/javascript/function-utilities/sleep-function.md diff --git a/snippets/Javascript/function-utilities/throttle-function.md b/snippets/javascript/function-utilities/throttle-function.md similarity index 100% rename from snippets/Javascript/function-utilities/throttle-function.md rename to snippets/javascript/function-utilities/throttle-function.md diff --git a/snippets/Javascript/icon.svg b/snippets/javascript/icon.svg similarity index 100% rename from snippets/Javascript/icon.svg rename to snippets/javascript/icon.svg diff --git a/snippets/Javascript/local-storage/add-item-to-localstorage.md b/snippets/javascript/local-storage/add-item-to-localstorage.md similarity index 100% rename from snippets/Javascript/local-storage/add-item-to-localstorage.md rename to snippets/javascript/local-storage/add-item-to-localstorage.md 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 similarity index 100% rename from snippets/Javascript/local-storage/check-if-item-exists-in-localstorage.md rename to snippets/javascript/local-storage/check-if-item-exists-in-localstorage.md diff --git a/snippets/Javascript/local-storage/clear-all-localstorage.md b/snippets/javascript/local-storage/clear-all-localstorage.md similarity index 100% rename from snippets/Javascript/local-storage/clear-all-localstorage.md rename to snippets/javascript/local-storage/clear-all-localstorage.md diff --git a/snippets/Javascript/local-storage/retrieve-item-from-localstorage.md b/snippets/javascript/local-storage/retrieve-item-from-localstorage.md similarity index 100% rename from snippets/Javascript/local-storage/retrieve-item-from-localstorage.md rename to snippets/javascript/local-storage/retrieve-item-from-localstorage.md diff --git a/snippets/Javascript/number-formatting/convert-number-to-currency.md b/snippets/javascript/number-formatting/convert-number-to-currency.md similarity index 100% rename from snippets/Javascript/number-formatting/convert-number-to-currency.md rename to snippets/javascript/number-formatting/convert-number-to-currency.md diff --git a/snippets/Javascript/number-formatting/convert-number-to-roman-numerals.md b/snippets/javascript/number-formatting/convert-number-to-roman-numerals.md similarity index 100% rename from snippets/Javascript/number-formatting/convert-number-to-roman-numerals.md rename to snippets/javascript/number-formatting/convert-number-to-roman-numerals.md diff --git a/snippets/Javascript/number-formatting/convert-to-scientific-notation.md b/snippets/javascript/number-formatting/convert-to-scientific-notation.md similarity index 100% rename from snippets/Javascript/number-formatting/convert-to-scientific-notation.md rename to snippets/javascript/number-formatting/convert-to-scientific-notation.md diff --git a/snippets/Javascript/number-formatting/format-number-with-commas.md b/snippets/javascript/number-formatting/format-number-with-commas.md similarity index 100% rename from snippets/Javascript/number-formatting/format-number-with-commas.md rename to snippets/javascript/number-formatting/format-number-with-commas.md diff --git a/snippets/Javascript/number-formatting/number-formatter.md b/snippets/javascript/number-formatting/number-formatter.md similarity index 100% rename from snippets/Javascript/number-formatting/number-formatter.md rename to snippets/javascript/number-formatting/number-formatter.md diff --git a/snippets/Javascript/number-formatting/number-to-words-converter.md b/snippets/javascript/number-formatting/number-to-words-converter.md similarity index 100% rename from snippets/Javascript/number-formatting/number-to-words-converter.md rename to snippets/javascript/number-formatting/number-to-words-converter.md diff --git a/snippets/Javascript/object-manipulation/check-if-object-is-empty.md b/snippets/javascript/object-manipulation/check-if-object-is-empty.md similarity index 100% rename from snippets/Javascript/object-manipulation/check-if-object-is-empty.md rename to snippets/javascript/object-manipulation/check-if-object-is-empty.md diff --git a/snippets/Javascript/object-manipulation/clone-object-shallowly.md b/snippets/javascript/object-manipulation/clone-object-shallowly.md similarity index 100% rename from snippets/Javascript/object-manipulation/clone-object-shallowly.md rename to snippets/javascript/object-manipulation/clone-object-shallowly.md diff --git a/snippets/Javascript/object-manipulation/compare-two-objects-shallowly.md b/snippets/javascript/object-manipulation/compare-two-objects-shallowly.md similarity index 100% rename from snippets/Javascript/object-manipulation/compare-two-objects-shallowly.md rename to snippets/javascript/object-manipulation/compare-two-objects-shallowly.md diff --git a/snippets/Javascript/object-manipulation/convert-object-to-query-string.md b/snippets/javascript/object-manipulation/convert-object-to-query-string.md similarity index 100% rename from snippets/Javascript/object-manipulation/convert-object-to-query-string.md rename to snippets/javascript/object-manipulation/convert-object-to-query-string.md diff --git a/snippets/Javascript/object-manipulation/count-properties-in-object.md b/snippets/javascript/object-manipulation/count-properties-in-object.md similarity index 100% rename from snippets/Javascript/object-manipulation/count-properties-in-object.md rename to snippets/javascript/object-manipulation/count-properties-in-object.md diff --git a/snippets/Javascript/object-manipulation/filter-object.md b/snippets/javascript/object-manipulation/filter-object.md similarity index 100% rename from snippets/Javascript/object-manipulation/filter-object.md rename to snippets/javascript/object-manipulation/filter-object.md diff --git a/snippets/Javascript/object-manipulation/flatten-nested-object.md b/snippets/javascript/object-manipulation/flatten-nested-object.md similarity index 100% rename from snippets/Javascript/object-manipulation/flatten-nested-object.md rename to snippets/javascript/object-manipulation/flatten-nested-object.md diff --git a/snippets/Javascript/object-manipulation/freeze-object.md b/snippets/javascript/object-manipulation/freeze-object.md similarity index 100% rename from snippets/Javascript/object-manipulation/freeze-object.md rename to snippets/javascript/object-manipulation/freeze-object.md diff --git a/snippets/Javascript/object-manipulation/get-nested-value.md b/snippets/javascript/object-manipulation/get-nested-value.md similarity index 100% rename from snippets/Javascript/object-manipulation/get-nested-value.md rename to snippets/javascript/object-manipulation/get-nested-value.md diff --git a/snippets/Javascript/object-manipulation/invert-object-keys-and-values.md b/snippets/javascript/object-manipulation/invert-object-keys-and-values.md similarity index 100% rename from snippets/Javascript/object-manipulation/invert-object-keys-and-values.md rename to snippets/javascript/object-manipulation/invert-object-keys-and-values.md diff --git a/snippets/Javascript/object-manipulation/merge-objects-deeply.md b/snippets/javascript/object-manipulation/merge-objects-deeply.md similarity index 100% rename from snippets/Javascript/object-manipulation/merge-objects-deeply.md rename to snippets/javascript/object-manipulation/merge-objects-deeply.md diff --git a/snippets/Javascript/object-manipulation/omit-keys-from-object.md b/snippets/javascript/object-manipulation/omit-keys-from-object.md similarity index 100% rename from snippets/Javascript/object-manipulation/omit-keys-from-object.md rename to snippets/javascript/object-manipulation/omit-keys-from-object.md diff --git a/snippets/Javascript/object-manipulation/pick-keys-from-object.md b/snippets/javascript/object-manipulation/pick-keys-from-object.md similarity index 100% rename from snippets/Javascript/object-manipulation/pick-keys-from-object.md rename to snippets/javascript/object-manipulation/pick-keys-from-object.md diff --git a/snippets/Javascript/object-manipulation/unique-by-key.md b/snippets/javascript/object-manipulation/unique-by-key.md similarity index 100% rename from snippets/Javascript/object-manipulation/unique-by-key.md rename to snippets/javascript/object-manipulation/unique-by-key.md diff --git a/snippets/Javascript/regular-expression/regex-match-utility-function.md b/snippets/javascript/regular-expression/regex-match-utility-function.md similarity index 100% rename from snippets/Javascript/regular-expression/regex-match-utility-function.md rename to snippets/javascript/regular-expression/regex-match-utility-function.md diff --git a/snippets/Javascript/string-manipulation/capitalize-string.md b/snippets/javascript/string-manipulation/capitalize-string.md similarity index 100% rename from snippets/Javascript/string-manipulation/capitalize-string.md rename to snippets/javascript/string-manipulation/capitalize-string.md 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 similarity index 100% rename from snippets/Javascript/string-manipulation/check-if-string-is-a-palindrome.md rename to snippets/javascript/string-manipulation/check-if-string-is-a-palindrome.md diff --git a/snippets/Javascript/string-manipulation/convert-string-to-camel-case.md b/snippets/javascript/string-manipulation/convert-string-to-camel-case.md similarity index 100% rename from snippets/Javascript/string-manipulation/convert-string-to-camel-case.md rename to snippets/javascript/string-manipulation/convert-string-to-camel-case.md diff --git a/snippets/Javascript/string-manipulation/convert-string-to-param-case.md b/snippets/javascript/string-manipulation/convert-string-to-param-case.md similarity index 100% rename from snippets/Javascript/string-manipulation/convert-string-to-param-case.md rename to snippets/javascript/string-manipulation/convert-string-to-param-case.md diff --git a/snippets/Javascript/string-manipulation/convert-string-to-pascal-case.md b/snippets/javascript/string-manipulation/convert-string-to-pascal-case.md similarity index 100% rename from snippets/Javascript/string-manipulation/convert-string-to-pascal-case.md rename to snippets/javascript/string-manipulation/convert-string-to-pascal-case.md diff --git a/snippets/Javascript/string-manipulation/convert-string-to-snake-case.md b/snippets/javascript/string-manipulation/convert-string-to-snake-case.md similarity index 100% rename from snippets/Javascript/string-manipulation/convert-string-to-snake-case.md rename to snippets/javascript/string-manipulation/convert-string-to-snake-case.md diff --git a/snippets/Javascript/string-manipulation/convert-string-to-title-case.md b/snippets/javascript/string-manipulation/convert-string-to-title-case.md similarity index 100% rename from snippets/Javascript/string-manipulation/convert-string-to-title-case.md rename to snippets/javascript/string-manipulation/convert-string-to-title-case.md diff --git a/snippets/Javascript/string-manipulation/convert-tabs-to-spaces.md b/snippets/javascript/string-manipulation/convert-tabs-to-spaces.md similarity index 100% rename from snippets/Javascript/string-manipulation/convert-tabs-to-spaces.md rename to snippets/javascript/string-manipulation/convert-tabs-to-spaces.md diff --git a/snippets/Javascript/string-manipulation/count-words-in-a-string.md b/snippets/javascript/string-manipulation/count-words-in-a-string.md similarity index 100% rename from snippets/Javascript/string-manipulation/count-words-in-a-string.md rename to snippets/javascript/string-manipulation/count-words-in-a-string.md diff --git a/snippets/Javascript/string-manipulation/data-with-prefix.md b/snippets/javascript/string-manipulation/data-with-prefix.md similarity index 100% rename from snippets/Javascript/string-manipulation/data-with-prefix.md rename to snippets/javascript/string-manipulation/data-with-prefix.md diff --git a/snippets/Javascript/string-manipulation/extract-initials-from-name.md b/snippets/javascript/string-manipulation/extract-initials-from-name.md similarity index 100% rename from snippets/Javascript/string-manipulation/extract-initials-from-name.md rename to snippets/javascript/string-manipulation/extract-initials-from-name.md diff --git a/snippets/Javascript/string-manipulation/mask-sensitive-information.md b/snippets/javascript/string-manipulation/mask-sensitive-information.md similarity index 100% rename from snippets/Javascript/string-manipulation/mask-sensitive-information.md rename to snippets/javascript/string-manipulation/mask-sensitive-information.md diff --git a/snippets/Javascript/string-manipulation/pad-string-on-both-sides.md b/snippets/javascript/string-manipulation/pad-string-on-both-sides.md similarity index 100% rename from snippets/Javascript/string-manipulation/pad-string-on-both-sides.md rename to snippets/javascript/string-manipulation/pad-string-on-both-sides.md diff --git a/snippets/Javascript/string-manipulation/random-string.md b/snippets/javascript/string-manipulation/random-string.md similarity index 100% rename from snippets/Javascript/string-manipulation/random-string.md rename to snippets/javascript/string-manipulation/random-string.md diff --git a/snippets/Javascript/string-manipulation/remove-all-whitespace.md b/snippets/javascript/string-manipulation/remove-all-whitespace.md similarity index 100% rename from snippets/Javascript/string-manipulation/remove-all-whitespace.md rename to snippets/javascript/string-manipulation/remove-all-whitespace.md diff --git a/snippets/Javascript/string-manipulation/remove-vowels-from-a-string.md b/snippets/javascript/string-manipulation/remove-vowels-from-a-string.md similarity index 100% rename from snippets/Javascript/string-manipulation/remove-vowels-from-a-string.md rename to snippets/javascript/string-manipulation/remove-vowels-from-a-string.md diff --git a/snippets/Javascript/string-manipulation/reverse-string.md b/snippets/javascript/string-manipulation/reverse-string.md similarity index 100% rename from snippets/Javascript/string-manipulation/reverse-string.md rename to snippets/javascript/string-manipulation/reverse-string.md diff --git a/snippets/Javascript/string-manipulation/slugify-string.md b/snippets/javascript/string-manipulation/slugify-string.md similarity index 100% rename from snippets/Javascript/string-manipulation/slugify-string.md rename to snippets/javascript/string-manipulation/slugify-string.md diff --git a/snippets/Javascript/string-manipulation/truncate-text.md b/snippets/javascript/string-manipulation/truncate-text.md similarity index 100% rename from snippets/Javascript/string-manipulation/truncate-text.md rename to snippets/javascript/string-manipulation/truncate-text.md diff --git a/snippets/Python/basics/hello-world.md b/snippets/python/basics/hello-world.md similarity index 100% rename from snippets/Python/basics/hello-world.md rename to snippets/python/basics/hello-world.md diff --git a/snippets/Python/datetime-utilities/calculate-date-difference-in-milliseconds.md b/snippets/python/datetime-utilities/calculate-date-difference-in-milliseconds.md similarity index 100% rename from snippets/Python/datetime-utilities/calculate-date-difference-in-milliseconds.md rename to snippets/python/datetime-utilities/calculate-date-difference-in-milliseconds.md 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 similarity index 100% rename from snippets/Python/datetime-utilities/check-if-date-is-a-weekend.md rename to snippets/python/datetime-utilities/check-if-date-is-a-weekend.md diff --git a/snippets/Python/datetime-utilities/determine-day-of-the-week.md b/snippets/python/datetime-utilities/determine-day-of-the-week.md similarity index 100% rename from snippets/Python/datetime-utilities/determine-day-of-the-week.md rename to snippets/python/datetime-utilities/determine-day-of-the-week.md diff --git a/snippets/Python/datetime-utilities/generate-date-range-list.md b/snippets/python/datetime-utilities/generate-date-range-list.md similarity index 100% rename from snippets/Python/datetime-utilities/generate-date-range-list.md rename to snippets/python/datetime-utilities/generate-date-range-list.md diff --git a/snippets/Python/datetime-utilities/get-current-date-and-time-string.md b/snippets/python/datetime-utilities/get-current-date-and-time-string.md similarity index 100% rename from snippets/Python/datetime-utilities/get-current-date-and-time-string.md rename to snippets/python/datetime-utilities/get-current-date-and-time-string.md 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 similarity index 100% rename from snippets/Python/datetime-utilities/get-number-of-days-in-a-month.md rename to snippets/python/datetime-utilities/get-number-of-days-in-a-month.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 similarity index 100% rename from snippets/Python/error-handling/handle-file-not-found-error.md rename to snippets/python/error-handling/handle-file-not-found-error.md diff --git a/snippets/Python/error-handling/retry-function-execution-on-exception.md b/snippets/python/error-handling/retry-function-execution-on-exception.md similarity index 100% rename from snippets/Python/error-handling/retry-function-execution-on-exception.md rename to snippets/python/error-handling/retry-function-execution-on-exception.md diff --git a/snippets/Python/error-handling/safe-division.md b/snippets/python/error-handling/safe-division.md similarity index 100% rename from snippets/Python/error-handling/safe-division.md rename to snippets/python/error-handling/safe-division.md diff --git a/snippets/Python/error-handling/validate-input-with-exception-handling.md b/snippets/python/error-handling/validate-input-with-exception-handling.md similarity index 100% rename from snippets/Python/error-handling/validate-input-with-exception-handling.md rename to snippets/python/error-handling/validate-input-with-exception-handling.md diff --git a/snippets/Python/file-handling/append-to-file.md b/snippets/python/file-handling/append-to-file.md similarity index 100% rename from snippets/Python/file-handling/append-to-file.md rename to snippets/python/file-handling/append-to-file.md diff --git a/snippets/Python/file-handling/check-if-file-exists.md b/snippets/python/file-handling/check-if-file-exists.md similarity index 100% rename from snippets/Python/file-handling/check-if-file-exists.md rename to snippets/python/file-handling/check-if-file-exists.md diff --git a/snippets/Python/file-handling/copy-file.md b/snippets/python/file-handling/copy-file.md similarity index 100% rename from snippets/Python/file-handling/copy-file.md rename to snippets/python/file-handling/copy-file.md diff --git a/snippets/Python/file-handling/delete-file.md b/snippets/python/file-handling/delete-file.md similarity index 100% rename from snippets/Python/file-handling/delete-file.md rename to snippets/python/file-handling/delete-file.md diff --git a/snippets/Python/file-handling/find-files.md b/snippets/python/file-handling/find-files.md similarity index 100% rename from snippets/Python/file-handling/find-files.md rename to snippets/python/file-handling/find-files.md diff --git a/snippets/Python/file-handling/get-file-extension.md b/snippets/python/file-handling/get-file-extension.md similarity index 100% rename from snippets/Python/file-handling/get-file-extension.md rename to snippets/python/file-handling/get-file-extension.md diff --git a/snippets/Python/file-handling/list-files-in-directory.md b/snippets/python/file-handling/list-files-in-directory.md similarity index 100% rename from snippets/Python/file-handling/list-files-in-directory.md rename to snippets/python/file-handling/list-files-in-directory.md diff --git a/snippets/Python/file-handling/read-file-in-chunks.md b/snippets/python/file-handling/read-file-in-chunks.md similarity index 100% rename from snippets/Python/file-handling/read-file-in-chunks.md rename to snippets/python/file-handling/read-file-in-chunks.md diff --git a/snippets/Python/file-handling/read-file-lines.md b/snippets/python/file-handling/read-file-lines.md similarity index 100% rename from snippets/Python/file-handling/read-file-lines.md rename to snippets/python/file-handling/read-file-lines.md diff --git a/snippets/Python/file-handling/write-to-file.md b/snippets/python/file-handling/write-to-file.md similarity index 100% rename from snippets/Python/file-handling/write-to-file.md rename to snippets/python/file-handling/write-to-file.md diff --git a/snippets/Python/icon.svg b/snippets/python/icon.svg similarity index 100% rename from snippets/Python/icon.svg rename to snippets/python/icon.svg diff --git a/snippets/Python/json-manipulation/filter-json-data.md b/snippets/python/json-manipulation/filter-json-data.md similarity index 100% rename from snippets/Python/json-manipulation/filter-json-data.md rename to snippets/python/json-manipulation/filter-json-data.md diff --git a/snippets/Python/json-manipulation/flatten-nested-json.md b/snippets/python/json-manipulation/flatten-nested-json.md similarity index 100% rename from snippets/Python/json-manipulation/flatten-nested-json.md rename to snippets/python/json-manipulation/flatten-nested-json.md diff --git a/snippets/Python/json-manipulation/merge-multiple-json-files.md b/snippets/python/json-manipulation/merge-multiple-json-files.md similarity index 100% rename from snippets/Python/json-manipulation/merge-multiple-json-files.md rename to snippets/python/json-manipulation/merge-multiple-json-files.md diff --git a/snippets/Python/json-manipulation/read-json-file.md b/snippets/python/json-manipulation/read-json-file.md similarity index 100% rename from snippets/Python/json-manipulation/read-json-file.md rename to snippets/python/json-manipulation/read-json-file.md diff --git a/snippets/Python/json-manipulation/update-json-file.md b/snippets/python/json-manipulation/update-json-file.md similarity index 100% rename from snippets/Python/json-manipulation/update-json-file.md rename to snippets/python/json-manipulation/update-json-file.md diff --git a/snippets/Python/json-manipulation/validate-json-schema.md b/snippets/python/json-manipulation/validate-json-schema.md similarity index 100% rename from snippets/Python/json-manipulation/validate-json-schema.md rename to snippets/python/json-manipulation/validate-json-schema.md diff --git a/snippets/Python/json-manipulation/write-json-file.md b/snippets/python/json-manipulation/write-json-file.md similarity index 100% rename from snippets/Python/json-manipulation/write-json-file.md rename to snippets/python/json-manipulation/write-json-file.md diff --git a/snippets/Python/list-manipulation/find-duplicates-in-a-list.md b/snippets/python/list-manipulation/find-duplicates-in-a-list.md similarity index 100% rename from snippets/Python/list-manipulation/find-duplicates-in-a-list.md rename to snippets/python/list-manipulation/find-duplicates-in-a-list.md diff --git a/snippets/Python/list-manipulation/find-intersection-of-two-lists.md b/snippets/python/list-manipulation/find-intersection-of-two-lists.md similarity index 100% rename from snippets/Python/list-manipulation/find-intersection-of-two-lists.md rename to snippets/python/list-manipulation/find-intersection-of-two-lists.md diff --git a/snippets/Python/list-manipulation/find-maximum-difference-in-list.md b/snippets/python/list-manipulation/find-maximum-difference-in-list.md similarity index 100% rename from snippets/Python/list-manipulation/find-maximum-difference-in-list.md rename to snippets/python/list-manipulation/find-maximum-difference-in-list.md diff --git a/snippets/Python/list-manipulation/flatten-nested-list.md b/snippets/python/list-manipulation/flatten-nested-list.md similarity index 100% rename from snippets/Python/list-manipulation/flatten-nested-list.md rename to snippets/python/list-manipulation/flatten-nested-list.md diff --git a/snippets/Python/list-manipulation/flatten-unevenly-nested-lists.md b/snippets/python/list-manipulation/flatten-unevenly-nested-lists.md similarity index 100% rename from snippets/Python/list-manipulation/flatten-unevenly-nested-lists.md rename to snippets/python/list-manipulation/flatten-unevenly-nested-lists.md diff --git a/snippets/Python/list-manipulation/partition-list.md b/snippets/python/list-manipulation/partition-list.md similarity index 100% rename from snippets/Python/list-manipulation/partition-list.md rename to snippets/python/list-manipulation/partition-list.md diff --git a/snippets/Python/list-manipulation/remove-duplicates.md b/snippets/python/list-manipulation/remove-duplicates.md similarity index 100% rename from snippets/Python/list-manipulation/remove-duplicates.md rename to snippets/python/list-manipulation/remove-duplicates.md diff --git a/snippets/Python/math-and-numbers/calculate-compound-interest.md b/snippets/python/math-and-numbers/calculate-compound-interest.md similarity index 100% rename from snippets/Python/math-and-numbers/calculate-compound-interest.md rename to snippets/python/math-and-numbers/calculate-compound-interest.md diff --git a/snippets/Python/math-and-numbers/check-perfect-square.md b/snippets/python/math-and-numbers/check-perfect-square.md similarity index 100% rename from snippets/Python/math-and-numbers/check-perfect-square.md rename to snippets/python/math-and-numbers/check-perfect-square.md diff --git a/snippets/Python/math-and-numbers/check-prime-number.md b/snippets/python/math-and-numbers/check-prime-number.md similarity index 100% rename from snippets/Python/math-and-numbers/check-prime-number.md rename to snippets/python/math-and-numbers/check-prime-number.md diff --git a/snippets/Python/math-and-numbers/convert-binary-to-decimal.md b/snippets/python/math-and-numbers/convert-binary-to-decimal.md similarity index 100% rename from snippets/Python/math-and-numbers/convert-binary-to-decimal.md rename to snippets/python/math-and-numbers/convert-binary-to-decimal.md diff --git a/snippets/Python/math-and-numbers/find-factorial.md b/snippets/python/math-and-numbers/find-factorial.md similarity index 100% rename from snippets/Python/math-and-numbers/find-factorial.md rename to snippets/python/math-and-numbers/find-factorial.md 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 similarity index 100% rename from snippets/Python/math-and-numbers/find-lcm-least-common-multiple.md rename to snippets/python/math-and-numbers/find-lcm-least-common-multiple.md diff --git a/snippets/Python/math-and-numbers/solve-quadratic-equation.md b/snippets/python/math-and-numbers/solve-quadratic-equation.md similarity index 100% rename from snippets/Python/math-and-numbers/solve-quadratic-equation.md rename to snippets/python/math-and-numbers/solve-quadratic-equation.md diff --git a/snippets/Python/sqlite-database/create-sqlite-database-table.md b/snippets/python/sqlite-database/create-sqlite-database-table.md similarity index 100% rename from snippets/Python/sqlite-database/create-sqlite-database-table.md rename to snippets/python/sqlite-database/create-sqlite-database-table.md diff --git a/snippets/Python/sqlite-database/insert-data-into-sqlite-table.md b/snippets/python/sqlite-database/insert-data-into-sqlite-table.md similarity index 100% rename from snippets/Python/sqlite-database/insert-data-into-sqlite-table.md rename to snippets/python/sqlite-database/insert-data-into-sqlite-table.md diff --git a/snippets/Python/string-manipulation/capitalize-words.md b/snippets/python/string-manipulation/capitalize-words.md similarity index 100% rename from snippets/Python/string-manipulation/capitalize-words.md rename to snippets/python/string-manipulation/capitalize-words.md diff --git a/snippets/Python/string-manipulation/check-anagram.md b/snippets/python/string-manipulation/check-anagram.md similarity index 100% rename from snippets/Python/string-manipulation/check-anagram.md rename to snippets/python/string-manipulation/check-anagram.md diff --git a/snippets/Python/string-manipulation/check-palindrome.md b/snippets/python/string-manipulation/check-palindrome.md similarity index 100% rename from snippets/Python/string-manipulation/check-palindrome.md rename to snippets/python/string-manipulation/check-palindrome.md 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 similarity index 100% rename from snippets/Python/string-manipulation/convert-snake-case-to-camel-case.md rename to snippets/python/string-manipulation/convert-snake-case-to-camel-case.md diff --git a/snippets/Python/string-manipulation/convert-string-to-ascii.md b/snippets/python/string-manipulation/convert-string-to-ascii.md similarity index 100% rename from snippets/Python/string-manipulation/convert-string-to-ascii.md rename to snippets/python/string-manipulation/convert-string-to-ascii.md diff --git a/snippets/Python/string-manipulation/count-character-frequency.md b/snippets/python/string-manipulation/count-character-frequency.md similarity index 100% rename from snippets/Python/string-manipulation/count-character-frequency.md rename to snippets/python/string-manipulation/count-character-frequency.md diff --git a/snippets/Python/string-manipulation/count-vowels.md b/snippets/python/string-manipulation/count-vowels.md similarity index 100% rename from snippets/Python/string-manipulation/count-vowels.md rename to snippets/python/string-manipulation/count-vowels.md diff --git a/snippets/Python/string-manipulation/count-words.md b/snippets/python/string-manipulation/count-words.md similarity index 100% rename from snippets/Python/string-manipulation/count-words.md rename to snippets/python/string-manipulation/count-words.md diff --git a/snippets/Python/string-manipulation/find-all-substrings.md b/snippets/python/string-manipulation/find-all-substrings.md similarity index 100% rename from snippets/Python/string-manipulation/find-all-substrings.md rename to snippets/python/string-manipulation/find-all-substrings.md diff --git a/snippets/Python/string-manipulation/find-longest-word.md b/snippets/python/string-manipulation/find-longest-word.md similarity index 100% rename from snippets/Python/string-manipulation/find-longest-word.md rename to snippets/python/string-manipulation/find-longest-word.md diff --git a/snippets/Python/string-manipulation/find-unique-characters.md b/snippets/python/string-manipulation/find-unique-characters.md similarity index 100% rename from snippets/Python/string-manipulation/find-unique-characters.md rename to snippets/python/string-manipulation/find-unique-characters.md diff --git a/snippets/Python/string-manipulation/remove-duplicate-characters.md b/snippets/python/string-manipulation/remove-duplicate-characters.md similarity index 100% rename from snippets/Python/string-manipulation/remove-duplicate-characters.md rename to snippets/python/string-manipulation/remove-duplicate-characters.md diff --git a/snippets/Python/string-manipulation/remove-punctuation.md b/snippets/python/string-manipulation/remove-punctuation.md similarity index 100% rename from snippets/Python/string-manipulation/remove-punctuation.md rename to snippets/python/string-manipulation/remove-punctuation.md diff --git a/snippets/Python/string-manipulation/remove-specific-characters.md b/snippets/python/string-manipulation/remove-specific-characters.md similarity index 100% rename from snippets/Python/string-manipulation/remove-specific-characters.md rename to snippets/python/string-manipulation/remove-specific-characters.md diff --git a/snippets/Python/string-manipulation/remove-whitespace.md b/snippets/python/string-manipulation/remove-whitespace.md similarity index 100% rename from snippets/Python/string-manipulation/remove-whitespace.md rename to snippets/python/string-manipulation/remove-whitespace.md diff --git a/snippets/Python/string-manipulation/reverse-string.md b/snippets/python/string-manipulation/reverse-string.md similarity index 100% rename from snippets/Python/string-manipulation/reverse-string.md rename to snippets/python/string-manipulation/reverse-string.md diff --git a/snippets/Python/string-manipulation/split-camel-case.md b/snippets/python/string-manipulation/split-camel-case.md similarity index 100% rename from snippets/Python/string-manipulation/split-camel-case.md rename to snippets/python/string-manipulation/split-camel-case.md diff --git a/snippets/Python/string-manipulation/truncate-string.md b/snippets/python/string-manipulation/truncate-string.md similarity index 100% rename from snippets/Python/string-manipulation/truncate-string.md rename to snippets/python/string-manipulation/truncate-string.md diff --git a/snippets/Python/utilities/convert-bytes-to-human-readable-format.md b/snippets/python/utilities/convert-bytes-to-human-readable-format.md similarity index 100% rename from snippets/Python/utilities/convert-bytes-to-human-readable-format.md rename to snippets/python/utilities/convert-bytes-to-human-readable-format.md diff --git a/snippets/Python/utilities/generate-random-string.md b/snippets/python/utilities/generate-random-string.md similarity index 100% rename from snippets/Python/utilities/generate-random-string.md rename to snippets/python/utilities/generate-random-string.md diff --git a/snippets/Python/utilities/measure-execution-time.md b/snippets/python/utilities/measure-execution-time.md similarity index 100% rename from snippets/Python/utilities/measure-execution-time.md rename to snippets/python/utilities/measure-execution-time.md diff --git a/snippets/Rust/basics/hello-world.md b/snippets/rust/basics/hello-world.md similarity index 100% rename from snippets/Rust/basics/hello-world.md rename to snippets/rust/basics/hello-world.md diff --git a/snippets/Rust/file-handling/find-files.md b/snippets/rust/file-handling/find-files.md similarity index 100% rename from snippets/Rust/file-handling/find-files.md rename to snippets/rust/file-handling/find-files.md diff --git a/snippets/Rust/file-handling/read-file-lines.md b/snippets/rust/file-handling/read-file-lines.md similarity index 100% rename from snippets/Rust/file-handling/read-file-lines.md rename to snippets/rust/file-handling/read-file-lines.md diff --git a/snippets/Rust/icon.svg b/snippets/rust/icon.svg similarity index 100% rename from snippets/Rust/icon.svg rename to snippets/rust/icon.svg diff --git a/snippets/Rust/string-manipulation/capitalize-string.md b/snippets/rust/string-manipulation/capitalize-string.md similarity index 100% rename from snippets/Rust/string-manipulation/capitalize-string.md rename to snippets/rust/string-manipulation/capitalize-string.md diff --git a/snippets/SCSS/animations/fade-in-animation.md b/snippets/scss/animations/fade-in-animation.md similarity index 100% rename from snippets/SCSS/animations/fade-in-animation.md rename to snippets/scss/animations/fade-in-animation.md diff --git a/snippets/SCSS/animations/slide-in-from-left.md b/snippets/scss/animations/slide-in-from-left.md similarity index 100% rename from snippets/SCSS/animations/slide-in-from-left.md rename to snippets/scss/animations/slide-in-from-left.md diff --git a/snippets/SCSS/borders-shadows/border-radius-helper.md b/snippets/scss/borders-shadows/border-radius-helper.md similarity index 100% rename from snippets/SCSS/borders-shadows/border-radius-helper.md rename to snippets/scss/borders-shadows/border-radius-helper.md diff --git a/snippets/SCSS/borders-shadows/box-shadow-helper.md b/snippets/scss/borders-shadows/box-shadow-helper.md similarity index 100% rename from snippets/SCSS/borders-shadows/box-shadow-helper.md rename to snippets/scss/borders-shadows/box-shadow-helper.md diff --git a/snippets/SCSS/components/primary-button.md b/snippets/scss/components/primary-button.md similarity index 100% rename from snippets/SCSS/components/primary-button.md rename to snippets/scss/components/primary-button.md diff --git a/snippets/SCSS/icon.svg b/snippets/scss/icon.svg similarity index 100% rename from snippets/SCSS/icon.svg rename to snippets/scss/icon.svg diff --git a/snippets/SCSS/layouts/aspect-ratio.md b/snippets/scss/layouts/aspect-ratio.md similarity index 100% rename from snippets/SCSS/layouts/aspect-ratio.md rename to snippets/scss/layouts/aspect-ratio.md diff --git a/snippets/SCSS/layouts/flex-center.md b/snippets/scss/layouts/flex-center.md similarity index 100% rename from snippets/SCSS/layouts/flex-center.md rename to snippets/scss/layouts/flex-center.md diff --git a/snippets/SCSS/layouts/grid-container.md b/snippets/scss/layouts/grid-container.md similarity index 100% rename from snippets/SCSS/layouts/grid-container.md rename to snippets/scss/layouts/grid-container.md diff --git a/snippets/SCSS/typography/font-import-helper.md b/snippets/scss/typography/font-import-helper.md similarity index 100% rename from snippets/SCSS/typography/font-import-helper.md rename to snippets/scss/typography/font-import-helper.md diff --git a/snippets/SCSS/typography/line-clamp-mixin.md b/snippets/scss/typography/line-clamp-mixin.md similarity index 100% rename from snippets/SCSS/typography/line-clamp-mixin.md rename to snippets/scss/typography/line-clamp-mixin.md diff --git a/snippets/SCSS/typography/text-gradient.md b/snippets/scss/typography/text-gradient.md similarity index 100% rename from snippets/SCSS/typography/text-gradient.md rename to snippets/scss/typography/text-gradient.md diff --git a/snippets/SCSS/typography/text-overflow-ellipsis.md b/snippets/scss/typography/text-overflow-ellipsis.md similarity index 100% rename from snippets/SCSS/typography/text-overflow-ellipsis.md rename to snippets/scss/typography/text-overflow-ellipsis.md diff --git a/snippets/SCSS/utilities/clearfix.md b/snippets/scss/utilities/clearfix.md similarity index 100% rename from snippets/SCSS/utilities/clearfix.md rename to snippets/scss/utilities/clearfix.md diff --git a/snippets/SCSS/utilities/responsive-breakpoints.md b/snippets/scss/utilities/responsive-breakpoints.md similarity index 100% rename from snippets/SCSS/utilities/responsive-breakpoints.md rename to snippets/scss/utilities/responsive-breakpoints.md diff --git a/utils/consolidateSnippets.js b/utils/consolidateSnippets.js index b3d50965..a55cf203 100644 --- a/utils/consolidateSnippets.js +++ b/utils/consolidateSnippets.js @@ -1,5 +1,5 @@ import { exit } from 'process'; -import { parseAllSnippets, slugify } from './snippetParser.js'; +import { parseAllSnippets, reverseSlugify } from './snippetParser.js'; import { join } from 'path'; import { copyFileSync, writeFileSync } from 'fs'; @@ -14,14 +14,13 @@ if(errored) exit(1); const index = []; for(const [language, categories] of Object.entries(snippets)) { - const languageSlugName = slugify(language); const languageIconPath = join(snippetsPath, language, 'icon.svg'); - copyFileSync(languageIconPath, join(iconPath, `${languageSlugName}.svg`)); + copyFileSync(languageIconPath, join(iconPath, `${language}.svg`)); - index.push({ lang: language, icon: `/icons/${languageSlugName}.svg` }); + index.push({ lang: reverseSlugify(language), icon: `/icons/${language}.svg` }); - const languageFilePath = join(dataPath, `${languageSlugName}.json`); + const languageFilePath = join(dataPath, `${language}.json`); writeFileSync(languageFilePath, JSON.stringify(categories, null, 4)); } diff --git a/utils/snippetParser.js b/utils/snippetParser.js index e9d4b395..0b704537 100644 --- a/utils/snippetParser.js +++ b/utils/snippetParser.js @@ -8,17 +8,6 @@ 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 = '') { From 9d1c04de4a8b94038535f4b0e3141cfda407053e Mon Sep 17 00:00:00 2001 From: Mathys-Gasnier Date: Wed, 1 Jan 2025 13:39:44 +0100 Subject: [PATCH 07/10] Adding support for an optional contributor field in the parser --- utils/snippetParser.js | 1 + 1 file changed, 1 insertion(+) diff --git a/utils/snippetParser.js b/utils/snippetParser.js index 0b704537..346f1ab8 100644 --- a/utils/snippetParser.js +++ b/utils/snippetParser.js @@ -52,6 +52,7 @@ function parseSnippet(snippetPath, text) { description: properties.description, author: properties.author, tags: properties.tags.split(',').map((tag) => tag.trim()).filter((tag) => tag), + contributors: 'contributors' in properties ? properties.contributors.split(',').map((contributor) => contributor.trim()).filter((contributor) => contributor) : [], code: code, } } From b4da317aae4904e3131957574f94c3432f2cef43 Mon Sep 17 00:00:00 2001 From: Mathys-Gasnier Date: Wed, 1 Jan 2025 13:40:26 +0100 Subject: [PATCH 08/10] Making all language name uppercase --- public/data/_index.json | 14 +++---- public/data/c.json | 3 ++ public/data/cpp.json | 3 ++ public/data/css.json | 12 ++++++ public/data/html.json | 2 + public/data/javascript.json | 73 ++++++++++++++++++++++++++++++++++++ public/data/python.json | 65 ++++++++++++++++++++++++++++++++ public/data/rust.json | 4 ++ public/data/scss.json | 14 +++++++ utils/consolidateSnippets.js | 2 +- 10 files changed, 184 insertions(+), 8 deletions(-) diff --git a/public/data/_index.json b/public/data/_index.json index 941d99f0..9a1e06f1 100644 --- a/public/data/_index.json +++ b/public/data/_index.json @@ -4,31 +4,31 @@ "icon": "/icons/c.svg" }, { - "lang": "Cpp", + "lang": "CPP", "icon": "/icons/cpp.svg" }, { - "lang": "Css", + "lang": "CSS", "icon": "/icons/css.svg" }, { - "lang": "Html", + "lang": "HTML", "icon": "/icons/html.svg" }, { - "lang": "Javascript", + "lang": "JAVASCRIPT", "icon": "/icons/javascript.svg" }, { - "lang": "Python", + "lang": "PYTHON", "icon": "/icons/python.svg" }, { - "lang": "Rust", + "lang": "RUST", "icon": "/icons/rust.svg" }, { - "lang": "Scss", + "lang": "SCSS", "icon": "/icons/scss.svg" } ] \ No newline at end of file diff --git a/public/data/c.json b/public/data/c.json index af65b1fa..b9a0e854 100644 --- a/public/data/c.json +++ b/public/data/c.json @@ -12,6 +12,7 @@ "hello-world", "utility" ], + "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" } ] @@ -29,6 +30,7 @@ "factorial", "utility" ], + "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" }, { @@ -41,6 +43,7 @@ "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" } ] diff --git a/public/data/cpp.json b/public/data/cpp.json index 69f6162f..71be4881 100644 --- a/public/data/cpp.json +++ b/public/data/cpp.json @@ -12,6 +12,7 @@ "hello-world", "utility" ], + "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" } ] @@ -29,6 +30,7 @@ "reverse", "utility" ], + "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" }, { @@ -41,6 +43,7 @@ "split", "utility" ], + "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" } ] diff --git a/public/data/css.json b/public/data/css.json index 6d91f46b..ff9b2725 100644 --- a/public/data/css.json +++ b/public/data/css.json @@ -12,6 +12,7 @@ "3D", "effect" ], + "contributors": [], "code": ".button {\n background-color: #28a745;\n color: white;\n padding: 10px 20px;\n border: none;\n border-radius: 5px;\n box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);\n transition: transform 0.1s;\n}\n\n.button:active {\n transform: translateY(2px);\n box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);\n}\n" }, { @@ -24,6 +25,7 @@ "hover", "transition" ], + "contributors": [], "code": ".button {\n background-color: #007bff;\n color: white;\n padding: 10px 20px;\n border: none;\n border-radius: 5px;\n cursor: pointer;\n transition: background-color 0.3s ease;\n}\n\n.button:hover {\n background-color: #0056b3;\n}\n" }, { @@ -37,6 +39,7 @@ "hover", "transition" ], + "contributors": [], "code": ".button {\n font: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica,;\n background: #0a85ff;\n color: #fff;\n padding: 8px 12px;\n border: none;\n margin: 4px;\n border-radius: 10px;\n cursor: pointer;\n box-shadow: inset 0 1px 1px #fff2, 0px 2px 3px -2px rgba(0, 0, 0, 0.3) !important; /*This is really performance heavy*/\n font-size: 14px;\n display: flex;\n align-items: center;\n justify-content: center;\n text-decoration: none;\n transition: all 150ms cubic-bezier(0.175, 0.885, 0.32, 1.275);\n}\n.button:hover {\n background: #0974ee;\n color: #fff\n}\n" } ] @@ -54,6 +57,7 @@ "background", "effects" ], + "contributors": [], "code": ".blur-background {\n backdrop-filter: blur(10px);\n background: rgba(255, 255, 255, 0.5);\n}\n" }, { @@ -66,6 +70,7 @@ "glow", "effects" ], + "contributors": [], "code": ".glow {\n background-color: #f39c12;\n padding: 10px 20px;\n border-radius: 5px;\n transition: box-shadow 0.3s ease;\n}\n\n.glow:hover {\n box-shadow: 0 0 15px rgba(243, 156, 18, 0.8);\n}\n" } ] @@ -83,6 +88,7 @@ "browser", "layout" ], + "contributors": [], "code": "* {\n margin: 0;\n padding: 0;\n box-sizing: border-box\n}\n" }, { @@ -95,6 +101,7 @@ "columns", "layout" ], + "contributors": [], "code": ".columns {\n display: flex;\n justify-content: space-between;\n}\n\n.column {\n flex: 1;\n margin: 0 10px;\n}\n" }, { @@ -106,6 +113,7 @@ "layout", "grid" ], + "contributors": [], "code": ".grid-container {\n display: grid\n grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));\n/* Explanation:\n- `auto-fit`: Automatically fits as many columns as possible within the container.\n- `minmax(250px, 1fr)`: Defines a minimum column size of 250px and a maximum size of 1fr (fraction of available space).\n*/\n}\n\n" }, { @@ -116,6 +124,7 @@ "css", "responsive" ], + "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" }, { @@ -128,6 +137,7 @@ "footer", "sticky" ], + "contributors": [], "code": "body {\n display: flex;\n flex-direction: column;\n min-height: 100vh;\n}\n\nfooter {\n margin-top: auto;\n}\n" } ] @@ -144,6 +154,7 @@ "typography", "spacing" ], + "contributors": [], "code": "p {\n letter-spacing: 0.05em;\n}\n" }, { @@ -156,6 +167,7 @@ "responsive", "typography" ], + "contributors": [], "code": "h1 {\n font-size: calc(1.5rem + 2vw);\n}\n" } ] diff --git a/public/data/html.json b/public/data/html.json index 7ef58ba0..9ea5b9b1 100644 --- a/public/data/html.json +++ b/public/data/html.json @@ -14,6 +14,7 @@ "grid", "full-height" ], + "contributors": [], "code": "\n\n \n \n \n \n
\n Header\n \n
\n
Main Content
\n
Footer
\n \n\n" }, { @@ -28,6 +29,7 @@ "flexbox", "viewport" ], + "contributors": [], "code": "\n\n \n \n \n \n
header
\n
body/content
\n
footer
\n \n\n" } ] diff --git a/public/data/javascript.json b/public/data/javascript.json index 5134f797..ca13b7a6 100644 --- a/public/data/javascript.json +++ b/public/data/javascript.json @@ -12,6 +12,7 @@ "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" }, { @@ -24,6 +25,7 @@ "deduplicate", "utility" ], + "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" }, { @@ -36,6 +38,7 @@ "shuffle", "utility" ], + "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" }, { @@ -48,6 +51,7 @@ "utility", "map" ], + "contributors": [], "code": "const zip = (arr1, arr2) => arr1.map((value, index) => [value, arr2[index]]);\n\n// Usage:\nconst arr1 = ['a', 'b', 'c'];\nconst arr2 = [1, 2, 3];\nconsole.log(zip(arr1, arr2)); // Output: [['a', 1], ['b', 2], ['c', 3]]\n" } ] @@ -65,6 +69,7 @@ "hello-world", "utility" ], + "contributors": [], "code": "console.log(\"Hello, World!\"); // Prints Hello, World! to the console\n" } ] @@ -82,6 +87,7 @@ "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" }, { @@ -94,6 +100,7 @@ "leap-year", "utility" ], + "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" }, { @@ -106,6 +113,7 @@ "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" }, { @@ -118,6 +126,7 @@ "timestamp", "utility" ], + "contributors": [], "code": "const getCurrentTimestamp = () => Date.now();\n\n// Usage:\nconsole.log(getCurrentTimestamp()); // Output: 1691825935839 (example)\n" }, { @@ -130,6 +139,7 @@ "day-of-year", "utility" ], + "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" }, { @@ -142,6 +152,7 @@ "days-in-month", "utility" ], + "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" }, { @@ -154,6 +165,7 @@ "time-difference", "utility" ], + "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" }, { @@ -169,6 +181,7 @@ "past", "utility" ], + "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" }, { @@ -181,6 +194,7 @@ "start-of-day", "utility" ], + "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" } ] @@ -198,6 +212,7 @@ "style", "utility" ], + "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" }, { @@ -210,6 +225,7 @@ "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" }, { @@ -222,6 +238,7 @@ "remove", "utility" ], + "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" }, { @@ -234,6 +251,7 @@ "scroll", "ui" ], + "contributors": [], "code": "const smoothScroll = (element) => {\n element.scrollIntoView({ behavior: 'smooth' });\n};\n\n// Usage:\nconst target = document.querySelector('#target');\nsmoothScroll(target);\n" }, { @@ -246,6 +264,7 @@ "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" } ] @@ -263,6 +282,7 @@ "compose", "utility" ], + "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" }, { @@ -275,6 +295,7 @@ "function", "utility" ], + "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" }, { @@ -287,6 +308,7 @@ "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" }, { @@ -301,6 +323,7 @@ "brightness", "utility" ], + "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" }, { @@ -313,6 +336,7 @@ "optimization", "utility" ], + "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" }, { @@ -325,6 +349,7 @@ "once", "utility" ], + "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" }, { @@ -337,6 +362,7 @@ "rate-limiting", "utility" ], + "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" }, { @@ -349,6 +375,7 @@ "repeat", "utility" ], + "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" }, { @@ -362,6 +389,7 @@ "utility", "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" }, { @@ -374,6 +402,7 @@ "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" } ] @@ -391,6 +420,7 @@ "storage", "utility" ], + "contributors": [], "code": "const addToLocalStorage = (key, value) => {\n localStorage.setItem(key, JSON.stringify(value));\n};\n\n// Usage:\naddToLocalStorage('user', { name: 'John', age: 30 });\n" }, { @@ -403,6 +433,7 @@ "storage", "utility" ], + "contributors": [], "code": "const isItemInLocalStorage = (key) => {\n return localStorage.getItem(key) !== null;\n};\n\n// Usage:\nconsole.log(isItemInLocalStorage('user')); // Output: true or false\n" }, { @@ -415,6 +446,7 @@ "storage", "utility" ], + "contributors": [], "code": "const clearLocalStorage = () => {\n localStorage.clear();\n};\n\n// Usage:\nclearLocalStorage(); // Removes all items from localStorage\n" }, { @@ -427,6 +459,7 @@ "storage", "utility" ], + "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" } ] @@ -444,6 +477,7 @@ "currency", "utility" ], + "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" }, { @@ -456,6 +490,7 @@ "roman", "utility" ], + "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" }, { @@ -468,6 +503,7 @@ "scientific", "utility" ], + "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" }, { @@ -480,6 +516,7 @@ "format", "utility" ], + "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" }, { @@ -492,6 +529,7 @@ "format", "utility" ], + "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" }, { @@ -504,6 +542,7 @@ "words", "utility" ], + "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" } ] @@ -521,6 +560,7 @@ "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" }, { @@ -533,6 +573,7 @@ "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" }, { @@ -545,6 +586,7 @@ "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" }, { @@ -557,6 +599,7 @@ "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" }, { @@ -569,6 +612,7 @@ "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" }, { @@ -581,6 +625,7 @@ "filter", "utility" ], + "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" }, { @@ -593,6 +638,7 @@ "flatten", "utility" ], + "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" }, { @@ -605,6 +651,7 @@ "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" }, { @@ -617,6 +664,7 @@ "nested", "utility" ], + "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" }, { @@ -629,6 +677,7 @@ "invert", "utility" ], + "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" }, { @@ -641,6 +690,7 @@ "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" }, { @@ -653,6 +703,7 @@ "omit", "utility" ], + "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" }, { @@ -665,6 +716,7 @@ "pick", "utility" ], + "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" }, { @@ -677,6 +729,7 @@ "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" } ] @@ -692,6 +745,7 @@ "javascript", "regex" ], + "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" } ] @@ -709,6 +763,7 @@ "capitalize", "utility" ], + "contributors": [], "code": "const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);\n\n// Usage:\nconsole.log(capitalize('hello')); // Output: 'Hello'\n" }, { @@ -721,6 +776,7 @@ "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" }, { @@ -732,6 +788,7 @@ "case", "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" }, { @@ -743,6 +800,7 @@ "case", "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" }, { @@ -754,6 +812,7 @@ "case", "pascalCase" ], + "contributors": [], "code": "function toPascalCase(str) {\n return str.replace(/\\b\\w/g, (s) => s.toUpperCase()).replace(/\\W+(.)/g, (match, chr) => chr.toUpperCase());\n}\n\n// Example usage:\nconsole.log(toPascalCase('hello world test')); // Output: 'HelloWorldTest'\n" }, { @@ -765,6 +824,7 @@ "case", "snake_case" ], + "contributors": [], "code": "function toSnakeCase(str) {\n return str.replace(/([a-z])([A-Z])/g, '$1_$2')\n .replace(/\\s+/g, '_')\n .toLowerCase();\n}\n\n// Example usage:\nconsole.log(toSnakeCase('Hello World Test')); // Output: 'hello_world_test'\n" }, { @@ -776,6 +836,7 @@ "case", "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" }, { @@ -787,6 +848,7 @@ "tabs", "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" }, { @@ -800,6 +862,7 @@ "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" }, { @@ -811,6 +874,7 @@ "data", "utility" ], + "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" }, { @@ -822,6 +886,7 @@ "initials", "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" }, { @@ -833,6 +898,7 @@ "mask", "sensitive" ], + "contributors": [], "code": "function maskSensitiveInfo(str, visibleCount = 4, maskChar = '*') {\n return str.slice(0, visibleCount) + maskChar.repeat(Math.max(0, str.length - visibleCount));\n}\n\n// Example usage:\nconsole.log(maskSensitiveInfo('123456789', 4)); // Output: '1234*****'\nconsole.log(maskSensitiveInfo('example@mail.com', 2, '#')); // Output: 'ex#############'\n" }, { @@ -844,6 +910,7 @@ "pad", "manipulation" ], + "contributors": [], "code": "function padString(str, length, char = ' ') {\n const totalPad = length - str.length;\n const padStart = Math.floor(totalPad / 2);\n const padEnd = totalPad - padStart;\n return char.repeat(padStart) + str + char.repeat(padEnd);\n}\n\n// Example usage:\nconsole.log(padString('hello', 10, '*')); // Output: '**hello***'\n" }, { @@ -855,6 +922,7 @@ "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" }, { @@ -866,6 +934,7 @@ "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" }, { @@ -877,6 +946,7 @@ "remove", "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" }, { @@ -889,6 +959,7 @@ "reverse", "utility" ], + "contributors": [], "code": "const reverseString = (str) => str.split('').reverse().join('');\n\n// Usage:\nconsole.log(reverseString('hello')); // Output: 'olleh'\n" }, { @@ -901,6 +972,7 @@ "slug", "utility" ], + "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" }, { @@ -914,6 +986,7 @@ "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" } ] diff --git a/public/data/python.json b/public/data/python.json index b8a46b3f..fce38442 100644 --- a/public/data/python.json +++ b/public/data/python.json @@ -12,6 +12,7 @@ "hello-world", "utility" ], + "contributors": [], "code": "print(\"Hello, World!\") # Prints Hello, World! to the terminal.\n" } ] @@ -28,6 +29,7 @@ "datetime", "utility" ], + "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" }, { @@ -40,6 +42,7 @@ "weekend", "utility" ], + "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" }, { @@ -52,6 +55,7 @@ "weekday", "utility" ], + "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" }, { @@ -64,6 +68,7 @@ "range", "utility" ], + "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" }, { @@ -75,6 +80,7 @@ "datetime", "utility" ], + "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" }, { @@ -87,6 +93,7 @@ "calendar", "utility" ], + "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" } ] @@ -104,6 +111,7 @@ "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" }, { @@ -116,6 +124,7 @@ "retry", "utility" ], + "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" }, { @@ -128,6 +137,7 @@ "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" }, { @@ -140,6 +150,7 @@ "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" } ] @@ -157,6 +168,7 @@ "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" }, { @@ -170,6 +182,7 @@ "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" }, { @@ -182,6 +195,7 @@ "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" }, { @@ -194,6 +208,7 @@ "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" }, { @@ -206,6 +221,7 @@ "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" }, { @@ -218,6 +234,7 @@ "extension", "utility" ], + "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" }, { @@ -231,6 +248,7 @@ "directory", "utility" ], + "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" }, { @@ -244,6 +262,7 @@ "chunks", "utility" ], + "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" }, { @@ -256,6 +275,7 @@ "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" }, { @@ -268,6 +288,7 @@ "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" } ] @@ -285,6 +306,7 @@ "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" }, { @@ -297,6 +319,7 @@ "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" }, { @@ -309,6 +332,7 @@ "merge", "file" ], + "contributors": [], "code": "import json\n\ndef merge_json_files(filepaths, output_filepath):\n merged_data = []\n\n # Read each JSON file and merge their data\n for filepath in filepaths:\n with open(filepath, 'r') as file:\n data = json.load(file)\n merged_data.extend(data)\n\n # Write the merged data into a new file\n with open(output_filepath, 'w') as file:\n json.dump(merged_data, file, indent=4)\n\n# Usage:\nfiles_to_merge = ['file1.json', 'file2.json']\nmerge_json_files(files_to_merge, 'merged.json')\n" }, { @@ -321,6 +345,7 @@ "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" }, { @@ -333,6 +358,7 @@ "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" }, { @@ -345,6 +371,7 @@ "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" }, { @@ -357,6 +384,7 @@ "file", "write" ], + "contributors": [], "code": "import json\n\ndef write_json(filepath, data):\n with open(filepath, 'w') as file:\n json.dump(data, file, indent=4)\n\n# Usage:\ndata = {'name': 'John', 'age': 30}\nwrite_json('data.json', data)\n" } ] @@ -374,6 +402,7 @@ "duplicates", "utility" ], + "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" }, { @@ -386,6 +415,7 @@ "intersection", "utility" ], + "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" }, { @@ -398,6 +428,7 @@ "difference", "utility" ], + "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" }, { @@ -410,6 +441,7 @@ "flatten", "utility" ], + "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" }, { @@ -424,6 +456,7 @@ "depth", "utilities" ], + "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" }, { @@ -436,6 +469,7 @@ "partition", "utility" ], + "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" }, { @@ -448,6 +482,7 @@ "duplicates", "utility" ], + "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" } ] @@ -465,6 +500,7 @@ "compound interest", "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" }, { @@ -477,6 +513,7 @@ "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" }, { @@ -489,6 +526,7 @@ "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" }, { @@ -502,6 +540,7 @@ "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" }, { @@ -514,6 +553,7 @@ "factorial", "utility" ], + "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" }, { @@ -527,6 +567,7 @@ "gcd", "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" }, { @@ -540,6 +581,7 @@ "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" } ] @@ -557,6 +599,7 @@ "database", "table" ], + "contributors": [], "code": "import sqlite3\n\ndef create_table(db_name, table_name, schema):\n conn = sqlite3.connect(db_name)\n cursor = conn.cursor()\n schema_string = ', '.join([f'{col} {dtype}' for col, dtype in schema.items()])\n cursor.execute(f'''\n CREATE TABLE IF NOT EXISTS {table_name} (\n {schema_string}\n )''')\n conn.commit()\n conn.close()\n\n# Usage:\ndb_name = 'example.db'\ntable_name = 'users'\nschema = {\n 'id': 'INTEGER PRIMARY KEY',\n 'name': 'TEXT',\n 'age': 'INTEGER',\n 'email': 'TEXT'\n}\ncreate_table(db_name, table_name, schema)\n" }, { @@ -569,6 +612,7 @@ "database", "utility" ], + "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" } ] @@ -586,6 +630,7 @@ "capitalize", "utility" ], + "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" }, { @@ -599,6 +644,7 @@ "check", "utility" ], + "contributors": [], "code": "def is_anagram(s1, s2):\n return sorted(s1) == sorted(s2)\n\n# Usage:\nprint(is_anagram('listen', 'silent')) # Output: True\n" }, { @@ -611,6 +657,7 @@ "palindrome", "utility" ], + "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" }, { @@ -625,6 +672,7 @@ "convert", "utility" ], + "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" }, { @@ -638,6 +686,7 @@ "convert", "utility" ], + "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" }, { @@ -650,6 +699,7 @@ "character-frequency", "utility" ], + "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" }, { @@ -663,6 +713,7 @@ "count", "utility" ], + "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" }, { @@ -675,6 +726,7 @@ "word-count", "utility" ], + "contributors": [], "code": "def count_words(s):\n return len(s.split())\n\n# Usage:\nprint(count_words('The quick brown fox')) # Output: 4\n" }, { @@ -688,6 +740,7 @@ "find", "utility" ], + "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" }, { @@ -700,6 +753,7 @@ "longest-word", "utility" ], + "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" }, { @@ -713,6 +767,7 @@ "characters", "utility" ], + "contributors": [], "code": "def find_unique_chars(s):\n return ''.join(sorted(set(s)))\n\n# Usage:\nprint(find_unique_chars('banana')) # Output: 'abn'\n" }, { @@ -726,6 +781,7 @@ "remove", "utility" ], + "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" }, { @@ -739,6 +795,7 @@ "remove", "utility" ], + "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" }, { @@ -752,6 +809,7 @@ "characters", "utility" ], + "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" }, { @@ -765,6 +823,7 @@ "remove", "utility" ], + "contributors": [], "code": "def remove_whitespace(s):\n return ''.join(s.split())\n\n# Usage:\nprint(remove_whitespace('hello world')) # Output: 'helloworld'\n" }, { @@ -777,6 +836,7 @@ "reverse", "utility" ], + "contributors": [], "code": "def reverse_string(s):\n return s[::-1]\n\n# Usage:\nprint(reverse_string('hello')) # Output: 'olleh'\n" }, { @@ -790,6 +850,7 @@ "split", "utility" ], + "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" }, { @@ -802,6 +863,7 @@ "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" } ] @@ -819,6 +881,7 @@ "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" }, { @@ -831,6 +894,7 @@ "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" }, { @@ -843,6 +907,7 @@ "execution", "utility" ], + "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" } ] diff --git a/public/data/rust.json b/public/data/rust.json index 7763a959..68d92de1 100644 --- a/public/data/rust.json +++ b/public/data/rust.json @@ -12,6 +12,7 @@ "hello-world", "utility" ], + "contributors": [], "code": "fn main() { // Defines the main running function\n println!(\"Hello, World!\"); // Prints Hello, World! to the terminal.\n}\n" } ] @@ -28,6 +29,7 @@ "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" }, { @@ -40,6 +42,7 @@ "read", "utility" ], + "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" } ] @@ -57,6 +60,7 @@ "capitalize", "utility" ], + "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" } ] diff --git a/public/data/scss.json b/public/data/scss.json index 955e528a..28ae8932 100644 --- a/public/data/scss.json +++ b/public/data/scss.json @@ -12,6 +12,7 @@ "fade", "css" ], + "contributors": [], "code": "@keyframes fade-in {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n@mixin fade-in($duration: 1s, $easing: ease-in-out) {\n animation: fade-in $duration $easing;\n}\n" }, { @@ -24,6 +25,7 @@ "slide", "css" ], + "contributors": [], "code": "@keyframes slide-in-left {\n from {\n transform: translateX(-100%);\n }\n to {\n transform: translateX(0);\n }\n}\n\n@mixin slide-in-left($duration: 0.5s, $easing: ease-out) {\n animation: slide-in-left $duration $easing;\n}\n" } ] @@ -41,6 +43,7 @@ "radius", "css" ], + "contributors": [], "code": "@mixin border-radius($radius: 4px) {\n border-radius: $radius;\n}\n" }, { @@ -53,6 +56,7 @@ "css", "effects" ], + "contributors": [], "code": "@mixin box-shadow($x: 0px, $y: 4px, $blur: 10px, $spread: 0px, $color: rgba(0, 0, 0, 0.1)) {\n box-shadow: $x $y $blur $spread $color;\n}\n" } ] @@ -70,6 +74,7 @@ "primary", "css" ], + "contributors": [], "code": "@mixin primary-button($bg: #007bff, $color: #fff) {\n background-color: $bg;\n color: $color;\n padding: 0.5rem 1rem;\n border: none;\n border-radius: 4px;\n cursor: pointer;\n\n &:hover {\n background-color: darken($bg, 10%);\n }\n}\n" } ] @@ -87,6 +92,7 @@ "layout", "css" ], + "contributors": [], "code": "@mixin aspect-ratio($width, $height) {\n position: relative;\n width: 100%;\n padding-top: ($height / $width) * 100%;\n > * {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n }\n}\n" }, { @@ -99,6 +105,7 @@ "center", "css" ], + "contributors": [], "code": "@mixin flex-center {\n display: flex;\n justify-content: center;\n align-items: center;\n}\n" }, { @@ -111,6 +118,7 @@ "layout", "css" ], + "contributors": [], "code": "@mixin grid-container($columns: 12, $gap: 1rem) {\n display: grid;\n grid-template-columns: repeat($columns, 1fr);\n gap: $gap;\n}\n" } ] @@ -128,6 +136,7 @@ "fonts", "css" ], + "contributors": [], "code": "@mixin import-font($family, $weight: 400, $style: normal) {\n @font-face {\n font-family: #{$family};\n font-weight: #{$weight};\n font-style: #{$style};\n src: url('/fonts/#{$family}-#{$weight}.woff2') format('woff2'),\n url('/fonts/#{$family}-#{$weight}.woff') format('woff');\n }\n}\n" }, { @@ -140,6 +149,7 @@ "typography", "css" ], + "contributors": [], "code": "@mixin line-clamp($number) {\n display: -webkit-box;\n -webkit-box-orient: vertical;\n -webkit-line-clamp: $number;\n overflow: hidden;\n}\n" }, { @@ -153,6 +163,7 @@ "text", "css" ], + "contributors": [], "code": "@mixin text-gradient($from, $to) {\n background: linear-gradient(to right, $from, $to);\n -webkit-background-clip: text;\n -webkit-text-fill-color: transparent;\n}\n" }, { @@ -165,6 +176,7 @@ "text", "css" ], + "contributors": [], "code": "@mixin text-ellipsis {\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n" } ] @@ -182,6 +194,7 @@ "utility", "css" ], + "contributors": [], "code": "@mixin clearfix {\n &::after {\n content: '';\n display: block;\n clear: both;\n }\n}\n" }, { @@ -194,6 +207,7 @@ "media-queries", "css" ], + "contributors": [], "code": "@mixin breakpoint($breakpoint) {\n @if $breakpoint == sm {\n @media (max-width: 576px) { @content; }\n } @else if $breakpoint == md {\n @media (max-width: 768px) { @content; }\n } @else if $breakpoint == lg {\n @media (max-width: 992px) { @content; }\n } @else if $breakpoint == xl {\n @media (max-width: 1200px) { @content; }\n }\n}\n" } ] diff --git a/utils/consolidateSnippets.js b/utils/consolidateSnippets.js index a55cf203..d0a33b2a 100644 --- a/utils/consolidateSnippets.js +++ b/utils/consolidateSnippets.js @@ -18,7 +18,7 @@ for(const [language, categories] of Object.entries(snippets)) { copyFileSync(languageIconPath, join(iconPath, `${language}.svg`)); - index.push({ lang: reverseSlugify(language), icon: `/icons/${language}.svg` }); + index.push({ lang: reverseSlugify(language).toUpperCase(), icon: `/icons/${language}.svg` }); const languageFilePath = join(dataPath, `${language}.json`); From 38fcc56755320862e4219511e37bcf39476d9910 Mon Sep 17 00:00:00 2001 From: Mathys-Gasnier Date: Wed, 1 Jan 2025 14:15:51 +0100 Subject: [PATCH 09/10] Making the migrate snippet script support already migrated json files and contributor array --- snippets/css/layouts/grid-layout.md | 1 - utils/migrateSnippets.js | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/snippets/css/layouts/grid-layout.md b/snippets/css/layouts/grid-layout.md index 2b0d434d..c28260d5 100644 --- a/snippets/css/layouts/grid-layout.md +++ b/snippets/css/layouts/grid-layout.md @@ -14,5 +14,4 @@ Tags: css,layout,grid - `minmax(250px, 1fr)`: Defines a minimum column size of 250px and a maximum size of 1fr (fraction of available space). */ } - ``` diff --git a/utils/migrateSnippets.js b/utils/migrateSnippets.js index 8d43e1fb..c77da85a 100644 --- a/utils/migrateSnippets.js +++ b/utils/migrateSnippets.js @@ -18,11 +18,11 @@ function formatSnippet(snippet) { Title: ${snippet.title} Description: ${snippet.description} Author: ${snippet.author} -Tags: ${snippet.tags} +Tags: ${snippet.tags}${('contributors' in snippet) && snippet.contributors.length > 0 ? `\nContributors: ${snippet.contributors}` : ''} --- \`\`\` -${snippet.code.join('\n')} +${Array.isArray(snippet.code) ? snippet.code.join('\n').trim() : snippet.code.trim()} \`\`\` `; } From debaa0e7f6ae8d5bf06105edd7624ae311ebccd8 Mon Sep 17 00:00:00 2001 From: Mathys-Gasnier Date: Wed, 1 Jan 2025 14:40:14 +0100 Subject: [PATCH 10/10] Add language to codeblocks using migration script --- snippets/c/basics/hello-world.md | 2 +- .../c/mathematical-functions/factorial-function.md | 2 +- snippets/c/mathematical-functions/power-function.md | 2 +- snippets/cpp/basics/hello-world.md | 2 +- snippets/cpp/string-manipulation/reverse-string.md | 2 +- snippets/cpp/string-manipulation/split-string.md | 2 +- snippets/css/buttons/3d-button-effect.md | 2 +- snippets/css/buttons/button-hover-effect.md | 2 +- snippets/css/buttons/macos-button.md | 2 +- snippets/css/effects/blur-background.md | 2 +- snippets/css/effects/hover-glow-effect.md | 2 +- snippets/css/layouts/css-reset.md | 2 +- snippets/css/layouts/equal-width-columns.md | 2 +- snippets/css/layouts/grid-layout.md | 2 +- snippets/css/layouts/responsive-design.md | 2 +- snippets/css/layouts/sticky-footer.md | 2 +- snippets/css/typography/letter-spacing.md | 2 +- snippets/css/typography/responsive-font-sizing.md | 2 +- .../html/basic-layouts/grid-layout-with-navigation.md | 2 +- .../html/basic-layouts/sticky-header-footer-layout.md | 2 +- .../javascript/array-manipulation/flatten-array.md | 2 +- .../array-manipulation/remove-duplicates.md | 2 +- .../javascript/array-manipulation/shuffle-array.md | 2 +- snippets/javascript/array-manipulation/zip-arrays.md | 2 +- snippets/javascript/basics/hello-world.md | 2 +- .../javascript/date-and-time/add-days-to-a-date.md | 2 +- snippets/javascript/date-and-time/check-leap-year.md | 2 +- snippets/javascript/date-and-time/format-date.md | 2 +- .../javascript/date-and-time/get-current-timestamp.md | 2 +- .../javascript/date-and-time/get-day-of-the-year.md | 2 +- .../javascript/date-and-time/get-days-in-month.md | 2 +- .../javascript/date-and-time/get-time-difference.md | 2 +- .../date-and-time/relative-time-formatter.md | 2 +- snippets/javascript/date-and-time/start-of-the-day.md | 2 +- .../dom-manipulation/change-element-style.md | 2 +- .../dom-manipulation/get-element-position.md | 2 +- .../javascript/dom-manipulation/remove-element.md | 2 +- .../dom-manipulation/smooth-scroll-to-element.md | 2 +- snippets/javascript/dom-manipulation/toggle-class.md | 2 +- .../function-utilities/compose-functions.md | 2 +- .../javascript/function-utilities/curry-function.md | 2 +- .../function-utilities/debounce-function.md | 2 +- .../function-utilities/get-contrast-color.md | 2 +- .../javascript/function-utilities/memoize-function.md | 2 +- .../javascript/function-utilities/once-function.md | 2 +- .../function-utilities/rate-limit-function.md | 2 +- .../function-utilities/repeat-function-invocation.md | 2 +- .../javascript/function-utilities/sleep-function.md | 2 +- .../function-utilities/throttle-function.md | 2 +- .../local-storage/add-item-to-localstorage.md | 2 +- .../check-if-item-exists-in-localstorage.md | 2 +- .../local-storage/clear-all-localstorage.md | 2 +- .../local-storage/retrieve-item-from-localstorage.md | 2 +- .../number-formatting/convert-number-to-currency.md | 2 +- .../convert-number-to-roman-numerals.md | 2 +- .../convert-to-scientific-notation.md | 2 +- .../number-formatting/format-number-with-commas.md | 2 +- .../javascript/number-formatting/number-formatter.md | 2 +- .../number-formatting/number-to-words-converter.md | 2 +- .../object-manipulation/check-if-object-is-empty.md | 2 +- .../object-manipulation/clone-object-shallowly.md | 2 +- .../compare-two-objects-shallowly.md | 2 +- .../convert-object-to-query-string.md | 2 +- .../object-manipulation/count-properties-in-object.md | 2 +- .../javascript/object-manipulation/filter-object.md | 2 +- .../object-manipulation/flatten-nested-object.md | 2 +- .../javascript/object-manipulation/freeze-object.md | 2 +- .../object-manipulation/get-nested-value.md | 2 +- .../invert-object-keys-and-values.md | 2 +- .../object-manipulation/merge-objects-deeply.md | 2 +- .../object-manipulation/omit-keys-from-object.md | 2 +- .../object-manipulation/pick-keys-from-object.md | 2 +- .../javascript/object-manipulation/unique-by-key.md | 2 +- .../regex-match-utility-function.md | 2 +- .../string-manipulation/capitalize-string.md | 2 +- .../check-if-string-is-a-palindrome.md | 2 +- .../convert-string-to-camel-case.md | 2 +- .../convert-string-to-param-case.md | 2 +- .../convert-string-to-pascal-case.md | 2 +- .../convert-string-to-snake-case.md | 2 +- .../convert-string-to-title-case.md | 2 +- .../string-manipulation/convert-tabs-to-spaces.md | 2 +- .../string-manipulation/count-words-in-a-string.md | 2 +- .../string-manipulation/data-with-prefix.md | 2 +- .../string-manipulation/extract-initials-from-name.md | 2 +- .../string-manipulation/mask-sensitive-information.md | 2 +- .../string-manipulation/pad-string-on-both-sides.md | 2 +- .../javascript/string-manipulation/random-string.md | 2 +- .../string-manipulation/remove-all-whitespace.md | 2 +- .../remove-vowels-from-a-string.md | 2 +- .../javascript/string-manipulation/reverse-string.md | 2 +- .../javascript/string-manipulation/slugify-string.md | 2 +- .../javascript/string-manipulation/truncate-text.md | 2 +- snippets/python/basics/hello-world.md | 2 +- .../calculate-date-difference-in-milliseconds.md | 2 +- .../datetime-utilities/check-if-date-is-a-weekend.md | 2 +- .../datetime-utilities/determine-day-of-the-week.md | 2 +- .../datetime-utilities/generate-date-range-list.md | 2 +- .../get-current-date-and-time-string.md | 2 +- .../get-number-of-days-in-a-month.md | 2 +- .../error-handling/handle-file-not-found-error.md | 2 +- .../retry-function-execution-on-exception.md | 2 +- snippets/python/error-handling/safe-division.md | 2 +- .../validate-input-with-exception-handling.md | 2 +- snippets/python/file-handling/append-to-file.md | 2 +- snippets/python/file-handling/check-if-file-exists.md | 2 +- snippets/python/file-handling/copy-file.md | 2 +- snippets/python/file-handling/delete-file.md | 2 +- snippets/python/file-handling/find-files.md | 2 +- snippets/python/file-handling/get-file-extension.md | 2 +- .../python/file-handling/list-files-in-directory.md | 2 +- snippets/python/file-handling/read-file-in-chunks.md | 2 +- snippets/python/file-handling/read-file-lines.md | 2 +- snippets/python/file-handling/write-to-file.md | 2 +- snippets/python/json-manipulation/filter-json-data.md | 2 +- .../python/json-manipulation/flatten-nested-json.md | 2 +- .../json-manipulation/merge-multiple-json-files.md | 2 +- snippets/python/json-manipulation/read-json-file.md | 2 +- snippets/python/json-manipulation/update-json-file.md | 2 +- .../python/json-manipulation/validate-json-schema.md | 2 +- snippets/python/json-manipulation/write-json-file.md | 2 +- .../list-manipulation/find-duplicates-in-a-list.md | 2 +- .../find-intersection-of-two-lists.md | 2 +- .../find-maximum-difference-in-list.md | 2 +- .../python/list-manipulation/flatten-nested-list.md | 2 +- .../flatten-unevenly-nested-lists.md | 2 +- snippets/python/list-manipulation/partition-list.md | 2 +- .../python/list-manipulation/remove-duplicates.md | 2 +- .../math-and-numbers/calculate-compound-interest.md | 2 +- .../python/math-and-numbers/check-perfect-square.md | 2 +- .../python/math-and-numbers/check-prime-number.md | 2 +- .../math-and-numbers/convert-binary-to-decimal.md | 2 +- snippets/python/math-and-numbers/find-factorial.md | 2 +- .../find-lcm-least-common-multiple.md | 2 +- .../math-and-numbers/solve-quadratic-equation.md | 2 +- .../sqlite-database/create-sqlite-database-table.md | 2 +- .../sqlite-database/insert-data-into-sqlite-table.md | 2 +- .../python/string-manipulation/capitalize-words.md | 2 +- snippets/python/string-manipulation/check-anagram.md | 2 +- .../python/string-manipulation/check-palindrome.md | 2 +- .../convert-snake-case-to-camel-case.md | 2 +- .../string-manipulation/convert-string-to-ascii.md | 2 +- .../string-manipulation/count-character-frequency.md | 2 +- snippets/python/string-manipulation/count-vowels.md | 2 +- snippets/python/string-manipulation/count-words.md | 2 +- .../python/string-manipulation/find-all-substrings.md | 2 +- .../python/string-manipulation/find-longest-word.md | 2 +- .../string-manipulation/find-unique-characters.md | 2 +- .../remove-duplicate-characters.md | 2 +- .../python/string-manipulation/remove-punctuation.md | 2 +- .../string-manipulation/remove-specific-characters.md | 2 +- .../python/string-manipulation/remove-whitespace.md | 2 +- snippets/python/string-manipulation/reverse-string.md | 2 +- .../python/string-manipulation/split-camel-case.md | 2 +- .../python/string-manipulation/truncate-string.md | 2 +- .../convert-bytes-to-human-readable-format.md | 2 +- snippets/python/utilities/generate-random-string.md | 2 +- snippets/python/utilities/measure-execution-time.md | 2 +- snippets/rust/basics/hello-world.md | 2 +- snippets/rust/file-handling/find-files.md | 2 +- snippets/rust/file-handling/read-file-lines.md | 2 +- .../rust/string-manipulation/capitalize-string.md | 2 +- snippets/scss/animations/fade-in-animation.md | 2 +- snippets/scss/animations/slide-in-from-left.md | 2 +- snippets/scss/borders-shadows/border-radius-helper.md | 2 +- snippets/scss/borders-shadows/box-shadow-helper.md | 2 +- snippets/scss/components/primary-button.md | 2 +- snippets/scss/layouts/aspect-ratio.md | 2 +- snippets/scss/layouts/flex-center.md | 2 +- snippets/scss/layouts/grid-container.md | 2 +- snippets/scss/typography/font-import-helper.md | 2 +- snippets/scss/typography/line-clamp-mixin.md | 2 +- snippets/scss/typography/text-gradient.md | 2 +- snippets/scss/typography/text-overflow-ellipsis.md | 2 +- snippets/scss/utilities/clearfix.md | 2 +- snippets/scss/utilities/responsive-breakpoints.md | 2 +- utils/migrateSnippets.js | 11 ++++++++--- 177 files changed, 184 insertions(+), 179 deletions(-) diff --git a/snippets/c/basics/hello-world.md b/snippets/c/basics/hello-world.md index 59f95d6d..c414ab9b 100644 --- a/snippets/c/basics/hello-world.md +++ b/snippets/c/basics/hello-world.md @@ -5,7 +5,7 @@ Author: 0xHouss Tags: c,printing,hello-world,utility --- -``` +```c #include // Includes the input/output library int main() { // Defines the main function diff --git a/snippets/c/mathematical-functions/factorial-function.md b/snippets/c/mathematical-functions/factorial-function.md index c16b279a..3dc0118e 100644 --- a/snippets/c/mathematical-functions/factorial-function.md +++ b/snippets/c/mathematical-functions/factorial-function.md @@ -5,7 +5,7 @@ Author: 0xHouss Tags: c,math,factorial,utility --- -``` +```c int factorial(int x) { int y = 1; diff --git a/snippets/c/mathematical-functions/power-function.md b/snippets/c/mathematical-functions/power-function.md index d23f3224..31846ea1 100644 --- a/snippets/c/mathematical-functions/power-function.md +++ b/snippets/c/mathematical-functions/power-function.md @@ -5,7 +5,7 @@ Author: 0xHouss Tags: c,math,power,utility --- -``` +```c int power(int x, int n) { int y = 1; diff --git a/snippets/cpp/basics/hello-world.md b/snippets/cpp/basics/hello-world.md index b44984d9..be5010f2 100644 --- a/snippets/cpp/basics/hello-world.md +++ b/snippets/cpp/basics/hello-world.md @@ -5,7 +5,7 @@ Author: James-Beans Tags: cpp,printing,hello-world,utility --- -``` +```cpp #include // Includes the input/output stream library int main() { // Defines the main function diff --git a/snippets/cpp/string-manipulation/reverse-string.md b/snippets/cpp/string-manipulation/reverse-string.md index e3fb1d95..58d35829 100644 --- a/snippets/cpp/string-manipulation/reverse-string.md +++ b/snippets/cpp/string-manipulation/reverse-string.md @@ -5,7 +5,7 @@ Author: Vaibhav-kesarwani Tags: cpp,array,reverse,utility --- -``` +```cpp #include #include diff --git a/snippets/cpp/string-manipulation/split-string.md b/snippets/cpp/string-manipulation/split-string.md index c372b62c..450d0c3b 100644 --- a/snippets/cpp/string-manipulation/split-string.md +++ b/snippets/cpp/string-manipulation/split-string.md @@ -5,7 +5,7 @@ Author: saminjay Tags: cpp,string,split,utility --- -``` +```cpp #include #include diff --git a/snippets/css/buttons/3d-button-effect.md b/snippets/css/buttons/3d-button-effect.md index 0d0e43cd..59e4bbc3 100644 --- a/snippets/css/buttons/3d-button-effect.md +++ b/snippets/css/buttons/3d-button-effect.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: css,button,3D,effect --- -``` +```css .button { background-color: #28a745; color: white; diff --git a/snippets/css/buttons/button-hover-effect.md b/snippets/css/buttons/button-hover-effect.md index 03757e30..635c7dec 100644 --- a/snippets/css/buttons/button-hover-effect.md +++ b/snippets/css/buttons/button-hover-effect.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: css,button,hover,transition --- -``` +```css .button { background-color: #007bff; color: white; diff --git a/snippets/css/buttons/macos-button.md b/snippets/css/buttons/macos-button.md index 9e4b5d4c..cfd94671 100644 --- a/snippets/css/buttons/macos-button.md +++ b/snippets/css/buttons/macos-button.md @@ -5,7 +5,7 @@ Author: e3nviction Tags: css,button,macos,hover,transition --- -``` +```css .button { font: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica,; background: #0a85ff; diff --git a/snippets/css/effects/blur-background.md b/snippets/css/effects/blur-background.md index 0a1567d0..41f579a4 100644 --- a/snippets/css/effects/blur-background.md +++ b/snippets/css/effects/blur-background.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: css,blur,background,effects --- -``` +```css .blur-background { backdrop-filter: blur(10px); background: rgba(255, 255, 255, 0.5); diff --git a/snippets/css/effects/hover-glow-effect.md b/snippets/css/effects/hover-glow-effect.md index f07e7db9..b2af4ef7 100644 --- a/snippets/css/effects/hover-glow-effect.md +++ b/snippets/css/effects/hover-glow-effect.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: css,hover,glow,effects --- -``` +```css .glow { background-color: #f39c12; padding: 10px 20px; diff --git a/snippets/css/layouts/css-reset.md b/snippets/css/layouts/css-reset.md index 019a25b2..a5127b11 100644 --- a/snippets/css/layouts/css-reset.md +++ b/snippets/css/layouts/css-reset.md @@ -5,7 +5,7 @@ Author: AmeerMoustafa Tags: css,reset,browser,layout --- -``` +```css * { margin: 0; padding: 0; diff --git a/snippets/css/layouts/equal-width-columns.md b/snippets/css/layouts/equal-width-columns.md index 0d5c8d93..3e1ef183 100644 --- a/snippets/css/layouts/equal-width-columns.md +++ b/snippets/css/layouts/equal-width-columns.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: css,flexbox,columns,layout --- -``` +```css .columns { display: flex; justify-content: space-between; diff --git a/snippets/css/layouts/grid-layout.md b/snippets/css/layouts/grid-layout.md index c28260d5..00c34eaf 100644 --- a/snippets/css/layouts/grid-layout.md +++ b/snippets/css/layouts/grid-layout.md @@ -5,7 +5,7 @@ Author: xshubhamg Tags: css,layout,grid --- -``` +```css .grid-container { display: grid grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); diff --git a/snippets/css/layouts/responsive-design.md b/snippets/css/layouts/responsive-design.md index b5ca5605..f4741e3f 100644 --- a/snippets/css/layouts/responsive-design.md +++ b/snippets/css/layouts/responsive-design.md @@ -5,7 +5,7 @@ Author: kruimol Tags: css,responsive --- -``` +```css /* Phone */ .element { margin: 0 10% diff --git a/snippets/css/layouts/sticky-footer.md b/snippets/css/layouts/sticky-footer.md index e387754c..bf4bd422 100644 --- a/snippets/css/layouts/sticky-footer.md +++ b/snippets/css/layouts/sticky-footer.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: css,layout,footer,sticky --- -``` +```css body { display: flex; flex-direction: column; diff --git a/snippets/css/typography/letter-spacing.md b/snippets/css/typography/letter-spacing.md index 1a68eb6e..df034688 100644 --- a/snippets/css/typography/letter-spacing.md +++ b/snippets/css/typography/letter-spacing.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: css,typography,spacing --- -``` +```css p { letter-spacing: 0.05em; } diff --git a/snippets/css/typography/responsive-font-sizing.md b/snippets/css/typography/responsive-font-sizing.md index e67bc53d..42fc7014 100644 --- a/snippets/css/typography/responsive-font-sizing.md +++ b/snippets/css/typography/responsive-font-sizing.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: css,font,responsive,typography --- -``` +```css h1 { font-size: calc(1.5rem + 2vw); } diff --git a/snippets/html/basic-layouts/grid-layout-with-navigation.md b/snippets/html/basic-layouts/grid-layout-with-navigation.md index 06568e25..7a2090ad 100644 --- a/snippets/html/basic-layouts/grid-layout-with-navigation.md +++ b/snippets/html/basic-layouts/grid-layout-with-navigation.md @@ -5,7 +5,7 @@ Author: GreenMan36 Tags: html,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 4a9d1b87..6cb30dd1 100644 --- a/snippets/html/basic-layouts/sticky-header-footer-layout.md +++ b/snippets/html/basic-layouts/sticky-header-footer-layout.md @@ -5,7 +5,7 @@ Author: GreenMan36 Tags: html,css,layout,sticky,flexbox,viewport --- -``` +```html diff --git a/snippets/javascript/array-manipulation/flatten-array.md b/snippets/javascript/array-manipulation/flatten-array.md index 0845a975..a92e37c2 100644 --- a/snippets/javascript/array-manipulation/flatten-array.md +++ b/snippets/javascript/array-manipulation/flatten-array.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: javascript,array,flatten,utility --- -``` +```js const flattenArray = (arr) => arr.flat(Infinity); // Usage: diff --git a/snippets/javascript/array-manipulation/remove-duplicates.md b/snippets/javascript/array-manipulation/remove-duplicates.md index 91f28a99..6c576c01 100644 --- a/snippets/javascript/array-manipulation/remove-duplicates.md +++ b/snippets/javascript/array-manipulation/remove-duplicates.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: javascript,array,deduplicate,utility --- -``` +```js const removeDuplicates = (arr) => [...new Set(arr)]; // Usage: diff --git a/snippets/javascript/array-manipulation/shuffle-array.md b/snippets/javascript/array-manipulation/shuffle-array.md index aaeecc68..0a1a0379 100644 --- a/snippets/javascript/array-manipulation/shuffle-array.md +++ b/snippets/javascript/array-manipulation/shuffle-array.md @@ -5,7 +5,7 @@ Author: loxt-nixo Tags: javascript,array,shuffle,utility --- -``` +```js function shuffleArray(array) { for (let i = array.length - 1; i >= 0; i--) { const j = Math.floor(Math.random() * (i + 1)); diff --git a/snippets/javascript/array-manipulation/zip-arrays.md b/snippets/javascript/array-manipulation/zip-arrays.md index 0f3893e5..673b83d0 100644 --- a/snippets/javascript/array-manipulation/zip-arrays.md +++ b/snippets/javascript/array-manipulation/zip-arrays.md @@ -5,7 +5,7 @@ Author: Swaraj-Singh-30 Tags: javascript,array,utility,map --- -``` +```js const zip = (arr1, arr2) => arr1.map((value, index) => [value, arr2[index]]); // Usage: diff --git a/snippets/javascript/basics/hello-world.md b/snippets/javascript/basics/hello-world.md index b435818d..bfa646cc 100644 --- a/snippets/javascript/basics/hello-world.md +++ b/snippets/javascript/basics/hello-world.md @@ -5,6 +5,6 @@ Author: James-Beans Tags: javascript,printing,hello-world,utility --- -``` +```js console.log("Hello, World!"); // Prints Hello, World! to the console ``` 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 index 12220ccd..bd4436f7 100644 --- a/snippets/javascript/date-and-time/add-days-to-a-date.md +++ b/snippets/javascript/date-and-time/add-days-to-a-date.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,date,add-days,utility --- -``` +```js const addDays = (date, days) => { const result = new Date(date); result.setDate(result.getDate() + days); diff --git a/snippets/javascript/date-and-time/check-leap-year.md b/snippets/javascript/date-and-time/check-leap-year.md index cafcbaca..7720e89e 100644 --- a/snippets/javascript/date-and-time/check-leap-year.md +++ b/snippets/javascript/date-and-time/check-leap-year.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,date,leap-year,utility --- -``` +```js const isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; // Usage: diff --git a/snippets/javascript/date-and-time/format-date.md b/snippets/javascript/date-and-time/format-date.md index c7d2a76a..fad01ad2 100644 --- a/snippets/javascript/date-and-time/format-date.md +++ b/snippets/javascript/date-and-time/format-date.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: javascript,date,format,utility --- -``` +```js const formatDate = (date) => date.toISOString().split('T')[0]; // Usage: diff --git a/snippets/javascript/date-and-time/get-current-timestamp.md b/snippets/javascript/date-and-time/get-current-timestamp.md index fcb627c0..fb9fd34c 100644 --- a/snippets/javascript/date-and-time/get-current-timestamp.md +++ b/snippets/javascript/date-and-time/get-current-timestamp.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,date,timestamp,utility --- -``` +```js const getCurrentTimestamp = () => Date.now(); // Usage: 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 a3f7a86d..3c6226a4 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 @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,date,day-of-year,utility --- -``` +```js const getDayOfYear = (date) => { const startOfYear = new Date(date.getFullYear(), 0, 0); const diff = date - startOfYear + (startOfYear.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000; 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 096e5fec..4a083aa5 100644 --- a/snippets/javascript/date-and-time/get-days-in-month.md +++ b/snippets/javascript/date-and-time/get-days-in-month.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,date,days-in-month,utility --- -``` +```js const getDaysInMonth = (year, month) => new Date(year, month + 1, 0).getDate(); // Usage: diff --git a/snippets/javascript/date-and-time/get-time-difference.md b/snippets/javascript/date-and-time/get-time-difference.md index 64b26192..c0193221 100644 --- a/snippets/javascript/date-and-time/get-time-difference.md +++ b/snippets/javascript/date-and-time/get-time-difference.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: javascript,date,time-difference,utility --- -``` +```js const getTimeDifference = (date1, date2) => { const diff = Math.abs(date2 - date1); return Math.ceil(diff / (1000 * 60 * 60 * 24)); diff --git a/snippets/javascript/date-and-time/relative-time-formatter.md b/snippets/javascript/date-and-time/relative-time-formatter.md index 5a6b41b3..83130cb4 100644 --- a/snippets/javascript/date-and-time/relative-time-formatter.md +++ b/snippets/javascript/date-and-time/relative-time-formatter.md @@ -5,7 +5,7 @@ Author: Yugveer06 Tags: javascript,date,time,relative,future,past,utility --- -``` +```js const getRelativeTime = (date) => { const now = Date.now(); const diff = date.getTime() - now; 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 157fc0f1..533b7159 100644 --- a/snippets/javascript/date-and-time/start-of-the-day.md +++ b/snippets/javascript/date-and-time/start-of-the-day.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,date,start-of-day,utility --- -``` +```js const startOfDay = (date) => new Date(date.setHours(0, 0, 0, 0)); // Usage: diff --git a/snippets/javascript/dom-manipulation/change-element-style.md b/snippets/javascript/dom-manipulation/change-element-style.md index 70759421..a37eaa82 100644 --- a/snippets/javascript/dom-manipulation/change-element-style.md +++ b/snippets/javascript/dom-manipulation/change-element-style.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,dom,style,utility --- -``` +```js const changeElementStyle = (element, styleObj) => { Object.entries(styleObj).forEach(([property, value]) => { element.style[property] = value; diff --git a/snippets/javascript/dom-manipulation/get-element-position.md b/snippets/javascript/dom-manipulation/get-element-position.md index 23ae0b8c..cd7ce3c8 100644 --- a/snippets/javascript/dom-manipulation/get-element-position.md +++ b/snippets/javascript/dom-manipulation/get-element-position.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,dom,position,utility --- -``` +```js const getElementPosition = (element) => { const rect = element.getBoundingClientRect(); return { x: rect.left, y: rect.top }; diff --git a/snippets/javascript/dom-manipulation/remove-element.md b/snippets/javascript/dom-manipulation/remove-element.md index d59f4dbe..9cfe9084 100644 --- a/snippets/javascript/dom-manipulation/remove-element.md +++ b/snippets/javascript/dom-manipulation/remove-element.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,dom,remove,utility --- -``` +```js const removeElement = (element) => { if (element && element.parentNode) { element.parentNode.removeChild(element); diff --git a/snippets/javascript/dom-manipulation/smooth-scroll-to-element.md b/snippets/javascript/dom-manipulation/smooth-scroll-to-element.md index c66bbd84..b6900196 100644 --- a/snippets/javascript/dom-manipulation/smooth-scroll-to-element.md +++ b/snippets/javascript/dom-manipulation/smooth-scroll-to-element.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: javascript,dom,scroll,ui --- -``` +```js const smoothScroll = (element) => { element.scrollIntoView({ behavior: 'smooth' }); }; diff --git a/snippets/javascript/dom-manipulation/toggle-class.md b/snippets/javascript/dom-manipulation/toggle-class.md index abb28985..08ee2f38 100644 --- a/snippets/javascript/dom-manipulation/toggle-class.md +++ b/snippets/javascript/dom-manipulation/toggle-class.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: javascript,dom,class,utility --- -``` +```js const toggleClass = (element, className) => { element.classList.toggle(className); }; diff --git a/snippets/javascript/function-utilities/compose-functions.md b/snippets/javascript/function-utilities/compose-functions.md index e061777c..2de032d8 100644 --- a/snippets/javascript/function-utilities/compose-functions.md +++ b/snippets/javascript/function-utilities/compose-functions.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,function,compose,utility --- -``` +```js const compose = (...funcs) => (initialValue) => { return funcs.reduce((acc, func) => func(acc), initialValue); }; diff --git a/snippets/javascript/function-utilities/curry-function.md b/snippets/javascript/function-utilities/curry-function.md index 762605dc..89a01b0a 100644 --- a/snippets/javascript/function-utilities/curry-function.md +++ b/snippets/javascript/function-utilities/curry-function.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,curry,function,utility --- -``` +```js const curry = (func) => { const curried = (...args) => { if (args.length >= func.length) { diff --git a/snippets/javascript/function-utilities/debounce-function.md b/snippets/javascript/function-utilities/debounce-function.md index 361b4360..d73117d1 100644 --- a/snippets/javascript/function-utilities/debounce-function.md +++ b/snippets/javascript/function-utilities/debounce-function.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: javascript,utility,debounce,performance --- -``` +```js const debounce = (func, delay) => { let timeout; diff --git a/snippets/javascript/function-utilities/get-contrast-color.md b/snippets/javascript/function-utilities/get-contrast-color.md index 057ae383..b5ab4374 100644 --- a/snippets/javascript/function-utilities/get-contrast-color.md +++ b/snippets/javascript/function-utilities/get-contrast-color.md @@ -5,7 +5,7 @@ Author: yaya12085 Tags: javascript,color,hex,contrast,brightness,utility --- -``` +```js const getContrastColor = (hexColor) => { // Expand short hex color to full format if (hexColor.length === 4) { diff --git a/snippets/javascript/function-utilities/memoize-function.md b/snippets/javascript/function-utilities/memoize-function.md index c30a5888..dbda561b 100644 --- a/snippets/javascript/function-utilities/memoize-function.md +++ b/snippets/javascript/function-utilities/memoize-function.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,memoization,optimization,utility --- -``` +```js const memoize = (func) => { const cache = new Map(); return (...args) => { diff --git a/snippets/javascript/function-utilities/once-function.md b/snippets/javascript/function-utilities/once-function.md index 2e2e6714..3eb756b3 100644 --- a/snippets/javascript/function-utilities/once-function.md +++ b/snippets/javascript/function-utilities/once-function.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,function,once,utility --- -``` +```js const once = (func) => { let called = false; return (...args) => { diff --git a/snippets/javascript/function-utilities/rate-limit-function.md b/snippets/javascript/function-utilities/rate-limit-function.md index 2fc61d96..0976c971 100644 --- a/snippets/javascript/function-utilities/rate-limit-function.md +++ b/snippets/javascript/function-utilities/rate-limit-function.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,function,rate-limiting,utility --- -``` +```js const rateLimit = (func, limit, timeWindow) => { let queue = []; setInterval(() => { diff --git a/snippets/javascript/function-utilities/repeat-function-invocation.md b/snippets/javascript/function-utilities/repeat-function-invocation.md index 36bb0e92..7c66ed84 100644 --- a/snippets/javascript/function-utilities/repeat-function-invocation.md +++ b/snippets/javascript/function-utilities/repeat-function-invocation.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: javascript,function,repeat,utility --- -``` +```js const times = (func, n) => { Array.from(Array(n)).forEach(() => { func(); diff --git a/snippets/javascript/function-utilities/sleep-function.md b/snippets/javascript/function-utilities/sleep-function.md index 120d2410..3964270c 100644 --- a/snippets/javascript/function-utilities/sleep-function.md +++ b/snippets/javascript/function-utilities/sleep-function.md @@ -5,7 +5,7 @@ Author: 0xHouss Tags: javascript,sleep,delay,utility,promises --- -``` +```js const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); // Usage: diff --git a/snippets/javascript/function-utilities/throttle-function.md b/snippets/javascript/function-utilities/throttle-function.md index 37229cc7..9d8c1f95 100644 --- a/snippets/javascript/function-utilities/throttle-function.md +++ b/snippets/javascript/function-utilities/throttle-function.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: javascript,utility,throttle,performance --- -``` +```js const throttle = (func, limit) => { let lastFunc; let lastRan; diff --git a/snippets/javascript/local-storage/add-item-to-localstorage.md b/snippets/javascript/local-storage/add-item-to-localstorage.md index c0b9799e..cb27da30 100644 --- a/snippets/javascript/local-storage/add-item-to-localstorage.md +++ b/snippets/javascript/local-storage/add-item-to-localstorage.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: javascript,localStorage,storage,utility --- -``` +```js const addToLocalStorage = (key, value) => { localStorage.setItem(key, JSON.stringify(value)); }; 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 25dd1287..389beabb 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 @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,localStorage,storage,utility --- -``` +```js const isItemInLocalStorage = (key) => { return localStorage.getItem(key) !== null; }; diff --git a/snippets/javascript/local-storage/clear-all-localstorage.md b/snippets/javascript/local-storage/clear-all-localstorage.md index bc884994..da1c8e6f 100644 --- a/snippets/javascript/local-storage/clear-all-localstorage.md +++ b/snippets/javascript/local-storage/clear-all-localstorage.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: javascript,localStorage,storage,utility --- -``` +```js const clearLocalStorage = () => { localStorage.clear(); }; diff --git a/snippets/javascript/local-storage/retrieve-item-from-localstorage.md b/snippets/javascript/local-storage/retrieve-item-from-localstorage.md index 96da181b..003745f8 100644 --- a/snippets/javascript/local-storage/retrieve-item-from-localstorage.md +++ b/snippets/javascript/local-storage/retrieve-item-from-localstorage.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: javascript,localStorage,storage,utility --- -``` +```js const getFromLocalStorage = (key) => { const item = localStorage.getItem(key); return item ? JSON.parse(item) : null; diff --git a/snippets/javascript/number-formatting/convert-number-to-currency.md b/snippets/javascript/number-formatting/convert-number-to-currency.md index 49df5e02..e1c49de3 100644 --- a/snippets/javascript/number-formatting/convert-number-to-currency.md +++ b/snippets/javascript/number-formatting/convert-number-to-currency.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,number,currency,utility --- -``` +```js const convertToCurrency = (num, locale = 'en-US', currency = 'USD') => { return new Intl.NumberFormat(locale, { style: 'currency', 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 94ef8d16..1ed5bf81 100644 --- a/snippets/javascript/number-formatting/convert-number-to-roman-numerals.md +++ b/snippets/javascript/number-formatting/convert-number-to-roman-numerals.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,number,roman,utility --- -``` +```js const numberToRoman = (num) => { const romanNumerals = { 1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L', diff --git a/snippets/javascript/number-formatting/convert-to-scientific-notation.md b/snippets/javascript/number-formatting/convert-to-scientific-notation.md index b65e922a..631e9af2 100644 --- a/snippets/javascript/number-formatting/convert-to-scientific-notation.md +++ b/snippets/javascript/number-formatting/convert-to-scientific-notation.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,number,scientific,utility --- -``` +```js const toScientificNotation = (num) => { if (isNaN(num)) { throw new Error('Input must be a number'); diff --git a/snippets/javascript/number-formatting/format-number-with-commas.md b/snippets/javascript/number-formatting/format-number-with-commas.md index 5851fa49..a3eea426 100644 --- a/snippets/javascript/number-formatting/format-number-with-commas.md +++ b/snippets/javascript/number-formatting/format-number-with-commas.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,number,format,utility --- -``` +```js const formatNumberWithCommas = (num) => { return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); }; diff --git a/snippets/javascript/number-formatting/number-formatter.md b/snippets/javascript/number-formatting/number-formatter.md index ba7cfade..ca94810a 100644 --- a/snippets/javascript/number-formatting/number-formatter.md +++ b/snippets/javascript/number-formatting/number-formatter.md @@ -5,7 +5,7 @@ Author: realvishalrana Tags: javascript,number,format,utility --- -``` +```js const nFormatter = (num) => { if (!num) return; num = parseFloat(num.toString().replace(/[^0-9.]/g, '')); diff --git a/snippets/javascript/number-formatting/number-to-words-converter.md b/snippets/javascript/number-formatting/number-to-words-converter.md index 9f08a5a8..3e319d26 100644 --- a/snippets/javascript/number-formatting/number-to-words-converter.md +++ b/snippets/javascript/number-formatting/number-to-words-converter.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,number,words,utility --- -``` +```js const numberToWords = (num) => { const below20 = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']; const tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']; 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 7287b725..fbc75281 100644 --- a/snippets/javascript/object-manipulation/check-if-object-is-empty.md +++ b/snippets/javascript/object-manipulation/check-if-object-is-empty.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,object,check,empty --- -``` +```js function isEmptyObject(obj) { return Object.keys(obj).length === 0; } diff --git a/snippets/javascript/object-manipulation/clone-object-shallowly.md b/snippets/javascript/object-manipulation/clone-object-shallowly.md index 20f70dac..82feef8b 100644 --- a/snippets/javascript/object-manipulation/clone-object-shallowly.md +++ b/snippets/javascript/object-manipulation/clone-object-shallowly.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,object,clone,shallow --- -``` +```js function shallowClone(obj) { return { ...obj }; } diff --git a/snippets/javascript/object-manipulation/compare-two-objects-shallowly.md b/snippets/javascript/object-manipulation/compare-two-objects-shallowly.md index 1d52af16..ca020fd6 100644 --- a/snippets/javascript/object-manipulation/compare-two-objects-shallowly.md +++ b/snippets/javascript/object-manipulation/compare-two-objects-shallowly.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,object,compare,shallow --- -``` +```js function shallowEqual(obj1, obj2) { const keys1 = Object.keys(obj1); const keys2 = Object.keys(obj2); 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 29667870..6a746040 100644 --- a/snippets/javascript/object-manipulation/convert-object-to-query-string.md +++ b/snippets/javascript/object-manipulation/convert-object-to-query-string.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,object,query string,url --- -``` +```js function toQueryString(obj) { return Object.entries(obj) .map(([key, value]) => encodeURIComponent(key) + '=' + encodeURIComponent(value)) diff --git a/snippets/javascript/object-manipulation/count-properties-in-object.md b/snippets/javascript/object-manipulation/count-properties-in-object.md index b3b9a41d..00080128 100644 --- a/snippets/javascript/object-manipulation/count-properties-in-object.md +++ b/snippets/javascript/object-manipulation/count-properties-in-object.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,object,count,properties --- -``` +```js function countProperties(obj) { return Object.keys(obj).length; } diff --git a/snippets/javascript/object-manipulation/filter-object.md b/snippets/javascript/object-manipulation/filter-object.md index 1acffb11..dd604527 100644 --- a/snippets/javascript/object-manipulation/filter-object.md +++ b/snippets/javascript/object-manipulation/filter-object.md @@ -5,7 +5,7 @@ Author: realvishalrana Tags: javascript,object,filter,utility --- -``` +```js export const filterObject = (object = {}) => Object.fromEntries( Object.entries(object) diff --git a/snippets/javascript/object-manipulation/flatten-nested-object.md b/snippets/javascript/object-manipulation/flatten-nested-object.md index 84971c91..4e85541f 100644 --- a/snippets/javascript/object-manipulation/flatten-nested-object.md +++ b/snippets/javascript/object-manipulation/flatten-nested-object.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,object,flatten,utility --- -``` +```js function flattenObject(obj, prefix = '') { return Object.keys(obj).reduce((acc, key) => { const fullPath = prefix ? `${prefix}.${key}` : key; diff --git a/snippets/javascript/object-manipulation/freeze-object.md b/snippets/javascript/object-manipulation/freeze-object.md index 1b846a07..99a1fa92 100644 --- a/snippets/javascript/object-manipulation/freeze-object.md +++ b/snippets/javascript/object-manipulation/freeze-object.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,object,freeze,immutable --- -``` +```js function freezeObject(obj) { return Object.freeze(obj); } diff --git a/snippets/javascript/object-manipulation/get-nested-value.md b/snippets/javascript/object-manipulation/get-nested-value.md index 221d4c7b..6d3278e9 100644 --- a/snippets/javascript/object-manipulation/get-nested-value.md +++ b/snippets/javascript/object-manipulation/get-nested-value.md @@ -5,7 +5,7 @@ Author: realvishalrana Tags: javascript,object,nested,utility --- -``` +```js const getNestedValue = (obj, path) => { const keys = path.split('.'); return keys.reduce((currentObject, key) => { 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 da924034..b5e54f27 100644 --- a/snippets/javascript/object-manipulation/invert-object-keys-and-values.md +++ b/snippets/javascript/object-manipulation/invert-object-keys-and-values.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,object,invert,utility --- -``` +```js function invertObject(obj) { return Object.fromEntries( Object.entries(obj).map(([key, value]) => [value, key]) diff --git a/snippets/javascript/object-manipulation/merge-objects-deeply.md b/snippets/javascript/object-manipulation/merge-objects-deeply.md index 44a32963..904458d6 100644 --- a/snippets/javascript/object-manipulation/merge-objects-deeply.md +++ b/snippets/javascript/object-manipulation/merge-objects-deeply.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,object,merge,deep --- -``` +```js function deepMerge(...objects) { return objects.reduce((acc, obj) => { Object.keys(obj).forEach(key => { diff --git a/snippets/javascript/object-manipulation/omit-keys-from-object.md b/snippets/javascript/object-manipulation/omit-keys-from-object.md index 075a4f9a..d39f1483 100644 --- a/snippets/javascript/object-manipulation/omit-keys-from-object.md +++ b/snippets/javascript/object-manipulation/omit-keys-from-object.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,object,omit,utility --- -``` +```js function omitKeys(obj, keys) { return Object.fromEntries( Object.entries(obj).filter(([key]) => !keys.includes(key)) diff --git a/snippets/javascript/object-manipulation/pick-keys-from-object.md b/snippets/javascript/object-manipulation/pick-keys-from-object.md index aa00b191..42f2ff49 100644 --- a/snippets/javascript/object-manipulation/pick-keys-from-object.md +++ b/snippets/javascript/object-manipulation/pick-keys-from-object.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,object,pick,utility --- -``` +```js function pickKeys(obj, keys) { return Object.fromEntries( Object.entries(obj).filter(([key]) => keys.includes(key)) diff --git a/snippets/javascript/object-manipulation/unique-by-key.md b/snippets/javascript/object-manipulation/unique-by-key.md index d8ed12fb..c4e5c184 100644 --- a/snippets/javascript/object-manipulation/unique-by-key.md +++ b/snippets/javascript/object-manipulation/unique-by-key.md @@ -5,7 +5,7 @@ Author: realvishalrana Tags: javascript,array,unique,utility --- -``` +```js const uniqueByKey = (key, arr) => arr.filter((obj, index, self) => index === self.findIndex((t) => t?.[key] === obj?.[key])); diff --git a/snippets/javascript/regular-expression/regex-match-utility-function.md b/snippets/javascript/regular-expression/regex-match-utility-function.md index fd0778c3..7be32eca 100644 --- a/snippets/javascript/regular-expression/regex-match-utility-function.md +++ b/snippets/javascript/regular-expression/regex-match-utility-function.md @@ -5,7 +5,7 @@ Author: aumirza Tags: javascript,regex --- -``` +```js /** * @param {string | number} input * The input string to match diff --git a/snippets/javascript/string-manipulation/capitalize-string.md b/snippets/javascript/string-manipulation/capitalize-string.md index 367530a7..e6f32f7c 100644 --- a/snippets/javascript/string-manipulation/capitalize-string.md +++ b/snippets/javascript/string-manipulation/capitalize-string.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: javascript,string,capitalize,utility --- -``` +```js const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1); // Usage: 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 924f4999..d6978bb9 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 @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,check,palindrome,string --- -``` +```js function isPalindrome(str) { const cleanStr = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase(); return cleanStr === cleanStr.split('').reverse().join(''); 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 3103c6c8..6981ff7e 100644 --- a/snippets/javascript/string-manipulation/convert-string-to-camel-case.md +++ b/snippets/javascript/string-manipulation/convert-string-to-camel-case.md @@ -5,7 +5,7 @@ Author: aumirza Tags: string,case,camelCase --- -``` +```js function toCamelCase(str) { return str.replace(/\W+(.)/g, (match, chr) => chr.toUpperCase()); } 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 369915ff..a4ae72c0 100644 --- a/snippets/javascript/string-manipulation/convert-string-to-param-case.md +++ b/snippets/javascript/string-manipulation/convert-string-to-param-case.md @@ -5,7 +5,7 @@ Author: aumirza Tags: string,case,paramCase --- -``` +```js function toParamCase(str) { return str.toLowerCase().replace(/\s+/g, '-'); } 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 d303a046..b1994ff4 100644 --- a/snippets/javascript/string-manipulation/convert-string-to-pascal-case.md +++ b/snippets/javascript/string-manipulation/convert-string-to-pascal-case.md @@ -5,7 +5,7 @@ Author: aumirza Tags: string,case,pascalCase --- -``` +```js function toPascalCase(str) { return str.replace(/\b\w/g, (s) => s.toUpperCase()).replace(/\W+(.)/g, (match, chr) => chr.toUpperCase()); } 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 ce177a10..b75399b2 100644 --- a/snippets/javascript/string-manipulation/convert-string-to-snake-case.md +++ b/snippets/javascript/string-manipulation/convert-string-to-snake-case.md @@ -5,7 +5,7 @@ Author: axorax Tags: string,case,snake_case --- -``` +```js function toSnakeCase(str) { return str.replace(/([a-z])([A-Z])/g, '$1_$2') .replace(/\s+/g, '_') 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 56f1916a..b724c0dd 100644 --- a/snippets/javascript/string-manipulation/convert-string-to-title-case.md +++ b/snippets/javascript/string-manipulation/convert-string-to-title-case.md @@ -5,7 +5,7 @@ Author: aumirza Tags: string,case,titleCase --- -``` +```js function toTitleCase(str) { return str.toLowerCase().replace(/\b\w/g, (s) => s.toUpperCase()); } diff --git a/snippets/javascript/string-manipulation/convert-tabs-to-spaces.md b/snippets/javascript/string-manipulation/convert-tabs-to-spaces.md index 2a5d97d7..c3022a6e 100644 --- a/snippets/javascript/string-manipulation/convert-tabs-to-spaces.md +++ b/snippets/javascript/string-manipulation/convert-tabs-to-spaces.md @@ -5,7 +5,7 @@ Author: axorax Tags: string,tabs,spaces --- -``` +```js function tabsToSpaces(str, spacesPerTab = 4) { return str.replace(/\t/g, ' '.repeat(spacesPerTab)); } 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 8a3429a3..c5614f57 100644 --- a/snippets/javascript/string-manipulation/count-words-in-a-string.md +++ b/snippets/javascript/string-manipulation/count-words-in-a-string.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,string,manipulation,word count,count --- -``` +```js function countWords(str) { return str.trim().split(/\s+/).length; } diff --git a/snippets/javascript/string-manipulation/data-with-prefix.md b/snippets/javascript/string-manipulation/data-with-prefix.md index 99d71870..35194faa 100644 --- a/snippets/javascript/string-manipulation/data-with-prefix.md +++ b/snippets/javascript/string-manipulation/data-with-prefix.md @@ -5,7 +5,7 @@ Author: realvishalrana Tags: javascript,data,utility --- -``` +```js const dataWithPrefix = (data, fallback = '-', prefix = '', postfix = '') => { return data ? `${prefix}${data}${postfix}` : fallback; }; diff --git a/snippets/javascript/string-manipulation/extract-initials-from-name.md b/snippets/javascript/string-manipulation/extract-initials-from-name.md index 33e9a98e..284eeb62 100644 --- a/snippets/javascript/string-manipulation/extract-initials-from-name.md +++ b/snippets/javascript/string-manipulation/extract-initials-from-name.md @@ -5,7 +5,7 @@ Author: axorax Tags: string,initials,name --- -``` +```js function getInitials(name) { return name.split(' ').map(part => part.charAt(0).toUpperCase()).join(''); } diff --git a/snippets/javascript/string-manipulation/mask-sensitive-information.md b/snippets/javascript/string-manipulation/mask-sensitive-information.md index c9733859..6da405f6 100644 --- a/snippets/javascript/string-manipulation/mask-sensitive-information.md +++ b/snippets/javascript/string-manipulation/mask-sensitive-information.md @@ -5,7 +5,7 @@ Author: axorax Tags: string,mask,sensitive --- -``` +```js function maskSensitiveInfo(str, visibleCount = 4, maskChar = '*') { return str.slice(0, visibleCount) + maskChar.repeat(Math.max(0, str.length - visibleCount)); } 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 2763564a..4689d661 100644 --- a/snippets/javascript/string-manipulation/pad-string-on-both-sides.md +++ b/snippets/javascript/string-manipulation/pad-string-on-both-sides.md @@ -5,7 +5,7 @@ Author: axorax Tags: string,pad,manipulation --- -``` +```js function padString(str, length, char = ' ') { const totalPad = length - str.length; const padStart = Math.floor(totalPad / 2); diff --git a/snippets/javascript/string-manipulation/random-string.md b/snippets/javascript/string-manipulation/random-string.md index b0c84161..a78faad6 100644 --- a/snippets/javascript/string-manipulation/random-string.md +++ b/snippets/javascript/string-manipulation/random-string.md @@ -5,7 +5,7 @@ Author: kruimol Tags: javascript,function,random --- -``` +```js function makeid(length, characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') { return Array.from({ length }, () => characters.charAt(Math.floor(Math.random() * characters.length))).join(''); } diff --git a/snippets/javascript/string-manipulation/remove-all-whitespace.md b/snippets/javascript/string-manipulation/remove-all-whitespace.md index 2b945f76..1c8c7074 100644 --- a/snippets/javascript/string-manipulation/remove-all-whitespace.md +++ b/snippets/javascript/string-manipulation/remove-all-whitespace.md @@ -5,7 +5,7 @@ Author: axorax Tags: javascript,string,whitespace --- -``` +```js function removeWhitespace(str) { return str.replace(/\s+/g, ''); } 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 320fe24e..a47ec16e 100644 --- a/snippets/javascript/string-manipulation/remove-vowels-from-a-string.md +++ b/snippets/javascript/string-manipulation/remove-vowels-from-a-string.md @@ -5,7 +5,7 @@ Author: axorax Tags: string,remove,vowels --- -``` +```js function removeVowels(str) { return str.replace(/[aeiouAEIOU]/g, ''); } diff --git a/snippets/javascript/string-manipulation/reverse-string.md b/snippets/javascript/string-manipulation/reverse-string.md index a7c1d9f1..ce55448d 100644 --- a/snippets/javascript/string-manipulation/reverse-string.md +++ b/snippets/javascript/string-manipulation/reverse-string.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: javascript,string,reverse,utility --- -``` +```js const reverseString = (str) => str.split('').reverse().join(''); // Usage: diff --git a/snippets/javascript/string-manipulation/slugify-string.md b/snippets/javascript/string-manipulation/slugify-string.md index b28c249d..c3536639 100644 --- a/snippets/javascript/string-manipulation/slugify-string.md +++ b/snippets/javascript/string-manipulation/slugify-string.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: javascript,string,slug,utility --- -``` +```js const slugify = (string, separator = "-") => { return string .toString() // Cast to string (optional) diff --git a/snippets/javascript/string-manipulation/truncate-text.md b/snippets/javascript/string-manipulation/truncate-text.md index eeffee54..84437145 100644 --- a/snippets/javascript/string-manipulation/truncate-text.md +++ b/snippets/javascript/string-manipulation/truncate-text.md @@ -5,7 +5,7 @@ Author: realvishalrana Tags: javascript,string,truncate,utility,text --- -``` +```js const truncateText = (text = '', maxLength = 50) => { return `${text.slice(0, maxLength)}${text.length >= maxLength ? '...' : ''}`; }; diff --git a/snippets/python/basics/hello-world.md b/snippets/python/basics/hello-world.md index 25131882..e94d322b 100644 --- a/snippets/python/basics/hello-world.md +++ b/snippets/python/basics/hello-world.md @@ -5,6 +5,6 @@ Author: James-Beans Tags: python,printing,hello-world,utility --- -``` +```py print("Hello, World!") # Prints Hello, World! to the terminal. ``` 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 9550ee4e..350315b1 100644 --- a/snippets/python/datetime-utilities/calculate-date-difference-in-milliseconds.md +++ b/snippets/python/datetime-utilities/calculate-date-difference-in-milliseconds.md @@ -5,7 +5,7 @@ Author: e3nviction Tags: python,datetime,utility --- -``` +```py from datetime import datetime def date_difference_in_millis(date1, date2): 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 3aef4357..70c1475c 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 @@ -5,7 +5,7 @@ Author: axorax Tags: python,datetime,weekend,utility --- -``` +```py from datetime import datetime def is_weekend(date): diff --git a/snippets/python/datetime-utilities/determine-day-of-the-week.md b/snippets/python/datetime-utilities/determine-day-of-the-week.md index 9e39e042..71ae5dfc 100644 --- a/snippets/python/datetime-utilities/determine-day-of-the-week.md +++ b/snippets/python/datetime-utilities/determine-day-of-the-week.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,datetime,weekday,utility --- -``` +```py from datetime import datetime def get_day_of_week(date): diff --git a/snippets/python/datetime-utilities/generate-date-range-list.md b/snippets/python/datetime-utilities/generate-date-range-list.md index a7cd5abe..36508709 100644 --- a/snippets/python/datetime-utilities/generate-date-range-list.md +++ b/snippets/python/datetime-utilities/generate-date-range-list.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,datetime,range,utility --- -``` +```py from datetime import datetime, timedelta def generate_date_range(start_date, end_date): diff --git a/snippets/python/datetime-utilities/get-current-date-and-time-string.md b/snippets/python/datetime-utilities/get-current-date-and-time-string.md index feb9b5a0..22e6bf99 100644 --- a/snippets/python/datetime-utilities/get-current-date-and-time-string.md +++ b/snippets/python/datetime-utilities/get-current-date-and-time-string.md @@ -5,7 +5,7 @@ Author: e3nviction Tags: python,datetime,utility --- -``` +```py from datetime import datetime def get_current_datetime_string(): 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 579d96fa..9e1053a5 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 @@ -5,7 +5,7 @@ Author: axorax Tags: python,datetime,calendar,utility --- -``` +```py from calendar import monthrange from datetime import datetime diff --git a/snippets/python/error-handling/handle-file-not-found-error.md b/snippets/python/error-handling/handle-file-not-found-error.md index a4bfbd0d..d2d720a2 100644 --- a/snippets/python/error-handling/handle-file-not-found-error.md +++ b/snippets/python/error-handling/handle-file-not-found-error.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,error-handling,file,utility --- -``` +```py def read_file_safe(filepath): try: with open(filepath, 'r') as file: 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 d0f2b642..0723ee37 100644 --- a/snippets/python/error-handling/retry-function-execution-on-exception.md +++ b/snippets/python/error-handling/retry-function-execution-on-exception.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,error-handling,retry,utility --- -``` +```py import time def retry(func, retries=3, delay=1): diff --git a/snippets/python/error-handling/safe-division.md b/snippets/python/error-handling/safe-division.md index f86f6201..8d53bf57 100644 --- a/snippets/python/error-handling/safe-division.md +++ b/snippets/python/error-handling/safe-division.md @@ -5,7 +5,7 @@ Author: e3nviction Tags: python,error-handling,division,utility --- -``` +```py def safe_divide(a, b): try: return a / b diff --git a/snippets/python/error-handling/validate-input-with-exception-handling.md b/snippets/python/error-handling/validate-input-with-exception-handling.md index 6ce61e38..ae1ea01e 100644 --- a/snippets/python/error-handling/validate-input-with-exception-handling.md +++ b/snippets/python/error-handling/validate-input-with-exception-handling.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,error-handling,validation,utility --- -``` +```py def validate_positive_integer(input_value): try: value = int(input_value) diff --git a/snippets/python/file-handling/append-to-file.md b/snippets/python/file-handling/append-to-file.md index 0d9b1038..759c2d82 100644 --- a/snippets/python/file-handling/append-to-file.md +++ b/snippets/python/file-handling/append-to-file.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,file,append,utility --- -``` +```py def append_to_file(filepath, content): with open(filepath, 'a') as file: file.write(content + '\n') diff --git a/snippets/python/file-handling/check-if-file-exists.md b/snippets/python/file-handling/check-if-file-exists.md index ac1a7c46..3f109a06 100644 --- a/snippets/python/file-handling/check-if-file-exists.md +++ b/snippets/python/file-handling/check-if-file-exists.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,file,exists,check,utility --- -``` +```py import os def file_exists(filepath): diff --git a/snippets/python/file-handling/copy-file.md b/snippets/python/file-handling/copy-file.md index ff6ea68c..c737a268 100644 --- a/snippets/python/file-handling/copy-file.md +++ b/snippets/python/file-handling/copy-file.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,file,copy,utility --- -``` +```py import shutil def copy_file(src, dest): diff --git a/snippets/python/file-handling/delete-file.md b/snippets/python/file-handling/delete-file.md index c47e4074..2dc67691 100644 --- a/snippets/python/file-handling/delete-file.md +++ b/snippets/python/file-handling/delete-file.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,file,delete,utility --- -``` +```py import os def delete_file(filepath): diff --git a/snippets/python/file-handling/find-files.md b/snippets/python/file-handling/find-files.md index ab52a68b..928d9d23 100644 --- a/snippets/python/file-handling/find-files.md +++ b/snippets/python/file-handling/find-files.md @@ -5,7 +5,7 @@ Author: Jackeastern Tags: python,os,filesystem,file_search --- -``` +```py import os def find_files(directory, file_type): diff --git a/snippets/python/file-handling/get-file-extension.md b/snippets/python/file-handling/get-file-extension.md index 238bc4b7..4f49ef5a 100644 --- a/snippets/python/file-handling/get-file-extension.md +++ b/snippets/python/file-handling/get-file-extension.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,file,extension,utility --- -``` +```py import os def get_file_extension(filepath): diff --git a/snippets/python/file-handling/list-files-in-directory.md b/snippets/python/file-handling/list-files-in-directory.md index d9b95326..9abaf4be 100644 --- a/snippets/python/file-handling/list-files-in-directory.md +++ b/snippets/python/file-handling/list-files-in-directory.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,file,list,directory,utility --- -``` +```py import os def list_files(directory): diff --git a/snippets/python/file-handling/read-file-in-chunks.md b/snippets/python/file-handling/read-file-in-chunks.md index caf4c55f..155e480b 100644 --- a/snippets/python/file-handling/read-file-in-chunks.md +++ b/snippets/python/file-handling/read-file-in-chunks.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,file,read,chunks,utility --- -``` +```py def read_file_in_chunks(filepath, chunk_size): with open(filepath, 'r') as file: while chunk := file.read(chunk_size): diff --git a/snippets/python/file-handling/read-file-lines.md b/snippets/python/file-handling/read-file-lines.md index 42baf72e..fe058140 100644 --- a/snippets/python/file-handling/read-file-lines.md +++ b/snippets/python/file-handling/read-file-lines.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: python,file,read,utility --- -``` +```py def read_file_lines(filepath): with open(filepath, 'r') as file: return file.readlines() diff --git a/snippets/python/file-handling/write-to-file.md b/snippets/python/file-handling/write-to-file.md index 6c3cd3ca..1e8d5c29 100644 --- a/snippets/python/file-handling/write-to-file.md +++ b/snippets/python/file-handling/write-to-file.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: python,file,write,utility --- -``` +```py def write_to_file(filepath, content): with open(filepath, 'w') as file: file.write(content) diff --git a/snippets/python/json-manipulation/filter-json-data.md b/snippets/python/json-manipulation/filter-json-data.md index 9b4423c3..aace6946 100644 --- a/snippets/python/json-manipulation/filter-json-data.md +++ b/snippets/python/json-manipulation/filter-json-data.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,json,filter,data --- -``` +```py import json def filter_json_data(filepath, condition): diff --git a/snippets/python/json-manipulation/flatten-nested-json.md b/snippets/python/json-manipulation/flatten-nested-json.md index 9e3b4014..6830dde6 100644 --- a/snippets/python/json-manipulation/flatten-nested-json.md +++ b/snippets/python/json-manipulation/flatten-nested-json.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,json,flatten,nested --- -``` +```py def flatten_json(nested_json, prefix=''): flat_dict = {} for key, value in nested_json.items(): diff --git a/snippets/python/json-manipulation/merge-multiple-json-files.md b/snippets/python/json-manipulation/merge-multiple-json-files.md index 62472fcf..ef3e1b39 100644 --- a/snippets/python/json-manipulation/merge-multiple-json-files.md +++ b/snippets/python/json-manipulation/merge-multiple-json-files.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,json,merge,file --- -``` +```py import json def merge_json_files(filepaths, output_filepath): diff --git a/snippets/python/json-manipulation/read-json-file.md b/snippets/python/json-manipulation/read-json-file.md index a5e95544..c3f43ffa 100644 --- a/snippets/python/json-manipulation/read-json-file.md +++ b/snippets/python/json-manipulation/read-json-file.md @@ -5,7 +5,7 @@ Author: e3nviction Tags: python,json,file,read --- -``` +```py import json def read_json(filepath): diff --git a/snippets/python/json-manipulation/update-json-file.md b/snippets/python/json-manipulation/update-json-file.md index 773e80e5..4c83ad4c 100644 --- a/snippets/python/json-manipulation/update-json-file.md +++ b/snippets/python/json-manipulation/update-json-file.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,json,update,file --- -``` +```py import json def update_json(filepath, new_data): diff --git a/snippets/python/json-manipulation/validate-json-schema.md b/snippets/python/json-manipulation/validate-json-schema.md index 9e6c7fb4..639f0a66 100644 --- a/snippets/python/json-manipulation/validate-json-schema.md +++ b/snippets/python/json-manipulation/validate-json-schema.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,json,validation,schema --- -``` +```py import jsonschema from jsonschema import validate diff --git a/snippets/python/json-manipulation/write-json-file.md b/snippets/python/json-manipulation/write-json-file.md index 77d59b02..92985748 100644 --- a/snippets/python/json-manipulation/write-json-file.md +++ b/snippets/python/json-manipulation/write-json-file.md @@ -5,7 +5,7 @@ Author: e3nviction Tags: python,json,file,write --- -``` +```py import json def write_json(filepath, data): 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 b25043e3..bd99e976 100644 --- a/snippets/python/list-manipulation/find-duplicates-in-a-list.md +++ b/snippets/python/list-manipulation/find-duplicates-in-a-list.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,list,duplicates,utility --- -``` +```py def find_duplicates(lst): seen = set() duplicates = set() 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 32b27dd6..4d241948 100644 --- a/snippets/python/list-manipulation/find-intersection-of-two-lists.md +++ b/snippets/python/list-manipulation/find-intersection-of-two-lists.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,list,intersection,utility --- -``` +```py def list_intersection(lst1, lst2): return [item for item in lst1 if item in lst2] 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 b7a94dbe..f7a08bca 100644 --- a/snippets/python/list-manipulation/find-maximum-difference-in-list.md +++ b/snippets/python/list-manipulation/find-maximum-difference-in-list.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,list,difference,utility --- -``` +```py def max_difference(lst): if not lst or len(lst) < 2: return 0 diff --git a/snippets/python/list-manipulation/flatten-nested-list.md b/snippets/python/list-manipulation/flatten-nested-list.md index 3eba7908..22643c07 100644 --- a/snippets/python/list-manipulation/flatten-nested-list.md +++ b/snippets/python/list-manipulation/flatten-nested-list.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: python,list,flatten,utility --- -``` +```py def flatten_list(lst): return [item for sublist in lst for item in sublist] diff --git a/snippets/python/list-manipulation/flatten-unevenly-nested-lists.md b/snippets/python/list-manipulation/flatten-unevenly-nested-lists.md index e3f8d4d7..0c41a426 100644 --- a/snippets/python/list-manipulation/flatten-unevenly-nested-lists.md +++ b/snippets/python/list-manipulation/flatten-unevenly-nested-lists.md @@ -5,7 +5,7 @@ Author: agilarasu Tags: python,list,flattening,nested-lists,depth,utilities --- -``` +```py def flatten(nested_list): """ Flattens unevenly nested lists of any depth into a single flat list. diff --git a/snippets/python/list-manipulation/partition-list.md b/snippets/python/list-manipulation/partition-list.md index 75d5b277..3f99e8ae 100644 --- a/snippets/python/list-manipulation/partition-list.md +++ b/snippets/python/list-manipulation/partition-list.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,list,partition,utility --- -``` +```py def partition_list(lst, size): for i in range(0, len(lst), size): yield lst[i:i + size] diff --git a/snippets/python/list-manipulation/remove-duplicates.md b/snippets/python/list-manipulation/remove-duplicates.md index 836879b2..f89e239e 100644 --- a/snippets/python/list-manipulation/remove-duplicates.md +++ b/snippets/python/list-manipulation/remove-duplicates.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: python,list,duplicates,utility --- -``` +```py def remove_duplicates(lst): return list(dict.fromkeys(lst)) diff --git a/snippets/python/math-and-numbers/calculate-compound-interest.md b/snippets/python/math-and-numbers/calculate-compound-interest.md index dd358e93..93e143e4 100644 --- a/snippets/python/math-and-numbers/calculate-compound-interest.md +++ b/snippets/python/math-and-numbers/calculate-compound-interest.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,math,compound interest,finance --- -``` +```py def compound_interest(principal, rate, time, n=1): return principal * (1 + rate / n) ** (n * time) diff --git a/snippets/python/math-and-numbers/check-perfect-square.md b/snippets/python/math-and-numbers/check-perfect-square.md index b76f1362..fce869e2 100644 --- a/snippets/python/math-and-numbers/check-perfect-square.md +++ b/snippets/python/math-and-numbers/check-perfect-square.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,math,perfect square,check --- -``` +```py def is_perfect_square(n): if n < 0: return False diff --git a/snippets/python/math-and-numbers/check-prime-number.md b/snippets/python/math-and-numbers/check-prime-number.md index 5519b3f6..945daa2d 100644 --- a/snippets/python/math-and-numbers/check-prime-number.md +++ b/snippets/python/math-and-numbers/check-prime-number.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: python,math,prime,check --- -``` +```py def is_prime(n): if n <= 1: return False 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 d860da03..e8996d50 100644 --- a/snippets/python/math-and-numbers/convert-binary-to-decimal.md +++ b/snippets/python/math-and-numbers/convert-binary-to-decimal.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,math,binary,decimal,conversion --- -``` +```py def binary_to_decimal(binary_str): return int(binary_str, 2) diff --git a/snippets/python/math-and-numbers/find-factorial.md b/snippets/python/math-and-numbers/find-factorial.md index 9161f2d8..709a37b7 100644 --- a/snippets/python/math-and-numbers/find-factorial.md +++ b/snippets/python/math-and-numbers/find-factorial.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: python,math,factorial,utility --- -``` +```py def factorial(n): if n == 0: return 1 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 73ce1088..6acd3b11 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 @@ -5,7 +5,7 @@ Author: axorax Tags: python,math,lcm,gcd,utility --- -``` +```py def lcm(a, b): return abs(a * b) // gcd(a, b) diff --git a/snippets/python/math-and-numbers/solve-quadratic-equation.md b/snippets/python/math-and-numbers/solve-quadratic-equation.md index dd851041..469b19a2 100644 --- a/snippets/python/math-and-numbers/solve-quadratic-equation.md +++ b/snippets/python/math-and-numbers/solve-quadratic-equation.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,math,quadratic,equation,solver --- -``` +```py import cmath def solve_quadratic(a, b, c): diff --git a/snippets/python/sqlite-database/create-sqlite-database-table.md b/snippets/python/sqlite-database/create-sqlite-database-table.md index 8064e867..a2339546 100644 --- a/snippets/python/sqlite-database/create-sqlite-database-table.md +++ b/snippets/python/sqlite-database/create-sqlite-database-table.md @@ -5,7 +5,7 @@ Author: e3nviction Tags: python,sqlite,database,table --- -``` +```py import sqlite3 def create_table(db_name, table_name, schema): 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 5957c382..d5298720 100644 --- a/snippets/python/sqlite-database/insert-data-into-sqlite-table.md +++ b/snippets/python/sqlite-database/insert-data-into-sqlite-table.md @@ -5,7 +5,7 @@ Author: e3nviction Tags: python,sqlite,database,utility --- -``` +```py import sqlite3 def insert_into_table(db_path, table_name, data): diff --git a/snippets/python/string-manipulation/capitalize-words.md b/snippets/python/string-manipulation/capitalize-words.md index 1849021f..b7e85a48 100644 --- a/snippets/python/string-manipulation/capitalize-words.md +++ b/snippets/python/string-manipulation/capitalize-words.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,string,capitalize,utility --- -``` +```py def capitalize_words(s): return ' '.join(word.capitalize() for word in s.split()) diff --git a/snippets/python/string-manipulation/check-anagram.md b/snippets/python/string-manipulation/check-anagram.md index 8f947baa..a77f842f 100644 --- a/snippets/python/string-manipulation/check-anagram.md +++ b/snippets/python/string-manipulation/check-anagram.md @@ -5,7 +5,7 @@ Author: SteliosGee Tags: python,string,anagram,check,utility --- -``` +```py def is_anagram(s1, s2): return sorted(s1) == sorted(s2) diff --git a/snippets/python/string-manipulation/check-palindrome.md b/snippets/python/string-manipulation/check-palindrome.md index ebdf8be6..16bca74e 100644 --- a/snippets/python/string-manipulation/check-palindrome.md +++ b/snippets/python/string-manipulation/check-palindrome.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: python,string,palindrome,utility --- -``` +```py def is_palindrome(s): s = s.lower().replace(' ', '') return s == s[::-1] 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 8fb96640..a69ac827 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 @@ -5,7 +5,7 @@ Author: axorax Tags: python,string,snake-case,camel-case,convert,utility --- -``` +```py def snake_to_camel(s): parts = s.split('_') return parts[0] + ''.join(word.capitalize() for word in parts[1:]) diff --git a/snippets/python/string-manipulation/convert-string-to-ascii.md b/snippets/python/string-manipulation/convert-string-to-ascii.md index 444bf0d6..d9bddcf0 100644 --- a/snippets/python/string-manipulation/convert-string-to-ascii.md +++ b/snippets/python/string-manipulation/convert-string-to-ascii.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,string,ascii,convert,utility --- -``` +```py def string_to_ascii(s): return [ord(char) for char in s] diff --git a/snippets/python/string-manipulation/count-character-frequency.md b/snippets/python/string-manipulation/count-character-frequency.md index a56b8568..f6c85a7c 100644 --- a/snippets/python/string-manipulation/count-character-frequency.md +++ b/snippets/python/string-manipulation/count-character-frequency.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,string,character-frequency,utility --- -``` +```py from collections import Counter def char_frequency(s): diff --git a/snippets/python/string-manipulation/count-vowels.md b/snippets/python/string-manipulation/count-vowels.md index e18e0a3d..11407e93 100644 --- a/snippets/python/string-manipulation/count-vowels.md +++ b/snippets/python/string-manipulation/count-vowels.md @@ -5,7 +5,7 @@ Author: SteliosGee Tags: python,string,vowels,count,utility --- -``` +```py def count_vowels(s): vowels = 'aeiou' return len([char for char in s.lower() if char in vowels]) diff --git a/snippets/python/string-manipulation/count-words.md b/snippets/python/string-manipulation/count-words.md index ec5e207d..1755e566 100644 --- a/snippets/python/string-manipulation/count-words.md +++ b/snippets/python/string-manipulation/count-words.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,string,word-count,utility --- -``` +```py def count_words(s): return len(s.split()) diff --git a/snippets/python/string-manipulation/find-all-substrings.md b/snippets/python/string-manipulation/find-all-substrings.md index 105a7c68..f3be9d18 100644 --- a/snippets/python/string-manipulation/find-all-substrings.md +++ b/snippets/python/string-manipulation/find-all-substrings.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,string,substring,find,utility --- -``` +```py def find_substrings(s): substrings = [] for i in range(len(s)): diff --git a/snippets/python/string-manipulation/find-longest-word.md b/snippets/python/string-manipulation/find-longest-word.md index e28b5355..94a7158e 100644 --- a/snippets/python/string-manipulation/find-longest-word.md +++ b/snippets/python/string-manipulation/find-longest-word.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,string,longest-word,utility --- -``` +```py def find_longest_word(s): words = s.split() return max(words, key=len) if words else '' diff --git a/snippets/python/string-manipulation/find-unique-characters.md b/snippets/python/string-manipulation/find-unique-characters.md index badc4c35..c3e94bc4 100644 --- a/snippets/python/string-manipulation/find-unique-characters.md +++ b/snippets/python/string-manipulation/find-unique-characters.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,string,unique,characters,utility --- -``` +```py def find_unique_chars(s): return ''.join(sorted(set(s))) diff --git a/snippets/python/string-manipulation/remove-duplicate-characters.md b/snippets/python/string-manipulation/remove-duplicate-characters.md index efd1cab4..e25191d0 100644 --- a/snippets/python/string-manipulation/remove-duplicate-characters.md +++ b/snippets/python/string-manipulation/remove-duplicate-characters.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,string,duplicates,remove,utility --- -``` +```py def remove_duplicate_chars(s): seen = set() return ''.join(char for char in s if not (char in seen or seen.add(char))) diff --git a/snippets/python/string-manipulation/remove-punctuation.md b/snippets/python/string-manipulation/remove-punctuation.md index 796ea3d0..b18e1295 100644 --- a/snippets/python/string-manipulation/remove-punctuation.md +++ b/snippets/python/string-manipulation/remove-punctuation.md @@ -5,7 +5,7 @@ Author: SteliosGee Tags: python,string,punctuation,remove,utility --- -``` +```py import string def remove_punctuation(s): diff --git a/snippets/python/string-manipulation/remove-specific-characters.md b/snippets/python/string-manipulation/remove-specific-characters.md index 535f2668..ce75a767 100644 --- a/snippets/python/string-manipulation/remove-specific-characters.md +++ b/snippets/python/string-manipulation/remove-specific-characters.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,string,remove,characters,utility --- -``` +```py def remove_chars(s, chars): return ''.join(c for c in s if c not in chars) diff --git a/snippets/python/string-manipulation/remove-whitespace.md b/snippets/python/string-manipulation/remove-whitespace.md index 690c012f..9745af85 100644 --- a/snippets/python/string-manipulation/remove-whitespace.md +++ b/snippets/python/string-manipulation/remove-whitespace.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,string,whitespace,remove,utility --- -``` +```py def remove_whitespace(s): return ''.join(s.split()) diff --git a/snippets/python/string-manipulation/reverse-string.md b/snippets/python/string-manipulation/reverse-string.md index 2e5e74bb..83213418 100644 --- a/snippets/python/string-manipulation/reverse-string.md +++ b/snippets/python/string-manipulation/reverse-string.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: python,string,reverse,utility --- -``` +```py def reverse_string(s): return s[::-1] diff --git a/snippets/python/string-manipulation/split-camel-case.md b/snippets/python/string-manipulation/split-camel-case.md index 70ca44c3..95a311ea 100644 --- a/snippets/python/string-manipulation/split-camel-case.md +++ b/snippets/python/string-manipulation/split-camel-case.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,string,camel-case,split,utility --- -``` +```py import re def split_camel_case(s): diff --git a/snippets/python/string-manipulation/truncate-string.md b/snippets/python/string-manipulation/truncate-string.md index 688daf45..2528258d 100644 --- a/snippets/python/string-manipulation/truncate-string.md +++ b/snippets/python/string-manipulation/truncate-string.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,string,truncate,utility --- -``` +```py def truncate_string(s, length): return s[:length] + '...' if len(s) > length else s diff --git a/snippets/python/utilities/convert-bytes-to-human-readable-format.md b/snippets/python/utilities/convert-bytes-to-human-readable-format.md index d92a51a9..fa476880 100644 --- a/snippets/python/utilities/convert-bytes-to-human-readable-format.md +++ b/snippets/python/utilities/convert-bytes-to-human-readable-format.md @@ -5,7 +5,7 @@ Author: axorax Tags: python,bytes,format,utility --- -``` +```py def bytes_to_human_readable(num): for unit in ['B', 'KB', 'MB', 'GB', 'TB', 'PB']: if num < 1024: diff --git a/snippets/python/utilities/generate-random-string.md b/snippets/python/utilities/generate-random-string.md index 39c1d265..45f97ca0 100644 --- a/snippets/python/utilities/generate-random-string.md +++ b/snippets/python/utilities/generate-random-string.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: python,random,string,utility --- -``` +```py import random import string diff --git a/snippets/python/utilities/measure-execution-time.md b/snippets/python/utilities/measure-execution-time.md index bb3c5276..5c513da8 100644 --- a/snippets/python/utilities/measure-execution-time.md +++ b/snippets/python/utilities/measure-execution-time.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: python,time,execution,utility --- -``` +```py import time def measure_time(func, *args): diff --git a/snippets/rust/basics/hello-world.md b/snippets/rust/basics/hello-world.md index e41568c1..4e042a85 100644 --- a/snippets/rust/basics/hello-world.md +++ b/snippets/rust/basics/hello-world.md @@ -5,7 +5,7 @@ Author: James-Beans Tags: rust,printing,hello-world,utility --- -``` +```rust fn main() { // Defines the main running function println!("Hello, World!"); // Prints Hello, World! to the terminal. } diff --git a/snippets/rust/file-handling/find-files.md b/snippets/rust/file-handling/find-files.md index 00b0a443..e68a98e3 100644 --- a/snippets/rust/file-handling/find-files.md +++ b/snippets/rust/file-handling/find-files.md @@ -5,7 +5,7 @@ Author: Mathys-Gasnier Tags: rust,file,search --- -``` +```rust fn find_files(directory: &str, file_type: &str) -> std::io::Result> { let mut result = vec![]; diff --git a/snippets/rust/file-handling/read-file-lines.md b/snippets/rust/file-handling/read-file-lines.md index 9fedf481..e5fd742b 100644 --- a/snippets/rust/file-handling/read-file-lines.md +++ b/snippets/rust/file-handling/read-file-lines.md @@ -5,7 +5,7 @@ Author: Mathys-Gasnier Tags: rust,file,read,utility --- -``` +```rust fn read_lines(file_name: &str) -> std::io::Result> Ok( std::fs::read_to_string(file_name)? diff --git a/snippets/rust/string-manipulation/capitalize-string.md b/snippets/rust/string-manipulation/capitalize-string.md index 93d23947..072e87a7 100644 --- a/snippets/rust/string-manipulation/capitalize-string.md +++ b/snippets/rust/string-manipulation/capitalize-string.md @@ -5,7 +5,7 @@ Author: Mathys-Gasnier Tags: rust,string,capitalize,utility --- -``` +```rust fn capitalized(str: &str) -> String { let mut chars = str.chars(); match chars.next() { diff --git a/snippets/scss/animations/fade-in-animation.md b/snippets/scss/animations/fade-in-animation.md index 26d6eb4f..6c3e03da 100644 --- a/snippets/scss/animations/fade-in-animation.md +++ b/snippets/scss/animations/fade-in-animation.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: scss,animation,fade,css --- -``` +```scss @keyframes fade-in { from { opacity: 0; diff --git a/snippets/scss/animations/slide-in-from-left.md b/snippets/scss/animations/slide-in-from-left.md index c9fe9936..fb1ca028 100644 --- a/snippets/scss/animations/slide-in-from-left.md +++ b/snippets/scss/animations/slide-in-from-left.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: scss,animation,slide,css --- -``` +```scss @keyframes slide-in-left { from { transform: translateX(-100%); diff --git a/snippets/scss/borders-shadows/border-radius-helper.md b/snippets/scss/borders-shadows/border-radius-helper.md index 567ae887..3b965e5e 100644 --- a/snippets/scss/borders-shadows/border-radius-helper.md +++ b/snippets/scss/borders-shadows/border-radius-helper.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: scss,border,radius,css --- -``` +```scss @mixin border-radius($radius: 4px) { border-radius: $radius; } diff --git a/snippets/scss/borders-shadows/box-shadow-helper.md b/snippets/scss/borders-shadows/box-shadow-helper.md index 4a752254..728df676 100644 --- a/snippets/scss/borders-shadows/box-shadow-helper.md +++ b/snippets/scss/borders-shadows/box-shadow-helper.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: scss,box-shadow,css,effects --- -``` +```scss @mixin box-shadow($x: 0px, $y: 4px, $blur: 10px, $spread: 0px, $color: rgba(0, 0, 0, 0.1)) { box-shadow: $x $y $blur $spread $color; } diff --git a/snippets/scss/components/primary-button.md b/snippets/scss/components/primary-button.md index b57d6341..b15f3a91 100644 --- a/snippets/scss/components/primary-button.md +++ b/snippets/scss/components/primary-button.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: scss,button,primary,css --- -``` +```scss @mixin primary-button($bg: #007bff, $color: #fff) { background-color: $bg; color: $color; diff --git a/snippets/scss/layouts/aspect-ratio.md b/snippets/scss/layouts/aspect-ratio.md index bf742681..1a9106f1 100644 --- a/snippets/scss/layouts/aspect-ratio.md +++ b/snippets/scss/layouts/aspect-ratio.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: scss,aspect-ratio,layout,css --- -``` +```scss @mixin aspect-ratio($width, $height) { position: relative; width: 100%; diff --git a/snippets/scss/layouts/flex-center.md b/snippets/scss/layouts/flex-center.md index b0538d81..cef2a05d 100644 --- a/snippets/scss/layouts/flex-center.md +++ b/snippets/scss/layouts/flex-center.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: scss,flex,center,css --- -``` +```scss @mixin flex-center { display: flex; justify-content: center; diff --git a/snippets/scss/layouts/grid-container.md b/snippets/scss/layouts/grid-container.md index 09772ee0..34dd36d0 100644 --- a/snippets/scss/layouts/grid-container.md +++ b/snippets/scss/layouts/grid-container.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: scss,grid,layout,css --- -``` +```scss @mixin grid-container($columns: 12, $gap: 1rem) { display: grid; grid-template-columns: repeat($columns, 1fr); diff --git a/snippets/scss/typography/font-import-helper.md b/snippets/scss/typography/font-import-helper.md index ccbb99f5..1e4de341 100644 --- a/snippets/scss/typography/font-import-helper.md +++ b/snippets/scss/typography/font-import-helper.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: sass,mixin,fonts,css --- -``` +```scss @mixin import-font($family, $weight: 400, $style: normal) { @font-face { font-family: #{$family}; diff --git a/snippets/scss/typography/line-clamp-mixin.md b/snippets/scss/typography/line-clamp-mixin.md index 837129c7..fb0ee478 100644 --- a/snippets/scss/typography/line-clamp-mixin.md +++ b/snippets/scss/typography/line-clamp-mixin.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: sass,mixin,typography,css --- -``` +```scss @mixin line-clamp($number) { display: -webkit-box; -webkit-box-orient: vertical; diff --git a/snippets/scss/typography/text-gradient.md b/snippets/scss/typography/text-gradient.md index 616684cb..273698c8 100644 --- a/snippets/scss/typography/text-gradient.md +++ b/snippets/scss/typography/text-gradient.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: sass,mixin,gradient,text,css --- -``` +```scss @mixin text-gradient($from, $to) { background: linear-gradient(to right, $from, $to); -webkit-background-clip: text; diff --git a/snippets/scss/typography/text-overflow-ellipsis.md b/snippets/scss/typography/text-overflow-ellipsis.md index 70138e20..4f698e86 100644 --- a/snippets/scss/typography/text-overflow-ellipsis.md +++ b/snippets/scss/typography/text-overflow-ellipsis.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: sass,mixin,text,css --- -``` +```scss @mixin text-ellipsis { overflow: hidden; white-space: nowrap; diff --git a/snippets/scss/utilities/clearfix.md b/snippets/scss/utilities/clearfix.md index 7a726296..3831a301 100644 --- a/snippets/scss/utilities/clearfix.md +++ b/snippets/scss/utilities/clearfix.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: scss,clearfix,utility,css --- -``` +```scss @mixin clearfix { &::after { content: ''; diff --git a/snippets/scss/utilities/responsive-breakpoints.md b/snippets/scss/utilities/responsive-breakpoints.md index 4b822dc9..cd13f19f 100644 --- a/snippets/scss/utilities/responsive-breakpoints.md +++ b/snippets/scss/utilities/responsive-breakpoints.md @@ -5,7 +5,7 @@ Author: dostonnabotov Tags: scss,responsive,media-queries,css --- -``` +```scss @mixin breakpoint($breakpoint) { @if $breakpoint == sm { @media (max-width: 576px) { @content; } diff --git a/utils/migrateSnippets.js b/utils/migrateSnippets.js index c77da85a..247f7729 100644 --- a/utils/migrateSnippets.js +++ b/utils/migrateSnippets.js @@ -13,7 +13,12 @@ function slugify(string, separator = "-") { .replace(/\-$/g, ""); // Remove trailing - } -function formatSnippet(snippet) { +const languageToMarkdownHighlightOverwrites = { + 'javascript': 'js', + 'python': 'py' +}; + +function formatSnippet(language, snippet) { return `--- Title: ${snippet.title} Description: ${snippet.description} @@ -21,7 +26,7 @@ Author: ${snippet.author} Tags: ${snippet.tags}${('contributors' in snippet) && snippet.contributors.length > 0 ? `\nContributors: ${snippet.contributors}` : ''} --- -\`\`\` +\`\`\`${language in languageToMarkdownHighlightOverwrites ? languageToMarkdownHighlightOverwrites[language] : language} ${Array.isArray(snippet.code) ? snippet.code.join('\n').trim() : snippet.code.trim()} \`\`\` `; @@ -51,7 +56,7 @@ for (const file of readdirSync(dataDir)) { for(const snippet of category.snippets) { const snippetPath = join(categoryPath, `${slugify(snippet.title)}.md`); - writeFileSync(snippetPath, formatSnippet(snippet)); + writeFileSync(snippetPath, formatSnippet(languageName, snippet)); } } } \ No newline at end of file