Skip to content

[Snippets] - add a few useful JS snippets #151

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions public/consolidated/javascript.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,24 @@
}
]
},
{
"categoryName": "Color Manipulation",
"snippets": [
{
"title": "RGB to Hex Color",
"description": "Converts RGB color values to hexadecimal color code.",
"author": "jjcantu",
"tags": [
"javascript",
"color",
"conversion",
"utility"
],
"contributors": [],
"code": "function rgbToHex(r, g, b) {\n const toHex = (n) => {\n const hex = n.toString(16);\n return hex.length === 1 ? '0' + hex : hex;\n };\n \n return '#' + toHex(r) + toHex(g) + toHex(b);\n}\n\n// Usage:\nconsole.log(rgbToHex(255, 128, 0)); // Output: \"#ff8000\"\nconsole.log(rgbToHex(0, 255, 0)); // Output: \"#00ff00\"\n"
}
]
},
{
"categoryName": "Date And Time",
"snippets": [
Expand Down Expand Up @@ -547,6 +565,19 @@
"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"
},
{
"title": "Format File Size",
"description": "Converts bytes into human-readable file size format.",
"author": "jjcantu",
"tags": [
"javascript",
"format",
"size",
"utility"
],
"contributors": [],
"code": "function formatFileSize(bytes) {\n if (bytes === 0) return '0 Bytes';\n \n const k = 1024;\n const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n \n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n}\n\n// Usage:\nconsole.log(formatFileSize(1234)); // Output: \"1.21 KB\"\nconsole.log(formatFileSize(1234567)); // Output: \"1.18 MB\"\n"
},
{
"title": "Format Number with Commas",
"description": "Formats a number with commas for better readability (e.g., 1000 -> 1,000).",
Expand Down Expand Up @@ -656,6 +687,19 @@
"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"
},
{
"title": "Deep Clone Object",
"description": "Creates a deep copy of an object or array without reference.",
"author": "jjcantu",
"tags": [
"javascript",
"object",
"clone",
"utility"
],
"contributors": [],
"code": "function deepClone(obj) {\n if (obj === null || typeof obj !== 'object') return obj;\n \n const clone = Array.isArray(obj) ? [] : {};\n \n for (let key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clone[key] = deepClone(obj[key]);\n }\n }\n \n return clone;\n}\n\n// Usage:\nconst original = { a: 1, b: { c: 2 }, d: [1, 2, 3] };\nconst cloned = deepClone(original);\nconsole.log(cloned); // Output: { a: 1, b: { c: 2 }, d: [1, 2, 3] }\n"
},
{
"title": "Filter Object",
"description": "Filter out entries in an object where the value is falsy, including empty strings, empty objects, null, and undefined.",
Expand Down Expand Up @@ -930,6 +974,18 @@
"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"
},
{
"title": "Generate UUID",
"description": "Generates a UUID (v4) string.",
"author": "jjcantu",
"tags": [
"javascript",
"uuid",
"utility"
],
"contributors": [],
"code": "function generateUUID() {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n const r = Math.random() * 16 | 0;\n const v = c === 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n}\n\n// Usage:\nconsole.log(generateUUID()); // Output: \"a1b2c3d4-e5f6-4g7h-8i9j-k0l1m2n3o4p5\"\n"
},
{
"title": "Mask Sensitive Information",
"description": "Masks parts of a sensitive string, like a credit card or email address.",
Expand Down
21 changes: 21 additions & 0 deletions snippets/javascript/color-manipulation/rgb-to-hex-color.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
title: RGB to Hex Color
description: Converts RGB color values to hexadecimal color code.
author: jjcantu
tags: color,conversion
---

```js
function rgbToHex(r, g, b) {
const toHex = (n) => {
const hex = n.toString(16);
return hex.length === 1 ? '0' + hex : hex;
};

return '#' + toHex(r) + toHex(g) + toHex(b);
}

// Usage:
console.log(rgbToHex(255, 128, 0)); // Output: "#ff8000"
console.log(rgbToHex(0, 255, 0)); // Output: "#00ff00"
```
22 changes: 22 additions & 0 deletions snippets/javascript/number-formatting/format-file-size.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
---
title: Format File Size
description: Converts bytes into human-readable file size format.
author: jjcantu
tags: format,size
---

```js
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';

const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));

return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// Usage:
console.log(formatFileSize(1234)); // Output: "1.21 KB"
console.log(formatFileSize(1234567)); // Output: "1.18 MB"
```
27 changes: 27 additions & 0 deletions snippets/javascript/object-manipulation/deep-clone-object.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
---
title: Deep Clone Object
description: Creates a deep copy of an object or array without reference.
author: jjcantu
tags: object,clone
---

```js
function deepClone(obj) {
if (obj === null || typeof obj !== 'object') return obj;

const clone = Array.isArray(obj) ? [] : {};

for (let key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
clone[key] = deepClone(obj[key]);
}
}

return clone;
}

// Usage:
const original = { a: 1, b: { c: 2 }, d: [1, 2, 3] };
const cloned = deepClone(original);
console.log(cloned); // Output: 'original' but cloned
```
19 changes: 19 additions & 0 deletions snippets/javascript/string-manipulation/generate-uuid.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
title: Generate UUID
description: Generates a UUID (v4) string.
author: jjcantu
tags: uuid, generate, string
---

```js
function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}

// Usage:
console.log(generateUUID()); // Output: "a1b2c3d4-e5f6-4g7h-8i9j-k0l1m2n3o4p5"
```
Loading