Skip to content

Instantly share code, notes, and snippets.

@manavm1990
Last active August 11, 2020 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manavm1990/9b8ef7294d88da151a8227bab9067b60 to your computer and use it in GitHub Desktop.
Save manavm1990/9b8ef7294d88da151a8227bab9067b60 to your computer and use it in GitHub Desktop.
My utility functions.
const convertSecondsToMinutesAndSeconds = (secs) => new Date(secs * 1000).toISOString().substring(14, 19)
/**
* Given a 'string date,' get the age in years.
* @param {string} d - 'string date' like from 'date input'
* @returns {number}
*/
function getAgeFromDate(d) {
return Math.floor((new Date() - new Date(d)) * 3.17098e-11));
}
/**
* Given a full directory and file path, split this into the directory path and file name
* @param {string} fullPath
* @returns {Array[string]} - First element is the directory path and other is file name
*/
export const fileDirSplit = (fullPath) => {
const pathStrSplit = fullPath.split('/')
const fileName = pathStrSplit.pop()
const directoryPath = pathStrSplit.join('/')
return [directoryPath, fileName]
}
/**
* Given a path to a JSON file, kindly give back JS
* @param files {Array[string]} - File paths relative to execution context
*/
export const getJSFromJSONFiles = (files) => Promise.all(files.map(async file => JSON.parse(await fs.readFile(file, 'utf-8'))))
/**
* Convert all 'prices' that might be strings into 'floating numbers'.
* @param arr {Array[Object]} - Each object should have a property 'price'
* @return {Array[Object]} - Any string price has been 'numberified'
*/
export const numberifyPrices = (arr) => arr.map(el => {
// Remove commas if it's a string
el.price = typeof el.price === 'string' ? el.price.replace(/,/g, '') : el.price
el.price = parseFloat(el.price)
return el
})
// formElements comes from event.target.elements
export const processFormSubmissions = (formElements) => Array.from(formElements)
.filter(({ id }) => id)
.reduce(
(submissionDeets, currentEl) => {
submissionDeets[currentEl.id] = currentEl.value
return submissionDeets
},
{}
);
export const removeDuplicates = (arr) => [...new Set(arr)]
export const textifyHTML = (html) =>
html
.replace(/(<([^>]+)>)/gi, '')
.replace(/&nbsp;/gi, '')
.replace(/\r?\n|\r/g, ' ')
.split(' ')
.filter((str) => str.length)
.join(' ')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment