Skip to content

Instantly share code, notes, and snippets.

@renatocfrancisco
Created August 1, 2023 13:00
Show Gist options
  • Save renatocfrancisco/7a3dd4f9f1c72a57ee898bc931eda27d to your computer and use it in GitHub Desktop.
Save renatocfrancisco/7a3dd4f9f1c72a57ee898bc931eda27d to your computer and use it in GitHub Desktop.
const capitalize = (str) => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;
const calculatePercent = (value, total) => Math.round((value / total) * 100)
const getRandomItem = (items) => items[Math.floor(Math.random() * items.length)];
const removeDuplicates = (arr) => [...new Set(arr)];
const sortBy = (arr, key) => arr.sort((a, b) => a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0);
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
const countOccurrences = (arr, value) => arr.reduce((a, v) => (v === value ? a + 1 : a), 0);
const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
const pluck = (objs, key) => objs.map((obj) => obj[key]);
const insert = (arr, index, newItem) => [...arr.slice(0, index), newItem, ...arr.slice(index)];
console.log('capitalize')
console.log(capitalize('hello world'))
console.log('calculatePercent')
console.log(calculatePercent(5, 10))
console.log('getRandomItem')
console.log(getRandomItem([1, 2, 3]))
console.log('removeDuplicates')
console.log(removeDuplicates([1, 2, 3, 3, 3, 3, 4, 5]))
console.log('sortBy')
console.log(sortBy([{ name: 'John', age: 25 }, { name: 'Jane', age: 31 }], 'age'))
console.log('isEqual')
console.log(isEqual([1], [1]))
console.log('countOccurrences')
console.log(countOccurrences([1, 1, 2, 1, 2, 3], 1))
console.log('wait')
wait(1000).then(() => console.log('Hello!'));
console.log('pluck')
console.log(pluck([{ name: 'John' }, { name: 'Jane' }], 'name'))
console.log('insert')
console.log(insert([1, 2, 3, 4], 2, 5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment