Skip to content

Instantly share code, notes, and snippets.

@dotproto
Last active February 14, 2024 01:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dotproto/51d96e9570edaed8374e6a78ab8d18fc to your computer and use it in GitHub Desktop.
Save dotproto/51d96e9570edaed8374e6a78ab8d18fc to your computer and use it in GitHub Desktop.
Helper functions I didn't realize I wanted until I wrote them a few times in several different projects. Uses ES6 module syntax.
// ====================
// = OBJECT HELPERS =
// ====================
export const set = (obj, prop, val) => {
obj[prop] = val
return obj
}
export const extractObj = (obj, prop) =>
Object.keys(obj).map(key =>
obj[key][prop])
export const simplify = (obj, prop) =>
Object.keys(obj)
.reduce((acc, key) =>
set(acc, key, obj[key][prop]), {})
// ===================
// = ARRAY HELPERS =
// ===================
export const extractArr = (arr, prop) =>
arr.map(val => val[prop])
export const span = (length, start = 0) =>
[...Array(length).keys()]
.map(num =>
num + start)
export const range = function(start, end = start) {
if (arguments[1] === undefined) a = 0
return span(end - start, start)
})
// ======================
// = OMNIVORE HELPERS =
// ======================
export const extract = (thing, prop) => {
if (Array.isArray(thing))
return extractArr(thing, prop)
return extractObj(thing, prop)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment