Skip to content

Commit 1bfa07c

Browse files
Merge pull request #51 from Axorax/main
Add JavaScript snippets
2 parents 159f0de + e21abf0 commit 1bfa07c

File tree

1 file changed

+375
-0
lines changed

1 file changed

+375
-0
lines changed

public/data/javascript.json

Lines changed: 375 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,96 @@
184184
],
185185
"tags": ["string", "whitespace"],
186186
"author": "axorax"
187+
},
188+
{
189+
"title": "Pad String on Both Sides",
190+
"description": "Pads a string on both sides with a specified character until it reaches the desired length.",
191+
"code": [
192+
"function padString(str, length, char = ' ') {",
193+
" const totalPad = length - str.length;",
194+
" const padStart = Math.floor(totalPad / 2);",
195+
" const padEnd = totalPad - padStart;",
196+
" return char.repeat(padStart) + str + char.repeat(padEnd);",
197+
"}",
198+
"",
199+
"// Example usage:",
200+
"console.log(padString('hello', 10, '*')); // Output: '**hello***'"
201+
],
202+
"tags": ["string", "pad", "manipulation"],
203+
"author": "axorax"
204+
},
205+
{
206+
"title": "Convert String to Snake Case",
207+
"description": "Converts a given string into snake_case.",
208+
"code": [
209+
"function toSnakeCase(str) {",
210+
" return str.replace(/([a-z])([A-Z])/g, '$1_$2')",
211+
" .replace(/\\s+/g, '_')",
212+
" .toLowerCase();",
213+
"}",
214+
"",
215+
"// Example usage:",
216+
"console.log(toSnakeCase('Hello World Test')); // Output: 'hello_world_test'"
217+
],
218+
"tags": ["string", "case", "snake_case"],
219+
"author": "axorax"
220+
},
221+
{
222+
"title": "Remove Vowels from a String",
223+
"description": "Removes all vowels from a given string.",
224+
"code": [
225+
"function removeVowels(str) {",
226+
" return str.replace(/[aeiouAEIOU]/g, '');",
227+
"}",
228+
"",
229+
"// Example usage:",
230+
"console.log(removeVowels('Hello World')); // Output: 'Hll Wrld'"
231+
],
232+
"tags": ["string", "remove", "vowels"],
233+
"author": "axorax"
234+
},
235+
{
236+
"title": "Mask Sensitive Information",
237+
"description": "Masks parts of a sensitive string, like a credit card or email address.",
238+
"code": [
239+
"function maskSensitiveInfo(str, visibleCount = 4, maskChar = '*') {",
240+
" return str.slice(0, visibleCount) + maskChar.repeat(Math.max(0, str.length - visibleCount));",
241+
"}",
242+
"",
243+
"// Example usage:",
244+
"console.log(maskSensitiveInfo('123456789', 4)); // Output: '1234*****'",
245+
"console.log(maskSensitiveInfo('[email protected]', 2, '#')); // Output: 'ex#############'"
246+
],
247+
"tags": ["string", "mask", "sensitive"],
248+
"author": "axorax"
249+
},
250+
{
251+
"title": "Extract Initials from Name",
252+
"description": "Extracts and returns the initials from a full name.",
253+
"code": [
254+
"function getInitials(name) {",
255+
" return name.split(' ').map(part => part.charAt(0).toUpperCase()).join('');",
256+
"}",
257+
"",
258+
"// Example usage:",
259+
"console.log(getInitials('John Doe')); // Output: 'JD'"
260+
],
261+
"tags": ["string", "initials", "name"],
262+
"author": "axorax"
263+
},
264+
{
265+
"title": "Convert Tabs to Spaces",
266+
"description": "Converts all tab characters in a string to spaces.",
267+
"code": [
268+
"function tabsToSpaces(str, spacesPerTab = 4) {",
269+
" return str.replace(/\\t/g, ' '.repeat(spacesPerTab));",
270+
"}",
271+
"",
272+
"// Example usage:",
273+
"console.log(tabsToSpaces('Hello\\tWorld', 2)); // Output: 'Hello World'"
274+
],
275+
"tags": ["string", "tabs", "spaces"],
276+
"author": "axorax"
187277
}
188278
]
189279
},
@@ -251,6 +341,206 @@
251341
],
252342
"tags": ["javascript", "array", "unique", "utility"],
253343
"author": "realvishalrana"
344+
},
345+
{
346+
"title": "Merge Objects Deeply",
347+
"description": "Deeply merges two or more objects, including nested properties.",
348+
"code": [
349+
"function deepMerge(...objects) {",
350+
" return objects.reduce((acc, obj) => {",
351+
" Object.keys(obj).forEach(key => {",
352+
" if (typeof obj[key] === 'object' && obj[key] !== null) {",
353+
" acc[key] = deepMerge(acc[key] || {}, obj[key]);",
354+
" } else {",
355+
" acc[key] = obj[key];",
356+
" }",
357+
" });",
358+
" return acc;",
359+
" }, {});",
360+
"}",
361+
"",
362+
"// Usage:",
363+
"const obj1 = { a: 1, b: { c: 2 } };",
364+
"const obj2 = { b: { d: 3 }, e: 4 };",
365+
"console.log(deepMerge(obj1, obj2)); // Output: { a: 1, b: { c: 2, d: 3 }, e: 4 }"
366+
],
367+
"tags": ["javascript", "object", "merge", "deep"],
368+
"author": "axorax"
369+
},
370+
{
371+
"title": "Omit Keys from Object",
372+
"description": "Creates a new object with specific keys omitted.",
373+
"code": [
374+
"function omitKeys(obj, keys) {",
375+
" return Object.fromEntries(",
376+
" Object.entries(obj).filter(([key]) => !keys.includes(key))",
377+
" );",
378+
"}",
379+
"",
380+
"// Usage:",
381+
"const obj = { a: 1, b: 2, c: 3 };",
382+
"console.log(omitKeys(obj, ['b', 'c'])); // Output: { a: 1 }"
383+
],
384+
"tags": ["javascript", "object", "omit", "utility"],
385+
"author": "axorax"
386+
},
387+
{
388+
"title": "Convert Object to Query String",
389+
"description": "Converts an object to a query string for use in URLs.",
390+
"code": [
391+
"function toQueryString(obj) {",
392+
" return Object.entries(obj)",
393+
" .map(([key, value]) => encodeURIComponent(key) + '=' + encodeURIComponent(value))",
394+
" .join('&');",
395+
"}",
396+
"",
397+
"// Usage:",
398+
"const params = { search: 'test', page: 1 };",
399+
"console.log(toQueryString(params)); // Output: 'search=test&page=1'"
400+
],
401+
"tags": ["javascript", "object", "query string", "url"],
402+
"author": "axorax"
403+
},
404+
{
405+
"title": "Flatten Nested Object",
406+
"description": "Flattens a nested object into a single-level object with dot notation for keys.",
407+
"code": [
408+
"function flattenObject(obj, prefix = '') {",
409+
" return Object.keys(obj).reduce((acc, key) => {",
410+
" const fullPath = prefix ? `${prefix}.${key}` : key;",
411+
" if (typeof obj[key] === 'object' && obj[key] !== null) {",
412+
" Object.assign(acc, flattenObject(obj[key], fullPath));",
413+
" } else {",
414+
" acc[fullPath] = obj[key];",
415+
" }",
416+
" return acc;",
417+
" }, {});",
418+
"}",
419+
"",
420+
"// Usage:",
421+
"const nestedObj = { a: { b: { c: 1 }, d: 2 }, e: 3 };",
422+
"console.log(flattenObject(nestedObj)); // Output: { 'a.b.c': 1, 'a.d': 2, e: 3 }"
423+
],
424+
"tags": ["javascript", "object", "flatten", "utility"],
425+
"author": "axorax"
426+
},
427+
{
428+
"title": "Pick Keys from Object",
429+
"description": "Creates a new object with only the specified keys.",
430+
"code": [
431+
"function pickKeys(obj, keys) {",
432+
" return Object.fromEntries(",
433+
" Object.entries(obj).filter(([key]) => keys.includes(key))",
434+
" );",
435+
"}",
436+
"",
437+
"// Usage:",
438+
"const obj = { a: 1, b: 2, c: 3 };",
439+
"console.log(pickKeys(obj, ['a', 'c'])); // Output: { a: 1, c: 3 }"
440+
],
441+
"tags": ["javascript", "object", "pick", "utility"],
442+
"author": "axorax"
443+
},
444+
{
445+
"title": "Check if Object is Empty",
446+
"description": "Checks whether an object has no own enumerable properties.",
447+
"code": [
448+
"function isEmptyObject(obj) {",
449+
" return Object.keys(obj).length === 0;",
450+
"}",
451+
"",
452+
"// Usage:",
453+
"console.log(isEmptyObject({})); // Output: true",
454+
"console.log(isEmptyObject({ a: 1 })); // Output: false"
455+
],
456+
"tags": ["javascript", "object", "check", "empty"],
457+
"author": "axorax"
458+
},
459+
{
460+
"title": "Invert Object Keys and Values",
461+
"description": "Creates a new object by swapping keys and values of the given object.",
462+
"code": [
463+
"function invertObject(obj) {",
464+
" return Object.fromEntries(",
465+
" Object.entries(obj).map(([key, value]) => [value, key])",
466+
" );",
467+
"}",
468+
"",
469+
"// Usage:",
470+
"const obj = { a: 1, b: 2, c: 3 };",
471+
"console.log(invertObject(obj)); // Output: { '1': 'a', '2': 'b', '3': 'c' }"
472+
],
473+
"tags": ["javascript", "object", "invert", "utility"],
474+
"author": "axorax"
475+
},
476+
{
477+
"title": "Clone Object Shallowly",
478+
"description": "Creates a shallow copy of an object.",
479+
"code": [
480+
"function shallowClone(obj) {",
481+
" return { ...obj };",
482+
"}",
483+
"",
484+
"// Usage:",
485+
"const obj = { a: 1, b: 2 };",
486+
"const clone = shallowClone(obj);",
487+
"console.log(clone); // Output: { a: 1, b: 2 }"
488+
],
489+
"tags": ["javascript", "object", "clone", "shallow"],
490+
"author": "axorax"
491+
},
492+
{
493+
"title": "Count Properties in Object",
494+
"description": "Counts the number of own properties in an object.",
495+
"code": [
496+
"function countProperties(obj) {",
497+
" return Object.keys(obj).length;",
498+
"}",
499+
"",
500+
"// Usage:",
501+
"const obj = { a: 1, b: 2, c: 3 };",
502+
"console.log(countProperties(obj)); // Output: 3"
503+
],
504+
"tags": ["javascript", "object", "count", "properties"],
505+
"author": "axorax"
506+
},
507+
{
508+
"title": "Compare Two Objects Shallowly",
509+
"description": "Compares two objects shallowly and returns whether they are equal.",
510+
"code": [
511+
"function shallowEqual(obj1, obj2) {",
512+
" const keys1 = Object.keys(obj1);",
513+
" const keys2 = Object.keys(obj2);",
514+
" if (keys1.length !== keys2.length) return false;",
515+
" return keys1.every(key => obj1[key] === obj2[key]);",
516+
"}",
517+
"",
518+
"// Usage:",
519+
"const obj1 = { a: 1, b: 2 };",
520+
"const obj2 = { a: 1, b: 2 };",
521+
"const obj3 = { a: 1, b: 3 };",
522+
"console.log(shallowEqual(obj1, obj2)); // Output: true",
523+
"console.log(shallowEqual(obj1, obj3)); // Output: false"
524+
],
525+
"tags": ["javascript", "object", "compare", "shallow"],
526+
"author": "axorax"
527+
},
528+
{
529+
"title": "Freeze Object",
530+
"description": "Freezes an object to make it immutable.",
531+
"code": [
532+
"function freezeObject(obj) {",
533+
" return Object.freeze(obj);",
534+
"}",
535+
"",
536+
"// Usage:",
537+
"const obj = { a: 1, b: 2 };",
538+
"const frozenObj = freezeObject(obj);",
539+
"frozenObj.a = 42; // This will fail silently in strict mode.",
540+
"console.log(frozenObj.a); // Output: 1"
541+
],
542+
"tags": ["javascript", "object", "freeze", "immutable"],
543+
"author": "axorax"
254544
}
255545
]
256546
},
@@ -328,6 +618,91 @@
328618
"utility"
329619
],
330620
"author": "Yugveer06"
621+
},
622+
{
623+
"title": "Get Current Timestamp",
624+
"description": "Retrieves the current timestamp in milliseconds since January 1, 1970.",
625+
"code": [
626+
"const getCurrentTimestamp = () => Date.now();",
627+
"",
628+
"// Usage:",
629+
"console.log(getCurrentTimestamp()); // Output: 1691825935839 (example)"
630+
],
631+
"tags": ["javascript", "date", "timestamp", "utility"],
632+
"author": "axorax"
633+
},
634+
{
635+
"title": "Check Leap Year",
636+
"description": "Determines if a given year is a leap year.",
637+
"code": [
638+
"const isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;",
639+
"",
640+
"// Usage:",
641+
"console.log(isLeapYear(2024)); // Output: true",
642+
"console.log(isLeapYear(2023)); // Output: false"
643+
],
644+
"tags": ["javascript", "date", "leap-year", "utility"],
645+
"author": "axorax"
646+
},
647+
{
648+
"title": "Add Days to a Date",
649+
"description": "Adds a specified number of days to a given date.",
650+
"code": [
651+
"const addDays = (date, days) => {",
652+
" const result = new Date(date);",
653+
" result.setDate(result.getDate() + days);",
654+
" return result;",
655+
"};",
656+
"",
657+
"// Usage:",
658+
"const today = new Date();",
659+
"console.log(addDays(today, 10)); // Output: Date object 10 days ahead"
660+
],
661+
"tags": ["javascript", "date", "add-days", "utility"],
662+
"author": "axorax"
663+
},
664+
{
665+
"title": "Start of the Day",
666+
"description": "Returns the start of the day (midnight) for a given date.",
667+
"code": [
668+
"const startOfDay = (date) => new Date(date.setHours(0, 0, 0, 0));",
669+
"",
670+
"// Usage:",
671+
"const today = new Date();",
672+
"console.log(startOfDay(today)); // Output: Date object for midnight"
673+
],
674+
"tags": ["javascript", "date", "start-of-day", "utility"],
675+
"author": "axorax"
676+
},
677+
{
678+
"title": "Get Days in Month",
679+
"description": "Calculates the number of days in a specific month of a given year.",
680+
"code": [
681+
"const getDaysInMonth = (year, month) => new Date(year, month + 1, 0).getDate();",
682+
"",
683+
"// Usage:",
684+
"console.log(getDaysInMonth(2024, 1)); // Output: 29 (February in a leap year)",
685+
"console.log(getDaysInMonth(2023, 1)); // Output: 28"
686+
],
687+
"tags": ["javascript", "date", "days-in-month", "utility"],
688+
"author": "axorax"
689+
},
690+
{
691+
"title": "Get Day of the Year",
692+
"description": "Calculates the day of the year (1-365 or 1-366 for leap years) for a given date.",
693+
"code": [
694+
"const getDayOfYear = (date) => {",
695+
" const startOfYear = new Date(date.getFullYear(), 0, 0);",
696+
" const diff = date - startOfYear + (startOfYear.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000;",
697+
" return Math.floor(diff / (1000 * 60 * 60 * 24));",
698+
"};",
699+
"",
700+
"// Usage:",
701+
"const today = new Date('2024-12-31');",
702+
"console.log(getDayOfYear(today)); // Output: 366 (in a leap year)"
703+
],
704+
"tags": ["javascript", "date", "day-of-year", "utility"],
705+
"author": "axorax"
331706
}
332707
]
333708
},

0 commit comments

Comments
 (0)