From c5147e060e39474ebf59d3d17acbde2be31ebc49 Mon Sep 17 00:00:00 2001 From: Axorax Date: Tue, 31 Dec 2024 19:55:45 +0600 Subject: [PATCH 1/4] Add JavaScript snippets --- public/data/javascript.json | 390 ++++++++++++++++++++++++++++++++++++ 1 file changed, 390 insertions(+) diff --git a/public/data/javascript.json b/public/data/javascript.json index 7ee15b3a..cfdf8909 100644 --- a/public/data/javascript.json +++ b/public/data/javascript.json @@ -809,6 +809,160 @@ ], "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.reduceRight((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": "Pipe Functions", + "description": "Pipes multiple functions into a single function, where the output of one function becomes the input of the next.", + "code": [ + "const pipe = (...funcs) => (initialValue) => {", + " return funcs.reduce((acc, func) => func(acc), initialValue);", + "};", + "", + "// Usage:", + "const add2 = (x) => x + 2;", + "const multiply3 = (x) => x * 3;", + "const piped = pipe(add2, multiply3);", + "console.log(piped(5)); // Output: 21 ((5 + 2) * 3)" + ], + "tags": ["javascript", "function", "pipe", "utility"], + "author": "axorax" + }, + { + "title": "Once Per Interval", + "description": "Ensures that a function can only be invoked once within a specific time interval.", + "code": [ + "const oncePerInterval = (func, interval) => {", + " let lastCallTime = 0;", + " return (...args) => {", + " const now = Date.now();", + " if (now - lastCallTime >= interval) {", + " lastCallTime = now;", + " func(...args);", + " }", + " };", + "};", + "", + "// Usage:", + "const logMessage = () => console.log('Message logged');", + "const logOncePerSecond = oncePerInterval(logMessage, 1000);", + "setInterval(() => logOncePerSecond(), 200); // Logs once per second" + ], + "tags": ["javascript", "function", "interval", "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" } ] }, @@ -844,6 +998,73 @@ ], "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" + }, + { + "title": "Toggle Visibility", + "description": "Toggles the visibility of an element.", + "code": [ + "const toggleVisibility = (element) => {", + " const currentDisplay = window.getComputedStyle(element).display;", + " element.style.display = currentDisplay === 'none' ? 'block' : 'none';", + "};", + "", + "// Usage:", + "const element = document.querySelector('.my-element');", + "toggleVisibility(element);" + ], + "tags": ["javascript", "dom", "visibility", "toggle"], + "author": "axorax" } ] }, @@ -893,6 +1114,38 @@ ], "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" + }, + { + "title": "Check Storage Capacity", + "description": "Checks the available space in the localStorage.", + "code": [ + "const checkLocalStorageCapacity = () => {", + " let spaceUsed = 0;", + " for (let i = 0; i < localStorage.length; i++) {", + " spaceUsed += localStorage.key(i).length + localStorage.getItem(localStorage.key(i)).length;", + " }", + " console.log(`Used space: ${spaceUsed} bytes`);", + "};", + "", + "// Usage:", + "checkLocalStorageCapacity();" + ], + "tags": ["javascript", "localStorage", "storage", "utility"], + "author": "axorax" } ] }, @@ -920,6 +1173,143 @@ ], "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": "Format Large Numbers with Abbreviations", + "description": "Formats large numbers with abbreviations like K, M, B, etc.", + "code": [ + "const abbreviateNumber = (num) => {", + " const abbreviations = ['K', 'M', 'B', 'T'];", + " let i = 0;", + " while (num >= 1000 && i < abbreviations.length) {", + " num /= 1000;", + " i++;", + " }", + " return num.toFixed(1) + abbreviations[i];", + "};", + "", + "// Usage:", + "console.log(abbreviateNumber(2500)); // Output: '2.5K'", + "console.log(abbreviateNumber(10500000)); // Output: '10.5M'", + "console.log(abbreviateNumber(1000000000)); // Output: '1.0B'" + ], + "tags": ["javascript", "number", "abbreviate", "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" } ] } From 626706a82b76167bbc14d23090acca8856e4eafa Mon Sep 17 00:00:00 2001 From: Axorax Date: Tue, 31 Dec 2024 20:24:13 +0600 Subject: [PATCH 2/4] fix --- public/data/javascript.json | 88 +++---------------------------------- 1 file changed, 5 insertions(+), 83 deletions(-) diff --git a/public/data/javascript.json b/public/data/javascript.json index 1a7381c2..70c34d61 100644 --- a/public/data/javascript.json +++ b/public/data/javascript.json @@ -885,7 +885,7 @@ "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.reduceRight((acc, func) => func(acc), initialValue);", + " return funcs.reduce((acc, func) => func(acc), initialValue);", "};", "", "// Usage:", @@ -897,46 +897,6 @@ "tags": ["javascript", "function", "compose", "utility"], "author": "axorax" }, - { - "title": "Pipe Functions", - "description": "Pipes multiple functions into a single function, where the output of one function becomes the input of the next.", - "code": [ - "const pipe = (...funcs) => (initialValue) => {", - " return funcs.reduce((acc, func) => func(acc), initialValue);", - "};", - "", - "// Usage:", - "const add2 = (x) => x + 2;", - "const multiply3 = (x) => x * 3;", - "const piped = pipe(add2, multiply3);", - "console.log(piped(5)); // Output: 21 ((5 + 2) * 3)" - ], - "tags": ["javascript", "function", "pipe", "utility"], - "author": "axorax" - }, - { - "title": "Once Per Interval", - "description": "Ensures that a function can only be invoked once within a specific time interval.", - "code": [ - "const oncePerInterval = (func, interval) => {", - " let lastCallTime = 0;", - " return (...args) => {", - " const now = Date.now();", - " if (now - lastCallTime >= interval) {", - " lastCallTime = now;", - " func(...args);", - " }", - " };", - "};", - "", - "// Usage:", - "const logMessage = () => console.log('Message logged');", - "const logOncePerSecond = oncePerInterval(logMessage, 1000);", - "setInterval(() => logOncePerSecond(), 200); // Logs once per second" - ], - "tags": ["javascript", "function", "interval", "utility"], - "author": "axorax" - }, { "title": "Rate Limit Function", "description": "Limits how often a function can be executed within a given time window.", @@ -1062,22 +1022,6 @@ ], "tags": ["javascript", "dom", "remove", "utility"], "author": "axorax" - }, - { - "title": "Toggle Visibility", - "description": "Toggles the visibility of an element.", - "code": [ - "const toggleVisibility = (element) => {", - " const currentDisplay = window.getComputedStyle(element).display;", - " element.style.display = currentDisplay === 'none' ? 'block' : 'none';", - "};", - "", - "// Usage:", - "const element = document.querySelector('.my-element');", - "toggleVisibility(element);" - ], - "tags": ["javascript", "dom", "visibility", "toggle"], - "author": "axorax" } ] }, @@ -1143,10 +1087,10 @@ "author": "axorax" }, { - "title": "Check Storage Capacity", - "description": "Checks the available space in the localStorage.", + "title": "Check bytes used", + "description": "Checks the amount of bytes used in the localStorage.", "code": [ - "const checkLocalStorageCapacity = () => {", + "const checkBytesUsed = () => {", " let spaceUsed = 0;", " for (let i = 0; i < localStorage.length; i++) {", " spaceUsed += localStorage.key(i).length + localStorage.getItem(localStorage.key(i)).length;", @@ -1155,7 +1099,7 @@ "};", "", "// Usage:", - "checkLocalStorageCapacity();" + "checkBytesUsed();" ], "tags": ["javascript", "localStorage", "storage", "utility"], "author": "axorax" @@ -1276,28 +1220,6 @@ "tags": ["javascript", "number", "words", "utility"], "author": "axorax" }, - { - "title": "Format Large Numbers with Abbreviations", - "description": "Formats large numbers with abbreviations like K, M, B, etc.", - "code": [ - "const abbreviateNumber = (num) => {", - " const abbreviations = ['K', 'M', 'B', 'T'];", - " let i = 0;", - " while (num >= 1000 && i < abbreviations.length) {", - " num /= 1000;", - " i++;", - " }", - " return num.toFixed(1) + abbreviations[i];", - "};", - "", - "// Usage:", - "console.log(abbreviateNumber(2500)); // Output: '2.5K'", - "console.log(abbreviateNumber(10500000)); // Output: '10.5M'", - "console.log(abbreviateNumber(1000000000)); // Output: '1.0B'" - ], - "tags": ["javascript", "number", "abbreviate", "utility"], - "author": "axorax" - }, { "title": "Convert to Scientific Notation", "description": "Converts a number to scientific notation.", From ce98365a364f2b79b86eb73ded09d9ac310ad76e Mon Sep 17 00:00:00 2001 From: Axorax Date: Tue, 31 Dec 2024 20:53:53 +0600 Subject: [PATCH 3/4] fix --- public/data/javascript.json | 45 ------------------------------------- 1 file changed, 45 deletions(-) diff --git a/public/data/javascript.json b/public/data/javascript.json index bb4c0faa..00ff61b0 100644 --- a/public/data/javascript.json +++ b/public/data/javascript.json @@ -910,33 +910,6 @@ "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" - }, { "title": "Random string", "description": "Generates a random string of characters of a certain length", @@ -1098,24 +1071,6 @@ ], "tags": ["javascript", "localStorage", "storage", "utility"], "author": "axorax" - }, - { - "title": "Check bytes used", - "description": "Checks the amount of bytes used in the localStorage.", - "code": [ - "const checkBytesUsed = () => {", - " let spaceUsed = 0;", - " for (let i = 0; i < localStorage.length; i++) {", - " spaceUsed += localStorage.key(i).length + localStorage.getItem(localStorage.key(i)).length;", - " }", - " console.log(`Used space: ${spaceUsed} bytes`);", - "};", - "", - "// Usage:", - "checkBytesUsed();" - ], - "tags": ["javascript", "localStorage", "storage", "utility"], - "author": "axorax" } ] }, From 3839ee7cc70224616e7ca60008367b49e8500d7e Mon Sep 17 00:00:00 2001 From: Axorax Date: Tue, 31 Dec 2024 20:58:18 +0600 Subject: [PATCH 4/4] fix --- public/data/javascript.json | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/public/data/javascript.json b/public/data/javascript.json index 00ff61b0..c92b0264 100644 --- a/public/data/javascript.json +++ b/public/data/javascript.json @@ -911,17 +911,31 @@ "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('');", - "}", + "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 });", + " }", + " };", + "};", "", - "console.log(makeid(5), \"1234\" /* (optional) */);" + "// 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", "random"], - "author": "kruimol" + "tags": ["javascript", "function", "rate-limiting", "utility"], + "author": "axorax" } ] },