1.0.0 • Published 4 years ago
dezhu-util-snippets v1.0.0
How To Use NPM
npm install util-snippets --save
import { allEqual } from 'util-snippets'
How To Run Debugging Locally
git clone https://github.com/czero1995/util-snippets.git
cd util-snippets
npm install
npm run build
Test Online
https://codesandbox.io/s/serene-wilbur-6uy5q
NPM Package Url
https://www.npmjs.com/package/util-snippets
Document
/**
* This snippet checks whether all elements of the array are equal
* allEqual([1, 2, 3, 4, 5, 6]); // false
* allEqual([1, 1, 1, 1]); // true
**/
const allEqual = arr => arr.every(val => val === arr[0]);
/**
* This snippet returns the average of two or more numerical values.
* average(...[1, 2, 3]); // 2
* average(1, 2, 3); // 2
*/
const average = (...nums) => {
return nums.reduce((acc, val) => acc + val, 0) / nums.length;
};
/**
* This snippet checks whether the bottom of a page is visible.
* bottomVisible(); // true
*/
const bottomVisible = () => document.documentElement.clientHeight + window.scrollY >=(document.documentElement.scrollHeight || document.documentElement.clientHeight);
/**
* This snippet capitalizes the first letter of every word in a given string.
* capitalizeEveryWord('hello world!'); // 'Hello World!'
*/
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
/**
* This snippet converts a non-array value into array.
* castArray('foo'); // ['foo']
* castArray([1]); // [1]
*/
const castArray = val => (Array.isArray(val) ? val : [val]);
/**
* This snippet removes false values from an array.
* compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); // 1,2
* [1, 2, 3, "a", "s", 34]
*/
const compact = arr => arr.filter(Boolean);
/**
* This snippet counts the occurrences of a value in an array.
* countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3
*/
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
/**
* This snippet returns the current URL.
* currentURL(); // 'https://medium.com/@fatosmorina'
*/
const currentURL = () => window.location.href;
/**
* This snippet finds the difference between two arrays.
* difference([1, 2, 3], [1, 2, 4]); // [3]
*/
const difference = (a, b) => {
const s = new Set(b);
return a.filter(x => !s.has(x));
};
/**
* This snippet removes duplicate values in an array.
* filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1, 2, 3, 4, 5]
*/
const filterNonUnique = arr => [...new Set(arr)];
/**
*This snippet executes a function for each element of an array starting from the array’s last element.
* forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1'
*/
const forEachRight = arr => {
return arr.slice(0).reverse();
};
/**
* This snippet can be used to get the time from a Date object as a string.
* getColonTimeFromDate(new Date()); // "08:38:00"
*/
const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);
/**
* This snippet can be used to find the difference in days between two dates.
* getDaysDiffBetweenDates(new Date('2019-01-13'), new Date('2019-01-15')); // 2
*/
const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 _ 3600 _ 24);
/**
* This snippet can be used to redirect from HTTP to HTTPS in a particular domain.
* httpsRedirect(); // If you are on http://mydomain.com, you are redirected to https://mydomain.com
*/
const httpsRedirect = () => {
if (location.protocol !== "https:")
location.replace("https://" + location.href.split("//")[1]);
};
/**
* This snippet can be used to get an array with elements that are included in two other arrays.
* intersection([1, 2, 3], [4, 3, 2]); // [2, 3]
*/
const intersection = (a, b) => {
const s = new Set(b);
return a.filter(x => s.has(x));
};
/**
* This snippet can be used to check whether a date is after another date.
* isAfterDate(new Date(2010, 10, 21), new Date(2010, 10, 20)); // true
*/
const isAfterDate = (dateA, dateB) => dateA > dateB;
/**
* This snippet can be used to check whether a date is before another date.
* isBeforeDate(new Date(2010, 10, 20), new Date(2010, 10, 21)); // true
*/
const isBeforeDate = (dateA, dateB) => dateA < dateB;
/**
* This snippet can be used to determine whether the current runtime environment is a browser. This is helpful for avoiding errors when running front-end modules on the server (Node).
* isBrowser(); // true (browser)
* isBrowser(); // false (Node)
*/
const isBrowser = () => ![typeof window, typeof document].includes("undefined");
/**
* This snippet can be used to determine whether a string is lower case.
* isLowerCase('abc'); // true
* isLowerCase('a3@$'); // true
* isLowerCase('Ab4'); // false
*/
const isLowerCase = str => str === str.toLowerCase();
/**
* This snippet can be used to check whether a value is null or undefined.
* isNil(null); // true
* isNil(undefined); // true
*/
const isNil = val => val === undefined || val === null;
/**
* This snippet can be used to check whether a value is null.
* isNull(null); // true
*/
const isNull = val => val === null;
/**
* This snippet can be used to check whether a date is before another date.
* isSameDate(new Date(2010, 10, 20), new Date(2010, 10, 20)); // true
*/
const isSameDate = (dateA, dateB) => dateA.toISOString() === dateB.toISOString();
/**
* This snippet can be used to check whether a string is a valid JSON.
* isValidJSON('{"name":"Adam","age":20}'); // true
* isValidJSON('{"name":"Adam",age:"20"}'); // false
* isValidJSON(null); // true
*/
const isValidJSON = str => {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
};
/**
* This snippet returns the n largest elements from a list. If n is greater than or equal to the list’s length, then it will return the original list (sorted in descending order).
* maxN([1, 2, 3]); // [3]
* maxN([1, 2, 3], 2); // [3,2]
*/
const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);
/**
* This snippet returns the n smallest elements from a list. If n is greater than or equal to the list’s length, then it will return the original list (sorted in ascending order).
* minN([1, 2, 3]); // [1]
* minN([1, 2, 3], 2); // [1,2]
*/
const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
/**
* This snippet can be used to generate a random hexadecimal color code.
* randomHexColorCode(); // "#e34155"
*/
const randomHexColorCode = () => {
let n = (Math.random() _ 0xfffff _ 1000000).toString(16);
return "#" + n.slice(0, 6);
};
/**
* This snippet can be used to generate an array with n random integers in a specified range.
* randomIntArrayInRange(12, 35, 10); // [ 34, 14, 27, 17, 30, 27, 20, 26, 21, 14 ]
*/
const randomIntArrayInRange = (min, max, n = 1) =>
Array.from(
{ length: n },
() => Math.floor(Math.random() \* (max - min + 1)) + min
);
/**
* This snippet can be used to generate a random integer in a specified range.
* randomIntegerInRange(0, 5); // 3
*/
const randomIntegerInRange = (min, max) => Math.floor(Math.random() \* (max - min + 1)) + min;
/**
* This snippet can be used to return a random number in a specified range.
* randomNumberInRange(2, 10); // 6.0211363285087005
*/
const randomNumberInRange = (min, max) => Math.random() \* (max - min) + min;
/**
* This snippet can be used to do a redirect to a specified URL.
* redirect('https://google.com');
*/
const redirect = (url, asLink = true) => asLink ? (window.location.href = url) : window.location.replace(url);
/**
* This snippet can be used to get a random number from an array.
* sample([3, 7, 9, 11]); // 9
*/
const sample = arr => arr[Math.floor(Math.random() * arr.length)];
/**
* This snippet can be used to do a smooth scroll to the top of the current page.
* scrollToTop();
*/
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
};
/**
* This snippet can be used to delay the execution of an asynchronous function by putting it into sleep.
* async function sleepyWork() {
console.log("I'm going to sleep for 1 second.");
await sleep(1000);
console.log('I woke up after 1 second.');
}
*/
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
/**
* This snippet can be used to smoothly scroll the element on which it is called into the visible area of the browser window.
* smoothScroll('#fooBar'); // scrolls smoothly to the element with the id fooBar
* smoothScroll('.fooBar'); // scrolls smoothly to the first element with a class of fooBar
*/
const smoothScroll = element =>
document.querySelector(element).scrollIntoView({
behavior: "smooth"
});
/**
* This snippet can be used to find the sum of two or more numbers or arrays.
* sum(1, 2, 3, 4); // 10
* sum(...[1, 2, 3, 4]); // 10
*/
const sum = (...arr) => {
return [...arr].reduce((acc, val) => acc + val, 0);
};
/**
* This snippet can be used to find the union of two arrays, resulting in an array that has elements that come from both arrays but that do not repeat.
* union([1, 2, 3], [4, 3, 2]); // [1,2,3,4]
*/
const union = (a, b) => Array.from(new Set([...a, ...b]));
/**
* This snippet uses ES6 Set and the …rest operator to get every element only once.
* uniqueElements([1, 2, 2, 3, 4, 4, 5]); // [1, 2, 3, 4, 5]
*/
const uniqueElements = arr => [...new Set(arr)];
/**
* This snippet can be used to determine whether the current runtime environment is Android.
* isAndroid() // true
*/
const isAndroid = () => {
const ua = navigator.userAgent.toLowerCase();
return ua.indexOf("Android") > -1 || ua.indexOf("Adr") > -1;
};
/**
* This snippet can be used to determine whether the current runtime environment is iOS .
* isAndroid() // true
*/
const isIos = () => {
const ua = navigator.userAgent;
return !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
};
Reference Article
1.0.0
4 years ago