OneLiners are brief snippets of code which might be utilized in many locations within the codebase. This can be a assortment of 150+ one-liners written in typescript.
Desk of content material
🙏 Hope you want 👍 this submit, let’s get all the way down to enterprise. 🚀
Array one liners ☝️
1. Solid a price as an array
export const castArray = <T, _>(worth: T | T[]): T[] => (Array.isArray(worth) ? worth : [value]);
// castArray(1); // [1]
// castArray([1, 2, 3]); // [1, 2, 3]
2. Examine if an array is empty
export const isEmpty = <T, _>(arr: T[]): boolean => Array.isArray(arr) && !arr.size;
// isEmpty([]); // true
// isEmpty([1, 2, 3]); // false
3. Clone an array
export const clone = <T, _>(arr: T[]): T[] => [...arr];
// clone([1,2,3]); // [1,2,3]
4. Examine two arrays
export const isEqual = <T, _>(a: T[], b: T[]): boolean => JSON.stringify(a) === JSON.stringify(b);
// isEqual([1, 2, 3], [1, 2, 3]); // true
// isEqual([1, 2, 3], [1, '2', 3]); // false
5. Examine two arrays no matter order
export const isEqualWithoutOrder = <T, _>(a: T[], b: T[]): boolean =>
JSON.stringify([...new Set(a)].type()) === JSON.stringify([...new Set(b)].type());
// isEqualWithoutOrder([1, 2, 3], [1, 2, 3]); // true
// isEqualWithoutOrder([1, 2, 3], [1, 3, 2]); // true
// isEqualWithoutOrder([1, 2, 3], [1, '2', 3]); // false
6. Convert an array of objects to a single object
export const toObject = <T extends Report<string, any>, Okay extends keyof T>(arr: T[], key: Okay): Report<string, T> =>
arr.cut back((a, b) => ({ ...a, [b[key]]: b }), {});
// toObject(
// [
// { id: '1', name: 'Alpha', gender: 'Male' },
// { id: '2', name: 'Bravo', gender: 'Male' },
// { id: '3', name: 'Charlie', gender: 'Female' },
// ],
// 'id'
// );
/_
{
'1': { id: '1', title: 'Alpha', gender: 'Male' },
'2': { id: '2', title: 'Bravo', gender: 'Male' },
'3': { id: '3', title: 'Charlie', gender: 'Feminine' },
}
7. Convert an array of strings to numbers
export const toNumbers = (arr: string[]): quantity[] => arr.map(Quantity);
// toNumbers(['2', '3', '4']); // [2, 3, 4]
8. Rely by the properties of an array of objects
export const countBy = <T extends Report<string, string>, Okay extends keyof T>(
arr: T[],
prop: Okay
): Report<string, quantity> =>
arr.cut back((prev, curr) => ((prev[curr[prop]] = ++prev[curr[prop]] || 1), prev), {} as Report<string, quantity>);
// countBy(
// [
// { branch: 'audi', model: 'q8', year: '2019' },
// { branch: 'audi', model: 'rs7', year: '2020' },
// { branch: 'ford', model: 'mustang', year: '2019' },
// { branch: 'ford', model: 'explorer', year: '2020' },
// { branch: 'bmw', model: 'x7', year: '2020' }
// ],
// 'department'
// );
// { 'audi': 2, 'ford': 2, 'bmw': 1 }
9. Rely the occurrences of a price in an array
export const countOccurrences = <T, _>(arr: T[], val: T): quantity => arr.cut back((a, v) => (v === val ? a + 1 : a), 0);
// countOccurrences([2, 1, 3, 3, 2, 3], 2); // 2
10. Rely the occurrences of array parts
export const countOccurrencesElements = <T extends string | quantity>(arr: T[]): Report<T, quantity> =>
arr.cut back((prev, curr) => ((prev[curr] = ++prev[curr] || 1), prev), {} as Report<T, quantity>);
// countOccurrencesElements([2, 1, 3, 3, 2, 3]); // { '1': 1, '2': 2, '3': 3 }
11. Create an array of cumulative sum
export const accumulate = (arr: quantity[]): quantity[] =>
arr.cut back((a, b, i) => (i === 0 ? [b] : [...a, b + a[i - 1]]), [0]);
// accumulate([1, 2, 3, 4]); // [1, 3, 6, 10]
12. Create an array of numbers within the given vary
export const vary = (min: quantity, max: quantity): quantity[] => [...Array(max - min + 1).keys()].map((i) => i + min);
// vary(5, 10); // [5, 6, 7, 8, 9, 10]
13. Discover the closest quantity from an array
export const closest = (arr: quantity[], n: quantity): quantity => arr.type((a, b) => Math.abs(a - n) - Math.abs(b - n))[0];
// closest([29, 87, 8, 78, 97, 20, 75, 33, 24, 17], 50); // 33
14. Discover the index of the final matching merchandise of an array
export const lastIndex = <T, _>(arr: T[], predicate: (a: T) => boolean): quantity =>
arr.map((merchandise) => predicate(merchandise)).lastIndexOf(true);
// lastIndex([1, 3, 5, 7, 9, 2, 4, 6, 8], (i) => i % 2 === 1); // 4
// lastIndex([1, 3, 5, 7, 9, 8, 6, 4, 2], (i) => i > 6); // 5
15. Discover the index of the utmost merchandise of an array
export const indexOfMax = (arr: quantity[]): quantity => arr.cut back((prev, curr, i, a) => (curr > a[prev] ? i : prev), 0);
// indexOfMax([1, 3, 9, 7, 5]); // 2
// indexOfMax([1, 3, 7, 7, 5]); //
16. Discover the index of the minimal merchandise of an array
export const indexOfMin = (arr: quantity[]): quantity => arr.cut back((prev, curr, i, a) => (curr < a[prev] ? i : prev), 0);
// indexOfMin([6, 4, 8, 2, 10]); // 3
// indexOfMin([6, 4, 2, 2, 10]); // 2
17. Discover the size of the longest string in an array
export const findLongest = (phrases: string[]): quantity => Math.max(...phrases.map((el) => el.size));
// findLongest(['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']); // 6
18. Discover the utmost merchandise of an array by given key
export const maxBy = <T extends Report<string, any>, Okay extends keyof T>(arr: T[], key: Okay): T =>
arr.cut back((a, b) => (a[key] >= b[key] ? a : b), {} as T);
// const individuals = [
// { name: 'Bar', age: 24 },
// { name: 'Baz', age: 32 },
// { name: 'Foo', age: 42 },
// { name: 'Fuzz', age: 36 }
// ];
// maxBy(individuals, 'age'); // { title: 'Foo', age: 42 }
19. Discover the utmost merchandise of an array
export const max = (arr: quantity[]): quantity => Math.max(...arr);
// max([1, 3, 9, 7, 5]); // 9
20. Discover the minimal merchandise of an array by given key
export const minBy = <T extends Report<string, any>, Okay extends keyof T>(arr: T[], key: Okay): T =>
arr.cut back((a, b) => (a[key] < b[key] ? a : b), {} as T);
// const individuals = [
// { name: 'Bar', age: 24 },
// { name: 'Baz', age: 32 },
// { name: 'Foo', age: 42 },
// { name: 'Fuzz', age: 36 },
// ];
// minBy(individuals, 'age'); // { title: 'Bar', age: 24 }
21. Discover the minimal merchandise of an array
export const min = (arr: quantity[]): quantity => Math.min(...arr);
// min([1, 3, 9, 7, 5]); // 1
22. Get all arrays of consecutive parts
export const getConsecutiveArrays = <T, _>(arr: T[], measurement: quantity): T[][] =>
measurement > arr.size ? [] : arr.slice(measurement - 1).map((_, i) => arr.slice(i, measurement + i));
// getConsecutiveArrays([1, 2, 3, 4, 5], 2); // [[1, 2], [2, 3], [3, 4], [4, 5]]
// getConsecutiveArrays([1, 2, 3, 4, 5], 3); // [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
// getConsecutiveArrays([1, 2, 3, 4, 5], 6); // []
23. Get all n-th gadgets of an array
export const getNthItems = <T, _>(arr: T[], nth: quantity): T[] => arr.filter((_, i) => i % nth === nth - 1);
// getNthItems([1, 2, 3, 4, 5, 6, 7, 8, 9], 2); // [2, 4, 6, 8]
// getNthItems([1, 2, 3, 4, 5, 6, 7, 8, 9], 3); // [3, 6, 9]
24. Get indices of a price in an array
export const indices = <T>(arr: T[], worth: T): quantity[] =>
arr.cut back((acc, v, i) => (v === worth ? [...acc, i] : acc), [] as quantity[]);
// indices(['h', 'e', 'l', 'l', 'o'], 'l'); // [2, 3]
// indices(['h', 'e', 'l', 'l', 'o'], 'w'); // []
25. Get the typical of an array
export const common = (arr: quantity[]): quantity => arr.cut back((a, b) => a + b, 0) / arr.size;
// common([1, 2, 3, 4, 5]); // 3
26. Get the intersection of arrays
export const getIntersection = <T, _>(a: T[], ...arr: T[][]): T[] =>
[...new Set(a)].filter((v) => arr.each((b) => b.consists of(v)));
// getIntersection([1, 2, 3], [2, 3, 4, 5]); // [2, 3]
// getIntersection([1, 2, 3], [2, 3, 4, 5], [1, 3, 5]); // [3]
27. Get the rank of an array of numbers
export const rating = (arr: quantity[]): quantity[] => arr.map((x, y, z) => z.filter((w) => w > x).size + 1);
// rating([80, 65, 90, 50]); // [2, 3, 1, 4]
// rating([80, 80, 70, 50]); // [1, 1, 3, 4]
// rating([80, 80, 80, 50]); // [1, 1, 1, 4]
28. Get the sum of an array of numbers
export const sum = (arr: quantity[]): quantity => arr.cut back((a, b) => a + b, 0);
// solar([1, 2, 3, 4, 5]); // 15
29. Get the distinctive values of an array
export const distinctive = <T>(arr: T[]): T[] => [...new Set(arr)];
// distinctive([1, 2, 3, 1, 4, 4, 5]); // [1, 2, 3, 4, 5]
30. Get union of arrays
export const union = <T, _>(...arr: T[][]): T[] => [...new Set(arr.flat())];
// union([1, 2], [2, 3], [3]); // [1, 2, 3]
31. Group an array of objects by a key
export const groupBy = <T extends Report<string, any>, Okay extends keyof T>(arr: T[], key: Okay): Report<string, T[]> =>
arr.cut back((acc, merchandise) => ((acc[item[key]] = [...(acc[item[key]] || []), merchandise]), acc), {} as Report<string, T[]>);
// groupBy(
// [
// { branch: 'audi', model: 'q8', year: '2019' },
// { branch: 'audi', model: 'rs7', year: '2020' },
// { branch: 'ford', model: 'mustang', year: '2019' },
// { branch: 'ford', model: 'explorer', year: '2020' },
// { branch: 'bmw', model: 'x7', year: '2020' }
// ],
// 'department'
// );
{
// audi: [
// { branch: 'audi', model: 'q8', year: '2019' },
// { branch: 'audi', model: 'rs7', year: '2020' }
// ],
// bmw: [
// { branch: 'bmw', model: 'x7', year: '2020' }
// ],
// ford: [
// { branch: 'ford', model: 'mustang', year: '2019' },
// { branch: 'ford', model: 'explorer', year: '2020' }
// ],
// }
32. Intersperse ingredient between parts
export const intersperse = <T>(a: T[], s: T): T[] => [...Array(2 * a.length - 1)].map((_, i) => (i % 2 ? s : a[i / 2]));
// intersperse(['A', 'B', 'C'], "https://dev.to/"); // ['A', "https://dev.to/", 'B', "https://dev.to/", 'C']
// intersperse([<li>A</li>, <li>B</li>, <li>C</li>], <li>/</li>); // [<li>A</li>, <li>/</li>, <li>B</li>, <li>/</li>, <li>C</li>]
33. Merge two arrays
export const merge = <T, _>(a: T[], b: T[]): T[] => [...a, ...b];
// merge([1, 2, 3], [4, 5, 6]); // [1, 2, 3, 4, 5, 6]
34. Partition an array primarily based on a situation
// export const partition = <T, _>(arr: T[], standards: (a: T) => boolean): T[][] =>
// arr.cut back((acc, i) => (acc[criteria(i) ? 0 : 1].push(i), acc), [[], []]);
// partition([1, 2, 3, 4, 5], (n) => n % 2); // [[1, 3, 5], [2, 4]]
35. Take away duplicate values in an array
export const removeDuplicate = <T, _>(arr: T[]): T[] => arr.filter((i) => arr.indexOf(i) === arr.lastIndexOf(i));
// removeDuplicate(['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']); // ['h', 'e', 'w', 'r', 'd']
36. Take away falsy values from array
export const removeFalsy = <T, _>(arr: T[]): T[] => arr.filter(Boolean);
// ['a string', true, 5, 'another string']
37. Repeat an array
export const repeat = <T, _>(arr: T[], n: quantity): T[] => Array(n).fill(arr).flat();
repeat([1, 2, 3], 3); // [1, 2, 3, 1, 2, 3, 1, 2, 3]
38. Shuffle an array
export const shuffle = <T, _>(arr: T[]): T[] =>
arr
.map((a) => ({ type: Math.random(), worth: a }))
.type((a, b) => a.type - b.type)
.map((a) => a.worth);
// shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); // [9, 1, 10, 6, 8, 5, 2, 3, 7, 4]
39. Kind an array of things by given key
export const sortBy = <T extends Report<string, any>, Okay extends keyof T>(arr: T[], okay: Okay): T[] =>
arr.concat().type((a, b) => (a[k] > b[k] ? 1 : a[k] < b[k] ? -1 : 0));
// const individuals = [
// { name: 'Foo', age: 42 },
// { name: 'Bar', age: 24 },
// { name: 'Fuzz', age: 36 },
// { name: 'Baz', age: 32 }
// ];
// sortBy(individuals, 'age');
// [
// { name: 'Bar', age: 24 },
// { name: 'Baz', age: 32 },
// { name: 'Fuzz', age: 36 },
// { name: 'Foo', age: 42 },
// ]
40. Kind an array of numbers
export const type = (arr: quantity[]): quantity[] => arr.type((a, b) => a - b);
// type([1, 5, 2, 4, 3]); // [1, 2, 3, 4, 5]
41. Break up an array into chunks
export const chunk = <T>(arr: T[], measurement: quantity): T[][] =>
arr.cut back((acc, e, i) => (i % measurement ? acc[acc.length - 1].push(e) : acc.push([e]), acc), [] as T[][]);
// chunk([1, 2, 3, 4, 5, 6, 7, 8], 3); // [[1, 2, 3], [4, 5, 6], [7, 8]]
// chunk([1, 2, 3, 4, 5, 6, 7, 8], 4); // [[1, 2, 3, 4], [5, 6, 7, 8]]
42. Swap the rows and columns of a matrix
export const transpose = <T>(matrix: T[][]): T[][] => matrix[0].map((col, i) => matrix.map((row) => row[i]));
// transpose([
// // [
// [1, 2, 3], // [1, 4, 7],
// [4, 5, 6], // [2, 5, 8],
// [7, 8, 9] // [3, 6, 9],
// ]); // ]
43. Swap two array gadgets
export const swapItems = <T, _>(a: T[], i: quantity, j: quantity): T[] =>
(a[i] && a[j] && [...a.slice(0, i), a[j], ...a.slice(i + 1, j), a[i], ...a.slice(j + 1)]) || a;
// swapItems([1, 2, 3, 4, 5], 1, 4); // [1, 5, 3, 4, 2]
44. Get all subsets of an array
export const getSubsets = <T>(arr: T[]): T[][] =>
arr.cut back((prev, curr) => prev.concat(prev.map((okay) => okay.concat(curr))), [[]] as T[][]);
// getSubsets([1, 2]); // [[], [1], [2], [1, 2]]
// getSubsets([1, 2, 3]); // [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
Date one liners ☝️
1. Add AM PM suffix to an hour
export const suffixAmPm = (h: quantity): string => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? 'am' : 'pm'}`;
// suffixAmPm(0); // '12am'
// suffixAmPm(5); // '5am'
// suffixAmPm(12); // '12pm'
// suffixAmPm(15); // '3pm'
// suffixAmPm(23); // '11pm'
2. Calculate the variety of distinction days between two dates
export const diffDays = (date: Date, otherDate: Date): quantity =>
Math.ceil(Math.abs(date.valueOf() - otherDate.valueOf()) / (1000 _ 60 _ 60 * 24));
// diffDays(new Date('2014-12-19'), new Date('2020-01-01')); // 1839
3. Calculate the variety of months between two dates
export const monthDiff = (startDate: Date, endDate: Date): quantity =>
Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth());
// monthDiff(new Date('2020-01-01'), new Date('2021-01-01')); // 12
4. Examine two dates
export const evaluate = (a: Date, b: Date): boolean => a.getTime() > b.getTime();
// evaluate(new Date('2020-03-30'), new Date('2020-01-01')); // true
5. Convert a date to YYYY-MM-DD format
export const formatYmd = (date: Date): string => date.toISOString().slice(0, 10);
// formatYmd(new Date()); // 2020-05-06
6. Convert a date to YYYY-MM-DD HH:MM:SS format
export const formatYmdHis = (date: Date): string => date.toISOString().slice(0, 19);
// formatYmdHis(new Date()); // 2020-05-06T15:00:00.000Z
7. Convert seconds to hh:mm:ss format
export const formatSeconds = (s: quantity): string => new Date(s * 1000).toISOString().substr(11, 8);
// formatSeconds(200); // 00:03:20
// formatSeconds(500); // 00:08:20
8. Extract yr, month, day, hour, minute, second and millisecond from a date
export const extract = (date: Date): string[] =>
date
.toISOString()
.cut up(/[^0-9]/)
.slice(0, -1);
// extract(new Date()); // ['2020', '05', '06', '15', '00', '00', '00']
9. Format a date for the given locale
export const format = (date: Date, locale: string): string => new Intl.DateTimeFormat(locale).format(date);
// format(new Date(), 'pt-BR'); // 06/05/2020
10. Get the present quarter of a date
export const getQuarter = (d = new Date()): quantity => Math.ceil((d.getMonth() + 1) / 3);
// getQuarter(new Date('2020-01-01')); // 1
11. Get the present timestamp in seconds
export const tseconds = (): quantity => Math.ground(new Date().getTime() / 1000);
// ts(); // 1588888888
12. Get the day of the yr from a date
export const dayOfYear = (date: Date): quantity =>
Math.ground((date.valueOf() - new Date(date.getFullYear(), 0, 0).valueOf()) / (1000 _ 60 _ 60 * 24));
// dayOfYear(new Date(2020, 04, 16)); // 137
13. Get the primary date within the month of a date
export const getFirstDate = (d = new Date()): Date => new Date(d.getFullYear(), d.getMonth(), 1);
// getFirstDate(new Date('2020-01-01')); // 2020-01-01
14. Get the final date within the month of a date
export const getLastDate = (d = new Date()): Date => new Date(d.getFullYear(), d.getMonth() + 1, 0);
// getLastDate(new Date('2020-02-01')); // 2020-02-29
15. Get the month title of a date
export const getMonthName = (date: Date): string =>
[
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
' November',
'December'
][date.getmonth()];
// getMonthName(new Date('2020-01-01')); // January
16.Get the variety of days in given month
export const daysInMonth = (month: quantity, yr: quantity): quantity => new Date(yr, month, 0).getDate();
// daysInMonth(2, 2020); // 29
17. Get the timezone string
export const getTimezone = (): string => Intl.DateTimeFormat().resolvedOptions().timeZone;
// getTimezone(); // 'Asia/Saigon'
18. Get the tomorrow date
export const tomorrow: Date = ((d) => new Date(d.setDate(d.getDate() + 1)))(new Date());
// tomorrow; // 2020-05-07
19. Get the entire variety of days in a yr
export const numberOfDays = (yr: quantity): quantity => (new Date(yr, 1, 29).getDate() === 29 ? 366 : 365);
// numberOfDays(2020); // 366
20. Get the weekday of a date
export const getWeekday = (date: Date): string =>
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][date.getday()];
// getWeekday(new Date('2020-01-01')); // Sunday
21. Get the yesterday date
export const yesterday: Date = ((d) => new Date(d.setDate(d.getDate() - 1)))(new Date());
// yesterday; // 2020-05-06
22. Initialize the present date however set time to midnight
export const midnightOfToday = (): Date => new Date(new Date().setHours(0, 0, 0, 0));
// midnightOfToday(); // 2020-05-06T00:00:00.000Z
23. Kind an array of dates
export const sortDescending = (arr: Date[]): Date[] => arr.type((a, b) => a.getTime() - b.getTime());
// sortDescending([new Date('2020-01-01'), new Date('2020-01-02')]); // [new Date('2020-01-02'), new Date('2020-01-01')]
export const sortAscending = (arr: Date[]): Date[] => arr.type((a, b) => b.getTime() - a.getTime());
// sortAscending([new Date('2020-01-01'), new Date('2020-01-02')]); // [new Date('2020-01-01'), new Date('2020-01-02')]
Features one liners ☝️
1. Field handler
export const boxHandler = (x: any): { subsequent: (f: any) => any; accomplished: (f: any) => any } => ({
subsequent: (f: any) => boxHandler(f(x)),
accomplished: (f: any) => f(x)
});
// const getMoney = (value) => Quantity.parseFloat(value.change(/$/, ''));
// const getPercent = (%) => Quantity.parseFloat(%.change(/%/)) * 0.01;
// const getDiscountPrice = (value, low cost) =>
// boxHandler(getMoney(value))
// .accomplished((cents) => boxHandler(getPercent(low cost)).subsequent((save) => cents - cents * save))
// .accomplished((res) => res);
// getDiscountPrice('$6.00', '20%'); // 4.8
2. Examine if a price is a perform
export const isFunction = (v: any): boolean =>
['[object Function]', '[object GeneratorFunction]', '[object AsyncFunction]', '[object Promise]'].consists of(
Object.prototype.toString.name(v)
);
// isFunction(perform () {}); // true
// isFunction(perform* () {}); // true
// isFunction(async perform () {}); // true
3. Examine if a price is a generator perform
export const isGeneratorFunction = (v: any): boolean =>
Object.prototype.toString.name(v) === '[object GeneratorFunction]';
// isGeneratorFunction(perform () {}); // false
// isGeneratorFunction(perform* () {}); // true
4. Examine if a price is an async perform
export const isAsyncFunction = (v: any): boolean => Object.prototype.toString.name(v) === '[object AsyncFunction]';
// isAsyncFunction(perform () {}); // false
// isAsyncFunction(perform* () {}); // false
// isAsyncFunction(async perform () {}); // true
5. Compose features from left to proper
export const pipe =
(...fns: any[]) =>
(x: any) =>
fns.cut back((y, f) => f(y), x);
// const lowercase = (str) => str.toLowerCase();
// const capitalize = (str) => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;
// const reverse = (str) => str.cut up('').reverse().be part of('');
// const fn = pipe(lowercase, capitalize, reverse);
// We'll execute `lowercase`, `capitalize` and `reverse` so as
// fn('Hey World') === 'dlrow olleH';
6. Compose features from proper to left
export const compose =
(...fns: any[]) =>
(x: any) =>
fns.reduceRight((y, f) => f(y), x);
// const lowercase = (str) => str.toLowerCase();
// const capitalize = (str) => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;
// const reverse = (str) => str.cut up('').reverse().be part of('');
// const fn = compose(reverse, capitalize, lowercase);
// // We'll execute `lowercase`, `capitalize` and `reverse` so as
// fn('Hey World') === 'dlrow olleH';
7. Curry a perform
export const curry = (fn: any, ...args: any[]): any =>
fn.size <= args.size ? fn(...args) : curry.bind(null, fn, ...args);
// const sum = (a, b, c) => a + b + c;
// curry(sum)(1)(2)(3); // 6
// curry(sum)(1, 2, 3); // 6
// curry(sum, 1)(2, 3); // 6
// curry(sum, 1)(2)(3); // 6
// curry(sum, 1, 2)(3); // 6
// curry(sum, 1, 2, 3); // 6
8. Memoize a perform
export const memoize = (fn: any) =>
(
(cache = Object.create(null)) =>
(arg: any) =>
cache[arg] || (cache[arg] = fn(arg))
)();
// Calculate Fibonacci numbers
// const fibo = memoize((n: quantity) => (n <= 2 ? 1 : fibo(n - 1) + fibo(n - 2)));
// fibo(1); // 1
// fibo(2); // 1
// fibo(3); // 2
// fibo(4); // 3
// fibo(5); // 5
// fibo(6); // 8
Math one liners ☝️
1. Calculate the angle of a line outlined by two factors
interface Level {
x: quantity;
y: quantity;
}
export const radiansAngle = (p1: Level, p2: Level): quantity => Math.atan2(p2.y - p1.y, p2.x - p1.x);
// radiansAngle({ x: 0, y: 0 }, { x: 0, y: 1 }); //
export const degreesAngle = (p1: Level, p2: Level): quantity => (Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180) / Math.PI;
// degreesAngle({ x: 0, y: 0 }, { x: 0, y: 3 }); // 90
2. Calculate the space between two factors
interface Level {
x: quantity;
y: quantity;
}
export const distance = (p1: Level, p2: Level): quantity =>
Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
// distance({ x: 0, y: 0 }, { x: 0, y: 1 }); // 1
3. Calculate the linear interpolation between two numbers
export const lerp = (a: quantity, b: quantity, quantity: quantity): quantity => (1 - quantity) _ a + quantity _ b;
// lerp(0, 1, 0.5); // 0.5
4. Calculate the midpoint between two factors
interface Level {
x: quantity;
y: quantity;
}
export const midpoint = (p1: Level, p2: Level): quantity[] => [(p1.x + p2.x) / 2, (p1.y + p2.y) / 2];
// midpoint({ x: 0, y: 0 }, { x: 0, y: 1 }); // [0, 0.5]
5. Calculate the slope between two factors
interface Level {
x: quantity;
y: quantity;
}
export const slope = (p1: Level, p2: Level): quantity => (p2.y - p1.y) / (p2.x - p1.x);
// slope({ x: 0, y: 0 }, { x: 0, y: 1 }); // 1
6. Calculate the perpendicular slope between two factors
interface Level {
x: quantity;
y: quantity;
}
export const perpendicularSlope = (p1: Level, p2: Level): quantity => -1 / slope(p1, p2);
// perpendicularSlope({ x: 0, y: 0 }, { x: 0, y: 1 }); // -1
7. Examine if some extent is inside a rectangle
interface Level {
x: quantity;
y: quantity;
}
interface Rect {
backside: quantity;
left: quantity;
high: quantity;
proper: quantity;
}
export const isInside = (level: Level, rect: Rect): boolean =>
level.x > rect.left && level.x < rect.proper && level.y > rect.high && level.y < rect.backside;
// isInside({ x: 0, y: 0 }, { left: 0, high: 0, proper: 1, backside: 1 }); // true
8. Examine if some extent is inside a circle
interface Level {
x: quantity;
y: quantity;
}
export const isInsideCircle = (level: Level, heart: Level, radius: quantity): boolean => {
const distance = Math.sqrt(Math.pow(level.x - heart.x, 2) + Math.pow(level.y - heart.y, 2));
return distance < radius;
};
// isInsideCircle({ x: 0, y: 0 }, { x: 0, y: 0 }, 1); // true
9. Examine if a rectangle incorporates different one
interface Rect {
x1: quantity;
x2: quantity;
y1: quantity;
y2: quantity;
}
export const incorporates = (a: Rect, b: Rect): boolean => a.x1 <= b.x1 && a.y1 <= b.y1 && a.x2 >= b.x2 && a.y2 >= b.y2;
// incorporates({ x1: 0, y1: 0, x2: 1, y2: 1 }, { x1: 0, y1: 0, x2: 1, y2: 1 }); // true
10. Examine if a rectangle overlaps one other one
interface Rect {
x1: quantity;
x2: quantity;
y1: quantity;
y2: quantity;
}
export const overlaps = (a: Rect, b: Rect): boolean => !(a.x2 < b.x1 || a.x1 > b.x2 || a.y2 < b.y1 || a.y1 > b.y2);
// overlaps({ x1: 0, y1: 0, x2: 1, y2: 1 }, { x1: 0, y1: 0, x2: 1, y2: 1 }); // true
11. Examine if a rectangle is inside one other one
interface Rect {
x1: quantity;
x2: quantity;
y1: quantity;
y2: quantity;
}
export const isInsideRect = (a: Rect, b: Rect): boolean => a.x1 >= b.x1 && a.y1 >= b.y1 && a.x2 <= b.x2 && a.y2 <= b.y2;
// isInsideRect({ x1: 0, y1: 0, x2: 1, y2: 1 }, { x1: 0, y1: 0, x2: 1, y2: 1 }); // true
12. Examine if a rectangle is outdoors one other one
interface Rect {
x1: quantity;
x2: quantity;
y1: quantity;
y2: quantity;
}
export const isOutsideRect = (a: Rect, b: Rect): boolean =>
a.x1 <= b.x1 || a.y1 <= b.y1 || a.x2 >= b.x2 || a.y2 >= b.y2;
// isOutsideRect({ x1: 0, y1: 0, x2: 1, y2: 1 }, { x1: 0, y1: 0, x2: 1, y2: 1 }); // true
13. Examine if a rectangle is touching one other one
interface Rect {
x1: quantity;
x2: quantity;
y1: quantity;
y2: quantity;
}
export const isTouchingRect = (a: Rect, b: Rect): boolean =>
a.x1 === b.x1 || a.x2 === b.x2 || a.y1 === b.y1 || a.y2 === b.y2;
// isTouchingRect({ x1: 0, y1: 0, x2: 1, y2: 1 }, { x1: 0, y1: 0, x2: 1, y2: 1 }); // true
14. Convert levels to radians
export const degsToRads = (deg: quantity): quantity => (deg * Math.PI) / 180.0;
// degsToRads(90); // 1.5707963267948966
15. Convert radians to levels
export const radsToDegs = (rad: quantity): quantity => (rad * 180.0) / Math.PI;
// radsToDegs(1.5707963267948966); // 90
16. Normalize the ratio of a quantity in a spread
export const normalizeRatio = (worth: quantity, min: quantity, max: quantity): quantity => (worth - min) / (max - min);
// normalizeRatio(0, 0, 1); // 0
17. Spherical a quantity to the closest a number of of a given worth
export const roundNearest = (worth: quantity, nearest: quantity): quantity => Math.spherical(worth / nearest) * nearest;
// roundNearest(100, 30); // 90
// roundNearest(200, 30); // 210
// roundNearest(200, 40); // 200
18. Spherical a quantity to a given variety of decimal locations
export const roundToDecimal = (worth: quantity, decimals: quantity): quantity => {
const issue = Math.pow(10, decimals);
return Math.spherical(worth * issue) / issue;
};
// roundToDecimal(1.2345, 2); // 1.23
19. Calculate the typical of arguments
export const common = (...args: quantity[]): quantity => args.cut back((a, b) => a + b) / args.size;
// common(1, 2, 3, 4); // 2.5
20.Calculate the division of arguments
export const division = (...args: quantity[]): quantity => args.cut back((a, b) => a / b);
// division(1, 2, 3, 4); // 0.04166666666666666
21. Calculate the factorial of a quantity
export const factorial = (n: quantity): quantity => (n <= 1 ? 1 : n * factorial(n - 1));
// factorial(2); // 2
// factorial(3); // 6
// factorial(4); // 24
// factorial(5); // 120
// factorial(6); // 720
22. Calculate the mod of assortment index
export const mod = (a: quantity, b: quantity): quantity => ((a % b) + b) % b;
// mod(-1, 5); // 4
// mod(3, 5); // 3
// mod(6, 5); // 1
23. Calculate the rest of division of arguments
export const the rest = (...args: quantity[]): quantity => args.cut back((a, b) => a % b);
// the rest(1, 2, 3, 4); // 1
24. Calculate the sum of arguments
export const sum = (...args: quantity[]): quantity => args.cut back((a, b) => a + b);
// sum(1, 2, 3, 4); // 10
25. Clamp a quantity between two values
export const clamp = (val: quantity, min: quantity = 0, max: quantity = 1): quantity => Math.max(min, Math.min(max, val));
// clamp(199, 10, 25); // 25
26. Compute the best frequent divisor between two numbers
export const gcd = (a: quantity, b: quantity): quantity => (b === 0 ? a : gcd(b, a % b));
// gcd(10, 15); // 5
27. Compute the least frequent a number of between two numbers
export const lcm = (a: quantity, b: quantity): quantity => (a * b) / gcd(a, b);
// lcm(10, 15); // 30
28. Compute the median of a group of numbers
export const median = (...args: quantity[]): quantity => {
const sorted = args.type((a, b) => a - b);
const mid = Math.ground(sorted.size / 2);
return sorted.size % 2 !== 0 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
};
// median(1, 2, 3, 4); // 2.5
29. Multiply arguments
export const mul = (...args: quantity[]): quantity => args.cut back((a, b) => a * b);
// mul(1, 2, 3, 4); // 24
30. Subtract arguments
export const subtract = (...args: quantity[]): quantity => args.cut back((a, b) => a - b);
// subtract(1, 2, 3, 4); // -8
Misc one liners ☝️
1. Examine if the code is working in Jest
export const isRunningInJest: boolean = typeof course of !== 'undefined' && course of.env.JEST_WORKER_ID !== undefined;
// isRunningInJest; // true
2. Examine if the code is working in NodeJS
export const isNode: boolean =
typeof course of !== 'undefined' && course of.variations != null && course of.variations.node != null;
// isNode; // true
3. Examine if the code is working within the browser
export const isBrowser: boolean = typeof window === 'object' && typeof doc === 'object';
// isBrowser; // true
4. Clear all cookies
export const clearCookies = (): void =>
doc.cookie
.cut up(';')
.forEach(
(c) => (doc.cookie = c.change(/^ +/, '').change(/=.*/, `=;expires=${new Date().toUTCString()};path=/`))
);
// clearCookies();
5. Convert 3 digits colour to six digits colour
export const toFullHexColor = (colour: string): string =>
`#${(colour.startsWith('#') ? colour.slice(1) : colour)
.cut up('')
.map((c) => `${c}${c}`)
.be part of('')}`;
// toFullHexColor('123'); // '#112233'
// toFullHexColor('#123'); // '#112233'
// toFullHexColor('#abc'); // '#aabbcc'
6. Convert Celsius to Fahrenheit
export const celsiusToFahrenheit = (celsius: quantity): quantity => (celsius * 9) / 5 + 32;
// celsiusToFahrenheit(15); // 59
// celsiusToFahrenheit(0); // 32
// celsiusToFahrenheit(-20); // -4
7. Convert Fahrenheit to Celsius
export const fahrenheitToCelsius = (fahrenheit: quantity): quantity => ((fahrenheit - 32) * 5) / 9;
// fahrenheitToCelsius(59); // 15
8. Convert Celsius to Kelvin
export const celsiusToKelvin = (celsius: quantity): quantity => celsius + 273.15;
// celsiusToKelvin(15); // 298.15
// celsiusToKelvin(0); // 273.15
9. Convert Fahrenheit to Kelvin
export const fahrenheitToKelvin = (fahrenheit: quantity): quantity => ((fahrenheit - 32) * 5) / 9 + 273.15;
// fahrenheitToKelvin(59); // 298.15
10. Convert Kelvin to Celsius
export const kelvinToCelsius = (kelvin: quantity): quantity => kelvin - 273.15;
// kelvinToCelsius(298.15); // 15
// kelvinToCelsius(273.15); // 0
11. Convert Kelvin to Fahrenheit
export const kelvinToFahrenheit = (kelvin: quantity): quantity => (kelvin * 9) / 5 - 459.67;
// kelvinToFahrenheit(298.15); // 59
// kelvinToFahrenheit(273.15); // 32
12. Convert rgb colour to hex
export const rgbToHex = (crimson: quantity, inexperienced: quantity, blue: quantity): string =>
`#${[red, green, blue].map((v) => v.toString(16).padStart(2, '0')).be part of('')}`;
// rgbToHex(0, 255, 255); // '#00ffff'
13. Convert hex colour to rgb
export const hexToRgb = (hex: string): [number, number, number] => {
const [r, g, b] = hex
.slice(1)
.cut up('')
.map((c) => parseInt(c + c, 16));
return [r, g, b];
}; // hexToRgb('#00ffff'); // [0, 255, 255]
// Convert URL parameters to object
export const getUrlParams = (question: string): Report<string, string> =>
Array.from(new URLSearchParams(question)).cut back(
(p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }),
{} as Report<string, string>
);
// getUrlParams(location.search); // Get the parameters of the present URL
// getUrlParams('foo=Foo&bar=Bar'); // { foo: "Foo", bar: "Bar" }
// Duplicate key
// getUrlParams('foo=Foo&foo=Fuzz&bar=Bar'); // { foo: ["Foo", "Fuzz"], bar: "Bar" }
14. Convert object to URL parameters
export const toUrlParams = (obj: Report<string, string | string[]>): string => {
const params = new URLSearchParams();
Object.entries(obj).forEach(([k, v]) => {
if (Array.isArray(v)) {
v.forEach((val) => params.append(okay, val));
} else {
params.append(okay, v);
}
}),
params.toString();
return params.toString();
};
// toUrlParams({ foo: "Foo", bar: "Bar" }); // "foo=Foo&bar=Bar"
15. Decode a JWT token
export const decodeJwt = (token: string): Report<string, string> => {
const [, payload] = token.cut up('.');
return JSON.parse(atob(payload));
};
// decodeJwt('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c');
// { sub: "1234567890", title: "John Doe", iat: 1516239022 }
16. Encode a JWT token
export const encodeJwt = (obj: Report<string, string>): string => {
const payload = JSON.stringify(obj);
const base64Payload = btoa(payload);
const base64Header = btoa(JSON.stringify({ alg: 'none', typ: 'JWT' }));
return `${base64Header}.${base64Payload}`;
};
// encodeJwt({ sub: "1234567890", title: "John Doe", iat: 1516239022 });
// "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ"
17. Detect darkish mode
export const isDarkMode: boolean = window.matchMedia && window.matchMedia('(prefers-color-scheme: darkish)').matches;
// isDarkMode; // true
18. Easing features
export const linear = (t: quantity): quantity => t;
export const easeInQuad = (t: quantity): quantity => t _ t;
export const easeOutQuad = (t: quantity): quantity => t _ (2 - t);
export const easeInOutQuad = (t: quantity): quantity => (t < 0.5 ? 2 _ t _ t : -1 + (4 - 2 _ t) _ t);
export const easeInCubic = (t: quantity): quantity => t _ t _ t;
export const easeOutCubic = (t: quantity): quantity => --t _ t _ t + 1;
export const easeInOutCubic = (t: quantity): quantity =>
t < 0.5 ? 4 _ t _ t _ t : (t - 1) _ (2 _ t - 2) _ (2 * t - 2) + 1;
export const easeInQuart = (t: quantity): quantity => t _ t _ t _ t;
export const easeOutQuart = (t: quantity): quantity => 1 - --t _ t _ t _ t;
export const easeInOutQuart = (t: quantity): quantity => (t < 0.5 ? 8 _ t _ t _ t _ t : 1 - 8 _ --t _ t _ t _ t);
export const easeInQuint = (t: quantity): quantity => t _ t _ t _ t _ t;
export const easeOutQuint = (t: quantity): quantity => 1 + --t _ t _ t _ t _ t;
export const easeInOutQuint = (t: quantity): quantity => (t < 0.5 ? 16 _ t _ t _ t _ t _ t : 1 + 16 _ --t _ t _ t _ t _ t);
export const easeInSine = (t: quantity): quantity => 1 + Math.sin((Math.PI / 2) _ t - Math.PI / 2);
export const easeOutSine = (t: quantity): quantity => Math.sin((Math.PI / 2) _ t);
export const easeInOutSine = (t: quantity): quantity => (1 + Math.sin(Math.PI * t - Math.PI / 2)) / 2;
export const easeInElastic = (t: quantity): quantity => (0.04 - 0.04 / t) _ Math.sin(25 _ t) + 1;
export const easeOutElastic = (t: quantity): quantity => ((0.04 _ t) / --t) _ Math.sin(25 _ t);
export const easeInOutElastic = (t: quantity): quantity =>
(t -= 0.5) < 0 ? (0.02 + 0.01 / t) _ Math.sin(50 _ t) : (0.02 - 0.01 / t) _ Math.sin(50 * t) + 1;
19. Emulate a cube throw
export const throwdice = (): quantity => ~~(Math.random() * 6) + 1;
// throwdice(); // 4
// throwdice(); // 1
// throwdice(); // 6
20. Emulate a coin flip
export const flipcoin = (): boolean => Math.random() < 0.5;
// flipcoin(); // true
21. Encode a URL
export const encode = (url: string): string =>
encodeURIComponent(url)
.change(/!/g, '%21')
.change(/~/g, '%7E')
.change(/*/g, '%2A')
.change(/'/g, '%27')
.change(/(/g, '%28')
.change(/)/g, '%29')
.change(/%20/g, '+');
// encode('https://www.google.com/'); // 'httpspercent3Apercent2Fpercent2Fwww.google.compercent2F'
22. Decode a URL
export const decode = (url: string): string => decodeURIComponent(url.change(/+/g, '%20'));
// decode('httpspercent3Apercent2Fpercent2Fwww.google.compercent2F'); // 'https://www.google.com/'
23. Get the present URL
export const getUrl = (): string => window.location.href;
// getUrl(); // 'https://www.google.com/'
24. Get the primary outlined and non null argument
export const coalesce = (...args: any[]): any[] => args.discover((merchandise) => ![undefined, null].consists of(merchandise));
// coalesce(undefined, null, 'helloworld', NaN); // 'helloworld'
25. Get the worth of a param from a URL
export const getParam = (url: string, param: string): string | null =>
new URLSearchParams(new URL(url).search).get(param);
getParam('http://area.com?message=hiya', 'message'); // 'hiya'
26. Get sort of a variable in string
export const getTypeOf = (obj: any): string =>
(Object.prototype.toString.name(obj).match(/[object (.*)]/) as string[])[1];
// getTypeOf('hiya world'); // String
// getTypeOf(1000); // Quantity
// getTypeOf(Infinity); // Quantity
// getTypeOf(true); // Boolean
// getTypeOf(Image()); // Image
// getTypeOf(null); // Null
// getTypeOf(undefined); // Undefined
// getTypeOf({}); // Object
// getTypeOf([]); // Array
// getTypeOf(/[a-z]/g); // RegExp
// getTypeOf(new Date(2021)); // Date
// getTypeOf(new Error()); // Error
// getTypeOf(perform () {}); // Operate
// getTypeOf((a, b) => a + b); // Operate
// getTypeOf(async () => {}); // AsyncFunction
// getTypeOf(doc); // HTMLDocument
27. Redirect the web page to HTTPS whether it is in HTTP
export const redirectHttps = (): string => (location.protocol === 'https:' ? '' : (location.protocol = 'https:'));
28. Run Guarantees in sequence
export const run = (guarantees: Promise<any>[]): Promise<any> =>
guarantees.cut back((p, c) => p.then((rp) => c.then((rc) => [...rp, rc])), Promise.resolve([]));
// run(guarantees).then((outcomes) => {
// // `outcomes` is an array of promise ends in the identical order
// });
29. Run Guarantees in parallel
export const runParallel = (guarantees: Promise<any>[]): Promise<any> => Promise.all(guarantees);
// runParallel(guarantees).then((outcomes) => {
// // `outcomes` is an array of promise ends in the identical order
// });
30. Run Guarantees in parallel and return the ends in the identical order
export const runParallelOrder = (guarantees: Promise<any>[]): Promise<any> =>
Promise.all(guarantees).then((outcomes) => outcomes.cut back((p, c) => [...p, c], []));
// runParallelOrder(guarantees).then((outcomes) => {
// // `outcomes` is an array of promise ends in the identical order
// });
31. Watch for an period of time
export const wait = async (milliseconds: quantity) => new Promise((resolve) => setTimeout(resolve, milliseconds));
// wait(1000).then(() => console.log('accomplished'));
32. Add an ordinal suffix to a quantity
export const addOrdinal = (n: quantity): string => `${n}$`;
// addOrdinal(1); // '1st'
// addOrdinal(2); // '2nd'
// addOrdinal(3); // 'third'
// addOrdinal(11); // 'eleventh'
// addOrdinal(12); // 'thirteenth'
// addOrdinal(13); // 'thirteenth'
33. Convert a quantity to equal characters
export const toChars = (n: quantity): string =>
`${n >= 26 ? toChars(Math.ground(n / 26) - 1) : ''}${'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[n % 26]}`;
// toChars(0); // A
// toChars(1); // B
// toChars(25); // Z
// toChars(26); // AA
// toChars(27); // AB
// toChars(51); // AZ
Objects one liners ☝️
1.Examine if a number of objects are equal
export const isEqual = (...objects: object[]): boolean =>
objects.each((obj) => JSON.stringify(obj) === JSON.stringify(objects[0]));
// isEqual({ foo: 'bar' }, { foo: 'bar' }); // true
// isEqual({ foo: 'bar' }, { bar: 'foo' }); // false
2. Extract values of a property from an array of objects
export const pluck = (objs: any[], property: any) => objs.map((obj) => obj[property]);
// pluck(
// [
// { name: 'John', age: 20 },
// { name: 'Smith', age: 25 },
// { name: 'Peter', age: 30 }
// ],
// 'title'
// ); // ['John', 'Smith', 'Peter']
3. Get the worth at given path of an object
export const getValue = (path: string, obj: any) => path.cut up('.').cut back((acc, c) => acc && acc[c], obj);
// getValue('a.b', { a: { b: 'Hey World' } }); // 'Hey World';
4. Take away all null and undefined properties from an object
export const removeNullUndefined = (obj: Object) =>
Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));
// removeNullUndefined({
// foo: null,
// bar: undefined,
// fuzz: 42,
// }); // { fuzz: 42 }
5. Shallow clone an object
export const shallowCopy = (obj: Object): Object => ({ ...obj });
6. Kind an object by its properties
export const type = (obj: any) =>
Object.keys(obj)
.type()
.cut back((p: any, c: string) => ((p[c] = obj[c]), p), {});
// const colours = {
// white: '#ffffff',
// black: '#000000',
// crimson: '#ff0000',
// inexperienced: '#008000',
// blue: '#0000ff',
// };
// type(colours);
// {
// black: '#000000',
// blue: '#0000ff',
// inexperienced: '#008000',
// crimson: '#ff0000',
// white: '#ffffff',
// }
String one liners ☝️
1. Capitalize a string
export const capitalize = (str: string): string => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;
// capitalize('hiya world'); // 'Hey world'
2. Examine if a path is relative
export const isRelative = (path: string): boolean => !/^([a-z]+:)?[/]/i.check(path);
// isRelative('/foo/bar/baz'); // false
// isRelative('C:foobarbaz'); // false
// isRelative('foo/bar/baz.txt'); // true
// isRelative('foo.md'); // true
3. Examine if a string consists of a repeated character sequence
export const consistsRepeatedSubstring = (str: string): boolean => `${str}${str}`.indexOf(str, 1) !== str.size;
// consistsRepeatedSubstring('aa'); // true
// consistsRepeatedSubstring('aaa'); // true
// consistsRepeatedSubstring('ababab'); // true
// consistsRepeatedSubstring('abc'); // false
4. Examine if a URL is absolute
export const isAbsoluteUrl = (url: string): boolean => /^[a-z][a-z0-9+.-]*:/.check(url);
// isAbsoluteUrl('https://1loc.dev'); // true
// isAbsoluteUrl('https://1loc.dev/foo/bar'); // true
// isAbsoluteUrl('1loc.dev'); // false
// isAbsoluteUrl('//1loc.dev'); // false
5. Examine if two strings are anagram
export const areAnagram = (str1: string, str2: string): boolean =>
str1.toLowerCase().cut up('').type().be part of('') === str2.toLowerCase().cut up('').type().be part of('');
// areAnagram('hear', 'silent'); // true
// areAnagram('they see', 'the eyes'); // true
// areAnagram('node', 'deno'); // true
6. Convert a base64 encoded string to an uint8 array
export const base64ToUint8 = (str: string): Uint8Array => Uint8Array.from(atob(str), (c) => c.charCodeAt(0));
// base64ToUint8('SGVsbG8gV29ybGQ='); // Uint8Array [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
7. Convert a letter to affiliate emoji
export const letterToEmoji = (c: string): string => String.fromCodePoint(c.toLowerCase().charCodeAt(0) + 127365);
// letterToEmoji('a'); // 🇦
// letterToEmoji('b'); // 🇧
8. Convert a string to camelCase
export const toCamelCase = (str: string): string =>
str.trim().change(/[-_s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));
// toCamelCase('background-color'); // backgroundColor
// toCamelCase('-webkit-scrollbar-thumb'); // WebkitScrollbarThumb
// toCamelCase('_hello_world'); // HelloWorld
// toCamelCase('hello_world'); // helloWorld
9. Convert a string to PascalCase
export const toPascalCase = (str: string): string =>
(str.match(/[a-zA-Z0-9]+/g) || []).map((w) => `${w.charAt(0).toUpperCase()}${w.slice(1)}`).be part of('');
// toPascalCase('hiya world'); // 'HelloWorld'
// toPascalCase('hiya.world'); // 'HelloWorld'
// toPascalCase('foo_bar-baz'); // FooBarBaz
10. Convert a string to URL slug
export const slugify = (str: string): string =>
str
.toLowerCase()
.change(/s+/g, '-')
.change(/[^w-]+/g, '');
// slugify('Chapter One: As soon as upon a time...'); // 'chapter-one-once-upon-a-time'
11. Convert a Home windows file path to Unix path
export const toUnixPath = (path: string): string => path.change(/[/]+/g, '/').change(/^([a-zA-Z]+:|./)/, '');
// toUnixPath('./foo/bar/baz'); // foo/bar/baz
// toUnixPath('C:foobarbaz'); // /foo/bar/baz
12. Convert an uint8 array to a base64 encoded string
export const uint8ToBase64 = (arr: Uint8Array): string => Buffer.from(arr).toString('base64');
// uint8ToBase64(Uint8Array.from([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100])); // 'SGVsbG8gV29ybGQ='
13. Convert camelCase to kebab-case and vice versa
export const kebabToCamel = (str: string): string => str.change(/-./g, (m) => m.toUpperCase()[1]);
// kebabToCamel('background-color'); // 'backgroundColor'
export const camelToKebab = (str: string): string => str.change(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
// camelToKebab('backgroundColor'); // 'background-color'
14. Convert snake_case to camelCase
export const snakeToCamel = (str: string): string =>
str.toLowerCase().change(/(_w)/g, (m) => m.toUpperCase().substr(1));
// snakeToCamel('HELLO_world'); // 'helloWorld'
15. Rely the occurrences of a personality in a string
export const countOccurrences = (str: string, char: string): quantity => [...str].filter((merchandise) => merchandise === char).size;
// countOccurrences('a.b.c.d.e', '.'); // 4
16. Format a string
export const format = (str: string, ...vals: string[]): string =>
vals.cut back((s, v, i) => s.change(new RegExp('{' + i + '}', 'g'), v), str);
// const template="My title is {0} and I'm {1} years outdated";
// format(template, 'John', '30');
// // My title is John and I'm 30 years outdated
// format(template, 'Jane', '20');
// // My title is Jane and I'm 20 years outdated
17. Generate a hash of a string
export const hash = (str: string): quantity =>
str.cut up('').cut back((prev, curr) => (Math.imul(31, prev) + curr.charCodeAt(0)) | 0, 0);
// hash('hiya'); // 99162322
18. Get the bottom URL with none parameters
export const baseUrl = (url: string): string => url.cut up('?')[0];
// baseUrl('https://area.com/path/sub/path?foo=bar&hiya=world'); // 'https://area.com/path/sub/path'
19. Get the variety of a personality in a string
export const characterCount = (str: string, char: string): quantity => str.cut up(char).size - 1;
// characterCount('192.168.1.1', '.'); // 3
// characterCount('star wars', 's'); // 2
20. Exchange the primary given variety of characters of a string with one other character
export const masks = (str: string, num: quantity, masks: string): string =>
`${str}`.slice(num).padStart(`${str}`.size, masks);
// masks('1234567890', 3, '*'); // ***4567890
21. Uppercase the primary character of every phrase in a string
export const uppercaseWords = (str: string): string => str.change(/^(.)|s+(.)/g, (c) => c.toUpperCase());
// uppercaseWords('hiya world'); // 'Hey World'