Skip to content

Instantly share code, notes, and snippets.

@55Cancri
Created May 24, 2023 20:12
Show Gist options
  • Save 55Cancri/3e66d09a729b66c063b75b501d9ab473 to your computer and use it in GitHub Desktop.
Save 55Cancri/3e66d09a729b66c063b75b501d9ab473 to your computer and use it in GitHub Desktop.
modules
import clone_deep from "lodash.clonedeep"
/**
* dicts are homogeneous- their values must be of the same type
* records can hold values of different types
*/
type t = Record<string, unknown> | object
export { clone_deep }
/**
* First object contains key/value pairs that pass the predicate.
* Secoond object contains key/value pairs that failed.
* x:xs
* r:rs
* d:ds
* @param xs
* @param predicate
* @returns
*/
export const partition = <R extends t>(
r: R,
predicate: (key: keyof R) => boolean
) => {
const passed = {} as R
const failed = {} as R
for (const key in r) {
if (predicate(key)) passed[key] = r[key]
else failed[key] = r[key]
}
return [passed, failed] as const
}
/**
* Determine if an object is empty.
* @param obj
* @returns
*/
export const is_empty = <T extends t>(obj: T) => {
return (
!obj ||
(Object.keys(obj).length === 0 && (obj as any).constructor === Object)
)
}
/**
* Merge two objects
* @param o1
* @param o2
* @returns
*/
export const merge = <O1, O2>(o1: O1, o2: O2) => ({ ...o1, ...o2 })
/**
* Shallow clone an object
* @param r
* @returns
*/
export const clone = <R extends t>(r: R) => ({ ...r })
/**
* Return an object with a subset of properties.
* @param r
* @param paths
*/
export const pick = <R extends t, U extends keyof R>(
r: R,
paths: Array<U>
): Pick<R, U> =>
Object.entries(r).reduce(
(store, [key, value]) =>
paths.includes(key as U) ? { ...store, [key]: value } : store,
{} as Pick<R, U>
)
/**
* Return an object with a subset of properties.
* @param r
* @param paths
*/
export const omit = <R extends Record<string, any>, U extends keyof R>(
r: R,
paths: Array<U>
): Omit<R, U> => {
if (!r) {
throw new Error("[omit] item was not an object")
}
return Object.entries(r).reduce((store, [key, value]) => {
if (paths.includes(key as U)) {
return store
} else {
store[key as keyof Omit<R, U>] = value as any
return store
}
}, {} as Omit<R, U>)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment