Skip to content

Instantly share code, notes, and snippets.

@rohailtaha
Last active March 16, 2024 11:33
Show Gist options
  • Save rohailtaha/46b2d87178f572576581673db939df59 to your computer and use it in GitHub Desktop.
Save rohailtaha/46b2d87178f572576581673db939df59 to your computer and use it in GitHub Desktop.
Reusable javascript code snippets
export const MONTHS: Record<number, string> = {
0: 'January',
1: 'February',
2: 'March',
3: 'April',
4: 'May',
5: 'June',
6: 'July',
7: 'August',
8: 'September',
9: 'October',
10: 'November',
11: 'December',
};
export const MONTHS_SHORT: Record<number, string> = {
0: 'Jan',
1: 'Feb',
2: 'Mar',
3: 'Apr',
4: 'May',
5: 'Jun',
6: 'Jul',
7: 'Aug',
8: 'Sep',
9: 'Oct',
10: 'Nov',
11: 'Dec',
};
// Set url in middleware to be accessed inside server components:
async function middleware(request) {
const requestHeaders = new Headers(request.headers);
requestHeaders.set('x-url', request.url);
return NextResponse.next({
request: {
headers: requestHeaders,
},
});
}
// inside the server component, use it like:
const cookieStore = cookies();
const url = headers().get('x-url')!;
// Given an array of keys, remove them from the object.
// returns the new object
function removeKeys(obj, keysToRemove) {
const newObject = {}
Object.keys(obj).forEach(
key => keysToRemove.includes(key) || (newObject[key] = obj[key])
)
return newObject
}
// Pick certain keys from an object.
// returns the new object
function pickKeys(obj, keysToPick) {
const newObject = {}
Object.keys(obj).forEach(
key => keysToPick.includes(key) && (newObject[key] = obj[key])
)
return newObject
}
// Given an array of keys, remove them from the list items.
// returns a new list with updated items(objects)
function removeKeysFromListItems(list, keys) {
return list.map(item => {
const newObject = {}
Object.keys(item).forEach(key => {
const found = keys.find(keyToRemove => key === keyToRemove)
if (!found) newObject[key] = item[key]
})
return newObject
})
}
// Read contents from a text file.
function loadFileContents() {
// input element of type "file"
const input = document.getElementById("file")
// programmatic click
input.click()
input.addEventListener("change", () => {
const file = input.files[0]
const reader = new FileReader()
reader.addEventListener("load", event => {
const result = event.target.result
// reusult contains the contents of the file!
})
if (file) {
reader.readAsText(file)
}
})
}
// display an uploaded image to html page.
// add an onchange event handler to a file input field and set it to this function
function handleUpload(e) {
var image = document.querySelector(".image")
image.src = URL.createObjectURL(e.target.files[0])
}
// Merge object2 in object1. All the properties of object1 will be copied to object1
// (object2 can override object1). A new object is returned
export function mergeObjects(
object1: Record<any, any>,
object2: Record<any, any>
): Record<any, any> {
const result = { ...object1 }
for (const key in object2) {
result[key] = { ...object2[key] }
}
return result
}
// divide an array into chunks of specific size. The leftover items will be added
// in the last chunk
export function getArrayChunks<T = any>(
array: Array<any>,
chunkSize: number
): Array<Array<T>> {
const chunks: Array<Array<any>> = []
let index = 0
while (index < array.length) {
chunks.push(array.slice(index, index + chunkSize))
index += chunkSize
}
return chunks
}
// Sort Records(objects) In Arrays By Some Key.
// @PARAMS:
// data => array of objects to sort
// key => object key on which sort is based.
// order => DESC | ASC
// limit => number of objects to return in resulting array.
// @RETURN:
// The sorted array.
export const sort = (data, key, order, limit = null) => {
limit = limit ? limit : data.length;
if (order == orders.ASC) {
return data.slice(0, limit).sort(sortAsc);
}
if (order === orders.DESC) {
return data.slice(0, limit).sort(sortDesc);
}
function sortAsc(firstRecord, secondRecord) {
return typeof firstRecord[key] === 'string'
? firstRecord[key].toLowerCase() <= secondRecord[key].toLowerCase()
? -1
: 1
: firstRecord[key] <= secondRecord[key]
? -1
: 1;
}
function sortDesc(firstRecord, secondRecord) {
return typeof firstRecord[key] === 'string'
? firstRecord[key].toLowerCase() >= secondRecord[key].toLowerCase()
? -1
: 1
: firstRecord[key] >= secondRecord[key]
? -1
: 1;
}
};
/**********************************************************************
Remove all extra spaces from a string.
**********************************************************************/
const removeExtraSpaces = str =>
str
.split(' ')
.filter(s => s)
.join(' ');
/**********************************************************************
Check if a string is empty
**********************************************************************/
function isEmpty(str) {
return removeExtraSpaces(str) === ""
}
/**********************************************************************
Check if any key's value is an empty string
**********************************************************************/
function someEmpty(obj) {
return Object.entries(obj).some(([, value]) => {
if (typeof value === "string" || value instanceof String) {
return isEmpty(value)
}
})
}
/**********************************************************************
See if one string (parent) starts with another string (child)
**********************************************************************/
const stringStarts = (parentString, childString) =>
removeExtraSpaces(parentString)
.toLowerCase()
.startsWith(removeExtraSpaces(childString).toLowerCase());
/**********************************************************************
See if one string (parent) includes another string (child)
**********************************************************************/
const stringIncludes = (parentString, childString) =>
removeExtraSpaces(parentString)
.toLowerCase()
.includes(removeExtraSpaces(childString).toLowerCase());
/**********************************************************************
Adjust text area height according to content without adding
a scroll.
**********************************************************************/
function adjustTextAreaHeight() {
textAreaElement.style.height = '1px';
const scrollHeight = textAreaElement.scrollHeight;
textAreaElement.style.height = `${scrollHeight}px`;
}
/**********************************************************************
Generate a random string of provided length
**********************************************************************/
function generateRandomString(length: number): string {
const characters =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++) {
const randomIndex = Math.floor(Math.random() * characters.length);
result += characters.charAt(randomIndex);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment