Skip to content
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

[Snippets] Added 20 new JavaScript snippets across multiple categories #229

Closed
wants to merge 9 commits into from
18 changes: 18 additions & 0 deletions snippets/javascript/array-manipulation/combine-arrays.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
title: Combine Arrays
description: Concatenates two arrays into one.
author: JanluOfficial
tags: array,concat
---

```js
function combineArrays(array1, array2) {
return array1.concat(array2);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This snippet does not quite align with QuickSnip guidelines, as is simply a wrapper for a standard library of JS

Copy link
Contributor Author

@JanluOfficial JanluOfficial Jan 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll remove this one if requested by a reviewer with write access

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ACR1209 i right, this doesn't align at all with quicksnip guidelines, Please read them it's something that's written in them

}

// Usage:
const array1 = [1, 2, 3];
const array2 = [1, 2, 3];
const combinedArray = combineArrays(array1, array2);
console.log(combinedArray); // Output: [1, 2, 3, 1, 2, 3]
```
18 changes: 18 additions & 0 deletions snippets/javascript/array-manipulation/union-arrays.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
title: Union Arrays
description: Combines two arrays into one with unique elements.
author: JanluOfficial
tags: array, set
---

```js
function unionArrays(array1, array2) {
return Array.from(new Set([...array1, ...array2]));
}

// Usage:
const array1 = [1, 2, 3];
const array2 = [2, 3, 4];
const unionArray = unionArrays(array1, array2);
console.log(unionArray); // Output: [1, 2, 3, 4]
```
55 changes: 55 additions & 0 deletions snippets/javascript/color-manipulation/hex-to-hsl-color.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
---
title: Hex to HSL Color
description: Converts HEX color values to HSL color values.
author: JanluOfficial
tags: validation,url
---

```js
function hexToHsl(hex) {
// Remove the '#' if present
hex = hex.replace(/^#/, '');

// Convert HEX to RGB
let r = parseInt(hex.substring(0, 2), 16) / 255;
let g = parseInt(hex.substring(2, 4), 16) / 255;
let b = parseInt(hex.substring(4, 6), 16) / 255;

// Find the min, max, and delta
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const delta = max - min;

// Calculate Lightness
let l = (max + min) / 2;

// Calculate Saturation
let s = 0;
if (delta !== 0) {
s = delta / (1 - Math.abs(2 * l - 1));
}

// Calculate Hue
let h = 0;
if (delta !== 0) {
if (max === r) {
h = ((g - b) / delta) % 6;
} else if (max === g) {
h = (b - r) / delta + 2;
} else if (max === b) {
h = (r - g) / delta + 4;
}
h = Math.round(h * 60); // Convert to degrees
if (h < 0) h += 360;
}

// Convert saturation and lightness to percentages
s = +(s * 100).toFixed(2);
l = +(l * 100).toFixed(2);

return { h, s, l };
}

// Usage:
hexToHsl("#3498db"); // Returns: { h: 204, s: 69.87, l: 53.14 }
```
42 changes: 42 additions & 0 deletions snippets/javascript/color-manipulation/hsl-to-hex-color.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
---
title: HSL to Hex Color
description: Converts HSL color values to HEX color values.
author: JanluOfficial
tags: validation,url
---

```js
function hslToHex(h, s, l) {
s /= 100;
l /= 100;

let c = (1 - Math.abs(2 * l - 1)) * s;
let x = c * (1 - Math.abs((h / 60) % 2 - 1));
let m = l - c / 2;

let r = 0, g = 0, b = 0;

if (0 <= h && h < 60) {
r = c; g = x; b = 0;
} else if (60 <= h && h < 120) {
r = x; g = c; b = 0;
} else if (120 <= h && h < 180) {
r = 0; g = c; b = x;
} else if (180 <= h && h < 240) {
r = 0; g = x; b = c;
} else if (240 <= h && h < 300) {
r = x; g = 0; b = c;
} else if (300 <= h && h < 360) {
r = c; g = 0; b = x;
}

r = Math.round((r + m) * 255).toString(16).padStart(2, '0');
g = Math.round((g + m) * 255).toString(16).padStart(2, '0');
b = Math.round((b + m) * 255).toString(16).padStart(2, '0');

return `#${r}${g}${b}`;
}

// Usage:
hslToHex(204, 69.87, 53.14); // Returns: "#3498db"
```
15 changes: 15 additions & 0 deletions snippets/javascript/color-manipulation/random-hex-color.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
title: Random Hex Color
description: Generates a completely random hex color.
author: JanluOfficial
tags: color,hex,random
---

```js
function getRandomHexColor() {
return '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0');
}

// Usage:
getRandomHexColor(); // Returns: "#f904d7" (random)
```
18 changes: 18 additions & 0 deletions snippets/javascript/color-manipulation/random-hsl-color.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
title: Random HSL Color
description: Generates a completely random HSL color.
author: JanluOfficial
tags: color,hsl,random
---

```js
function getRandomHslColor() {
const h = Math.floor(Math.random() * 360);
const s = Math.floor(Math.random() * 101);
const l = Math.floor(Math.random() * 101);
return { h, s, l };
}

// Usage:
getRandomHslColor(); // Returns: { h: 357, s: 53, l: 49 } (random)
```
18 changes: 18 additions & 0 deletions snippets/javascript/color-manipulation/random-rgb-color.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
title: Random RGB Color
description: Generates a completely random RGB color.
author: JanluOfficial
tags: color,rgb,random
---

```js
function getRandomRgbColor() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return { r, g, b };
}

// Usage:
getRandomRgbColor(); // Returns: { r: 189, g: 120, b: 201 } (random)
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
title: Add a CSS Class to an element
description: Add a CSS class to a HTML element.
author: JanluOfficial
tags: css,style
---

```js
function addClass(element, className) {
if (element && className) {
element.classList.add(className);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The classList.add() method already does the intended functionality you're presenting

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typing element.classList.add() is longer than addClass() which is why I'm including it this way

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I get it! 💯

This is the same as my response on .remove(), so we could just keep the thread there if you'll like as is an interesting boundary to comment on 😀

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Snippet shouldn't wrap around an std functionality, even if the function name is 10x longer, Also valid for the .remove() one too

}
}

// Usage:
const myElement = document.getElementById("myElement");
addClass(myElement, "myClass");
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
title: Get Computed Style from an Element
description: Retrieve the computed style of a specific CSS property from an HTML element.
author: JanluOfficial
tags: css,style
---

```js
function getComputedStyle(element, styleProp) {
if (element && styleProp) {
return window.getComputedStyle(element, null).getPropertyValue(styleProp);
}
return null;
}

// Usage:
const myElement = document.getElementById("myElement");
toggleClass(myElement, "background-color");
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
title: Remove a CSS Class from an element
description: Remove a CSS class from a HTML element.
author: JanluOfficial
tags: css,style
---

```js
function removeClass(element, className) {
if (element && className) {
element.classList.remove(className);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The classList.remove() method already does the intended functionality you're presenting

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typing element.classList.remove() is longer than removeClass() which is why I'm including it this way

Copy link
Contributor

@ACR1209 ACR1209 Jan 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I understand your point 💯

But at the end of the day, is a difference of 4 characters and removes the option of multi argument class removal. Plus adds a bit more bloat to the code base.

This was common with IE10 as it did throw errors

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as for add-a-css-class-to-an-element.

}
}

// Usage:
const myElement = document.getElementById("myElement");
removeClass(myElement, "myClass");
```
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as add-a-css-class-to-an-element

Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
title: Toggle a CSS Class on an Element
description: Toggle a CSS class on an HTML element.
author: JanluOfficial
tags: css,style
---

```js
function toggleClass(element, className) {
if (element && className) {
element.classList.toggle(className);
}
}

// Usage:
const myElement = document.getElementById("myElement");
toggleClass(myElement, "myClass");
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
title: Clear all items from localStorage
description: Removes all values in localStorage, no matter what key they're under.
author: JanluOfficial
tags: localStorage,storage
---

```js
localStorage.clear();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is simply a usage of a language standard function

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I included this considering that C:\xampp\htdocs\quicksnip\snippets\javascript\basics\hello-world.md is essentially also just a standard language function

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, you're definitely right on that, hello worlds are a kinda of the exception to the rule I think.

But for the rest of snippets we do consider the contributing guidelines "Does the standard library of my language provide an easy way of doing this ?" boundary

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If requested by a reviewer with write access, I will remove this

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ACR is right, Btw I've noticed you are not taking feedback from the community Even when it's backed by the guidelines, The community has an important role into the reviewing process, please take them a bit more into account.

Hello world, is infact a specific snippet, and it should be (in most cases) the only one of it's "type", so no, as per the guidelines, this doesn't qualify as a snippet

```
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
title: Get all keys from localStorage
description: Gets all the keys currently assigned in localStorage.
author: JanluOfficial
tags: localStorage,storage
---

```js
function getAllKeysFromLocalStorage() {
const keys = [];
for (let i = 0; i < localStorage.length; i++) {
keys.push(localStorage.key(i));
}
return keys;
}

// Usage:
getAllKeysFromLocalStorage(); // Returns all keys from localStorage
```
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as for the others, it just wraps over an std function, it adds a little bit of functionnality over it... But this functionnality isn't the main goal of the snippet, so in it's current state it's not valid

Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
title: Update Item in localStorage
description: Updates an item with a specific key in localStorage.
author: JanluOfficial
tags: localStorage,storage
---

```js
function updateLocalStorageItem(key, newValue) {
if (localStorage.getItem(key) !== null) {
localStorage.setItem(key, newValue);
} else {
console.error(`Item with key "${key}" does not exist in LocalStorage.`);
}
}

// Usage:
updateLocalStorageItem('username', 'newUsername');
```
18 changes: 18 additions & 0 deletions snippets/javascript/object-manipulation/combine-objects.md
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Already exists as merge-objects-deeply

Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
title: Combine Objects
description: Merges two objects into one.
author: JanluOfficial
tags: object,merge
---

```js
function combineObjects(obj1, obj2) {
return { ...obj1, ...obj2 };
}

// Usage:
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const combinedObject = combineObjects(obj1, obj2);
console.log(combinedObject); // Output: { a: 1, b: 2, c: 3, d: 4 }
```
16 changes: 16 additions & 0 deletions snippets/javascript/validation/validate-a-credit-card-number.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
title: Validate a Credit Card Number
description: Validates a Credit Card Number for a variety of major international credit card formats, including Visa, MasterCard, American Expres, Diners Club and JCB.
author: JanluOfficial
tags: validation,url
---

```js
function validateCreditCardNumber(cardNumber) {
const cardRegex = /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|6(?:011|5[0-9]{2})[0-9]{12}|(?:2131|1800|35\d{3})\d{11})$/;
return cardRegex.test(cardNumber);
}

// Usage:
validateCreditCardNumber("4111111111111111"); // Returns: true
```
16 changes: 16 additions & 0 deletions snippets/javascript/validation/validate-a-url.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
title: Validate a URL
description: Validates a URL.
author: JanluOfficial
tags: validation,url
---

```js
function validateURL(url) {
const urlRegex = /^(https?|http?|ftp):\/\/[^\s/$.?#].[^\s]*$/i;
return urlRegex.test(url);
}

// Usage:
validateURL("https://www.example.com"); // Returns: true
```
Loading
Loading