Useful JS code snippets

1. Password Generator

const generatePassword = (length = 8) => {
let CharacterSet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()[]{}';
let password = '';

for (let i = 0; i < length; i++) {
password += CharacterSet.charAt(Math.floor(Math.random() * CharacterSet.length));
}
return password;
};

2. Deep Clone Object

const clone = (item) => {
return JSON.parse(JSON.stringify(item));
};

3. Capitalize string

const capitalize = (string) => {
if (!string) {
return '';
}
string = string.toString().toLocaleLowerCase();
return string.charAt(0).toLocaleUpperCase() + string.slice(1);
};

4. Convert Object to FormData

const JSONToFormData = (data, exclude = []) => {
const formData = new FormData();

Object.keys(data).map((key) => {
if (Array.isArray(data[key])) {
data[key].forEach(value => {
formData.append(`${key}[]`, value);
});
} else if (data[key] !== null && typeof data[key] === 'object' && !(data[key] instanceof File)) {
formData.append(key, JSON.stringify(data[key]));
} else if(typeof data[key] === "undefined") {
formData.delete(key);
} else if(data[key] !== null) {
formData.append(key, data[key]);
} else if(data[key] === null && exclude.includes(key) === false) {
formData.append(key, null);
}
});
return formData;
};

5. Debounce

const debounce = (fn, delay) => {
let timeoutId = null;
return function() {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn.apply(this, arguments), delay);
};
};

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store