Utils
Collection of my utility functions to make life easier.
execAsync - Asynchronous wrapper for ShellJS
const {code, stdout, stderr} = await execAsync('date')
print(stdout) // prints Fri 27 Mar 2020 06:47:24 PM PDT
ordinalSuffix - Adds ordinal suffix to numbers
ordinalSuffix(2) // add ordinal suffix to number 2
Returns
2nd
filterByKeywords - Filters an array based on list of keywords
const someList = ["I'm a blue dog", "I'm a red dog", "I'm a green dog"]
const searchTerms = ["dog", "red"]
filterByKeywords(someList, searchTerms)
Returns
["I'm a red dog"]
asyncForEach - ForEach method made asynchronous
await asyncForEach(array, (item) => {
// callback
})
differenceInHours - Calulates time in hours between 2 dates
const date = new Date('2020-03-08 05:44:22.185 +00:00') // Random date from a while ago
differenceInHours(date) // Check how many hours ago the date was
Returns
476.69
chunkArray - Split array into multiple equally sized arrays
const sampleArray = ["one", "two", "three", "four", "five", "six"]
chunkArray(sampleArray, 3) // Split array into 3 equal chunks
Returns
[
["one", "two"],
["three", "four"],
["five", "six"]
]
splitArrayToCharLimit - Splits an array into multiple based on max character limit
findFilesByType - Finds nested files in a directory matching the pattern specified
// Find all mp4 files in a directory
findFilesByType("path/to/dir", ".mp4")
addSpace - Adds a set ammount of spaces
// Print Hello World with 5 spaces
console.log(`Hello${addSpace(5)}World`)
Returns
"Hello World"
capitalize - Capitalize the first letter of a string
capitalize("hello")
Returns
"Hello"
sortByKey - Sorts an array by key
sortByKey(array, "key")
groupByProperty - Splits an array based off of a property
const originalArray = [
{
animal: "dog",
color: "brown"
},
{
animal: "dog",
color: "white"
},
{
animal: "cat",
color: "white"
},
]
// Split array based off of the anime type
groupByProperty(originalArray, "animal")
Returns
[
dog: [
{ animal: 'dog', color: 'brown' },
{ animal: 'dog', color: 'white' }
],
cat: [ { animal: 'cat', color: 'white' } ]
]
bytesToSize - Converts bytes into human readable form
const bytes = 1000000 // 1 megabytes in bytes
const converted = bytesToSize(bytes)
Returns
"1 MB"
millisecondsToTime - Converts milliseconds to HH:MM format
// convert 2 minutes in milliseconds to time string
const time = millisecondsToTime(120000)
Returns
2:00
Sleep - Async sleep wrapper
await sleep(1000) // asynchronously sleeps for 1 second