Last active
February 14, 2024 01:52
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==================== | |
// = 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