Skip to content

Commit

Permalink
Merge pull request #151 from jjcantu/new-snippets-js
Browse files Browse the repository at this point in the history
[Snippets] - add a few useful JS snippets
  • Loading branch information
Mathys-Gasnier authored Jan 3, 2025
2 parents 862ae12 + bcfc368 commit 5fa53c3
Show file tree
Hide file tree
Showing 5 changed files with 145 additions and 0 deletions.
56 changes: 56 additions & 0 deletions public/consolidated/javascript.json
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,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 @@ -384,6 +402,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:\ntoScientificNotation(12345); // Returns: '1.23e+4'\ntoScientificNotation(0.0005678); // Returns: '5.68e-4'\ntoScientificNotation(1000); // Returns: '1.00e+3'\ntoScientificNotation(0); // Returns: '0e+0'\ntoScientificNotation(-54321); // Returns: '-5.43e+4'\n"
},
{
"title": "Format 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 @@ -470,6 +501,19 @@
"contributors": [],
"code": "function countProperties(obj) {\n return Object.keys(obj).length;\n}\n\n// Usage:\nconst obj = { a: 1, b: 2, c: 3 };\ncountProperties(obj); // Returns: 3\n"
},
{
"title": "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 @@ -709,6 +753,18 @@
"contributors": [],
"code": "function getInitials(name) {\n return name.split(' ').map(part => part.charAt(0).toUpperCase()).join('');\n}\n\n// Usage:\ngetInitials('John Doe'); // Returns: 'JD'\n"
},
{
"title": "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"
```

0 comments on commit 5fa53c3

Please sign in to comment.