Skip to content

Instantly share code, notes, and snippets.

View sayyedhammadali's full-sized avatar

Sayyed Hammad Ali sayyedhammadali

View GitHub Profile
@sayyedhammadali
sayyedhammadali / random-number-in-range.txt
Last active March 11, 2023 04:33
Get a random number in a specific range
const randomNumberInRange = (min = 0, max = 100) => Math.floor(Math.random() * (max - min + 1)) + min;
randomNumberInRange()
// Result: Default random number range is 0 - 100, so you get a number between 0 and 100.
randomNumberInRange(100, 200)
// Result: You will get a random number between 100 and 200, where 100 is min range and 200 is max range.
@sayyedhammadali
sayyedhammadali / date-valid.txt
Created October 3, 2021 10:01
Check if Date is Valid
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid("December 17, 1995 03:24:00");
// Result: true
@sayyedhammadali
sayyedhammadali / cookie.txt
Created October 3, 2021 09:54
Get Value of a brower Cookie
@sayyedhammadali
sayyedhammadali / remove-array-duplicates.txt
Last active October 5, 2021 18:17
Remove Duplicates in an Array
const removeDuplicates = (arr) => [...new Set(arr)];
removeDuplicates([31, 56, 12, 31, 45, 12, 31]);
//[ 31, 56, 12, 45 ]
@sayyedhammadali
sayyedhammadali / random-boolean.txt
Created October 3, 2021 09:40
Get a random boolean (true/false)
const randomBoolean = () => Math.random() >= 0.5;
console.log(randomBoolean());
// Result: a 50/50 change on returning true of false
@sayyedhammadali
sayyedhammadali / clear-cookies.txt
Created October 3, 2021 09:39
Clear All Cookies
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
@sayyedhammadali
sayyedhammadali / day-of-year.txt
Created October 3, 2021 09:36
Find the day of year
const dayOfYear = (date) =>
Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date());
// Result: 272
@sayyedhammadali
sayyedhammadali / touch-supported.txt
Created October 3, 2021 09:32
Check if the current user has touch events supported
const touchSupported = () => {
('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
console.log(touchSupported());
// Result: will return true if touch events are supported, false if not
@sayyedhammadali
sayyedhammadali / array-average.txt
Last active October 5, 2021 09:53
Get the Average of an Array of Number
const average = arr => arr.reduce((a, b) => a + b) / arr.length;
average([21, 56, 23, 122, 67])
//57.8
@sayyedhammadali
sayyedhammadali / get-url-params.txt
Last active October 16, 2021 12:34
Get Query Params from URL
const getParameters = (URL) => JSON.parse('{"' + decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') +'"}');
getParameters("https://www.google.de/search?q=cars&start=40");
// Result: { q: 'cars', start: '40' }