function capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
//console.log(capitalizeFirstLetter('hello')); // Output: 'Hello'
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
//console.log(getRandomNumber(1, 10)); // Output: Random number between 1 and 10
function validEmail(email) {
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailPattern.test(email);
}
//console.log(validEmail('test@example.com')); // Output: true
function calculateAge(birthdate) {
const birthYear = new Date(birthdate).getFullYear();
const currentYear = new Date().getFullYear();
return currentYear - birthYear;
}
//console.log(calculateAge('1990-05-15')); // Output: Current age based on birthdate
function reverseArray(arr) {
return arr.slice().reverse();
}
//const originalArray = [1, 2, 3, 4, 5];
//console.log(reverseArray(originalArray)); // Output: [5, 4, 3, 2, 1]
function groupBy(array, key) {
return array.reduce((result, item) => {
(result[item[key]] = result[item[key]] || []).push(item);
return result;
}, {});
}
/*
const data = [
{ category: 'A', value: 1 },
{ category: 'B', value: 2 },
{ category: 'A', value: 3 }
];
console.log(groupBy(data, 'category'));
*/
// Output: { A: [ { category: 'A', value: 1 }, { category: 'A', value: 3 } ],
// B: [ { category: 'B', value: 2 } ] }
function getRandomElement(arr) {
const randomIndex = Math.floor(Math.random() * arr.length);
return arr[randomIndex];
}
//const fruits = ['apple', 'banana', 'cherry', 'orange'];
//console.log(getRandomElement(fruits)); // Output: Random fruit
function formatTime(hours, minutes) {
const formattedHours = hours.toString().padStart(2, '0');
const formattedMinutes = minutes.toString().padStart(2, '0');
return `${formattedHours}:${formattedMinutes}`;
}
//console.log(formatTime(9, 30)); // Output: '09:30'
function formatDate(date, language) {
const options = { year: 'numeric', month: 'long', day: 'numeric' };
return date.toLocaleDateString(language, options);
}
/*
const today = new Date();
console.log(formatDate(today, 'en-US')); // Output: August 17, 2023
console.log(formatDate(today, 'fr-FR')); // Output: 17 août 2023
*/
/*
language settings common in Europe:
1. **English**: `en-US` (United States), `en-GB` (United Kingdom), `en-AU` (Australia), `en-CA` (Canada), etc.
2. **French**: `fr-FR` (France), `fr-BE` (Belgium), `fr-CA` (Canada), etc.
3. **German**: `de-DE` (Germany), `de-AT` (Austria), `de-CH` (Switzerland), etc.
4. **Spanish**: `es-ES` (Spain), `es-MX` (Mexico), `es-AR` (Argentina), etc.
5. **Italian**: `it-IT` (Italy), `it-CH` (Switzerland), etc.
6. **Portuguese**: `pt-PT` (Portugal), `pt-BR` (Brazil), etc.
7. **Dutch**: `nl-NL` (Netherlands), `nl-BE` (Belgium), etc.
8. **Swedish**: `sv-SE` (Sweden)
9. **Danish**: `da-DK` (Denmark)
10. **Norwegian**: `no-NO` (Norway), `nb-NO` (Bokmål), `nn-NO` (Nynorsk)
11. **Finnish**: `fi-FI` (Finland)
12. **Russian**: `ru-RU` (Russia)
13. **Greek**: `el-GR` (Greece), `el-CY` (Cyprus)
14. **Polish**: `pl-PL` (Poland)
15. **Czech**: `cs-CZ` (Czech Republic)
16. **Hungarian**: `hu-HU` (Hungary)
17. **Romanian**: `ro-RO` (Romania)
18. **Bulgarian**: `bg-BG` (Bulgaria)
19. **Croatian**: `hr-HR` (Croatia)
20. **Slovak**: `sk-SK` (Slovakia)
21. **Slovenian**: `sl-SI` (Slovenia)
22. **Estonian**: `et-EE` (Estonia)
23. **Latvian**: `lv-LV` (Latvia)
24. **Lithuanian**: `lt-LT` (Lithuania)
25. **Irish**: `ga-IE` (Ireland)
26. **Maltese**: `mt-MT` (Malta)
27. **Icelandic**: `is-IS` (Iceland)
28. **Luxembourgish**: `lb-LU` (Luxembourg)
*/
function getDaysDiff(date1, date2) {
const timeDiff = Math.abs(date2 - date1);
return Math.ceil(timeDiff / (1000 * 3600 * 24));
}
//const startDate = new Date('2023-08-01');
//const endDate = new Date('2023-08-17');
//console.log(getDaysDiff(startDate, endDate)); // Output: 16
function isValidURL(url) {
const urlPattern = /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/i;
return urlPattern.test(url);
}
//console.log(isValidURL('https://www.example.com')); // Output: true
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
//console.log(isLeapYear(2024)); // Output: true
function calculateDistanceBetweenPoints(x1, y1, x2, y2) {
return Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
}
//Not to be used with azimuth values, earth is a globe.
//console.log(calculateDistanceBetweenPoints(1, 2, 4, 6)); // Output: 5
function calculateHaversineDistance(lat1, lon1, lat2, lon2) {
const R = 6371; // Earth's radius in kilometers
const dLat = degToRad(lat2 - lat1);
const dLon = degToRad(lon2 - lon1);
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(degToRad(lat1)) * Math.cos(degToRad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
function degToRad(degrees) {
return degrees * (Math.PI / 180);
}
//console.log(calculateHaversineDistance(34.0522, -118.2437, 40.7128, -74.0060)); // Output: Distance in kilometers
function ExcelRound(number, decimalPlaces) {
const factor = Math.pow(10, decimalPlaces);
const roundedValue = Math.round(number * factor);
return roundedValue / factor;
}
//console.log(ExcelRound(4.723, 2)); // Output: 4.72
//console.log(ExcelRound(4.725, 2)); // Output: 4.72
//console.log(ExcelRound(4.726, 2)); // Output: 4.73
function calculateGCD(a, b) {
if (b === 0) return a;
return calculateGCD(b, a % b);
}
/*This function calculates the greatest common divisor (GCD) of two numbers using the Euclidean algorithm.*/
//console.log(calculateGCD(48, 18)); // Output: 6
function generateRandomPassword(length) {
const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let password = '';
for (let i = 0; i < length; i++) {
const randomIndex = Math.floor(Math.random() * charset.length);
password += charset[randomIndex];
}
return password;
}
//console.log(generateRandomPassword(10)); // Output: Random password with 10 characters
function convertToRoman(number) {
const romanNumerals = {
1000: 'M', 900: 'CM', 500: 'D', 400: 'CD',
100: 'C', 90: 'XC', 50: 'L', 40: 'XL',
10: 'X', 9: 'IX', 5: 'V', 4: 'IV', 1: 'I'
};
let result = '';
for (const value in romanNumerals) {
while (number >= value) {
result += romanNumerals[value];
number -= value;
}
}
return result;
}
//console.log(convertToRoman(1984)); // Output: 'MCMLXXXIV'
function postDataToWebService(url, data, callback) {
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
const responseData = JSON.parse(xhr.responseText);
callback(null, responseData);
} else {
callback(`HTTP error! Status: ${xhr.status}`);
}
}
};
xhr.send(JSON.stringify(data));
}
/*
const dataToSend = {
name: 'John Doe',
email: 'john@example.com'
};
const apiUrl = 'https://api.example.com/endpoint'; // Replace with your actual API URL
postDataToWebService(apiUrl, dataToSend, (error, response) => {
if (!error) {
console.log('Response from server:', response);
} else {
console.error('Error:', error);
}
});
*/
Obviously drop comments and minify before use…
function removeCommentsFromText(text) {
// Regular expression to match single-line comments
const singleLineRegex = /\/\/.*$/gm;
// Regular expression to match multi-line comments
const multiLineRegex = /\/\*[\s\S]*?\*\//g;
// Remove single-line comments
const textWithoutSingleLineComments = text.replace(singleLineRegex, '');
// Remove multi-line comments
const textWithoutComments = textWithoutSingleLineComments.replace(multiLineRegex, '');
return textWithoutComments;
}
const javascriptCode = `
// This is a single-line comment
const x = 5;
/*
This is a multi-line comment
that spans multiple lines.
*/
function foo() {
// This is another comment
return 42;
}
`;
const codeWithoutComments = removeCommentsFromText(javascriptCode);
console.log(codeWithoutComments);