Skip to content

Instantly share code, notes, and snippets.

View AitorAlejandro's full-sized avatar

Aitor Alejandro Herrera AitorAlejandro

View GitHub Profile
@AitorAlejandro
AitorAlejandro / getMaxFromArrayOfObjects.js
Created March 13, 2022 16:52
Get the max prop value from an object array
const objectList = [
{ value: 1 },
{ value: 2 },
{ value: 3 },
{ value: 4 },
{ value: 5 }
];
const maxValue = Math.max(...objectList.map(x => x.value));
// maxValue -> 5
@AitorAlejandro
AitorAlejandro / arrayRangeOfNumbers.js
Created March 13, 2022 16:49
Create an array with a range of numbers
const start = 0;
const end = 100;
const step = 10;
const arrayLength = Math.floor(((end - start) / step)) + 1;
const range = [...Array(arrayLength).keys()].map(x => (x * step) + start);
// [0,10,20,30,40,50,60,70,80,90,100]
@AitorAlejandro
AitorAlejandro / loopover.js
Created March 13, 2022 16:41
Loop over an object to access both key and value
const obj = { id: 1, name: 'laptop', price: 1200 };
Object.entries(obj).forEach(([key, value]) => {
console.log(key, value);
});
@AitorAlejandro
AitorAlejandro / addPropsToObjByCond.js
Created March 13, 2022 16:34
Conditionally add properties to an object
const condition1 = true;
const condition2 = false;
const person = {
id: 'uuid-1234',
name: 'John',
...(condition1 && { propA: 'A' }),
...(condition2 && { propB: 'B' }),
};
@AitorAlejandro
AitorAlejandro / randomItem.ts
Created March 11, 2022 10:31
Get a random item of an array
const randomItem = <T>(arr: T[]): T => arr[(Math.random() * arr.length) | 0];
randomItem(<number[]>[1, 2, 3, 4, 5]); // -> 4
@AitorAlejandro
AitorAlejandro / removeTrailingSlash.ts
Created March 11, 2022 10:30
Removes the trailing slash of a string
const removeTrailingSlash = (value: string): string => value && value.charAt(value.length - 1) === '/' ? value.slice(0, -1) : value;
removeTrailingSlash('foo-bar/'); // -> foo-bar
@AitorAlejandro
AitorAlejandro / randomHexColor.ts
Created March 11, 2022 10:26
Generates a random hex color
const randomHexColor = (): string => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0')}`;
randomHexColor(); // -> #dc7c40
@AitorAlejandro
AitorAlejandro / numberToLetter.ts
Created March 11, 2022 10:22
Converts a number to char/letter
const numberToLetter = (value: number): string => String.fromCharCode(94 + value);
numberToLetter(4); // -> b
@AitorAlejandro
AitorAlejandro / randomNumberString.ts
Created March 11, 2022 10:19
Generate a random number string based on the current time
const randomNumberString = (): string => new Date().getTime() + Math.random().toString(36).slice(2);
randomNumberString(); // -> 1646617484381wml196a8iso
@AitorAlejandro
AitorAlejandro / randomInteger.ts
Created March 11, 2022 10:16
Generates a random integer based on current time
const randomInteger = (): number => new Date().getTime();
randomInteger(); // -> 1646617367345