import { getObjectType } from '../type'
export type Mapper = (a: A) => B
export type ArrayMapper = (a: A, i: number, xs: A[]) => B
export type ObjectMapper = (
value: A[keyof A],
key: keyof A,
object: A,
) => B
export type SetMapper = (a: A, xs: Set) => B
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export type MapValueMapper = (
v: AV,
k: AK,
xs: Map,
) => BV
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export type MapKeyMapper = (v: AV, k: AK, xs: Map) => BK
export type NodeListElementMapper = (
a: A,
i: number,
xs: NodeListOf | HTMLCollectionOf,
) => B
export namespace maps {
export function array(xs: A[], f: ArrayMapper): B[] {
return xs.map(f)
}
export function object(x: A, f: ObjectMapper): B {
const y = new (x as any).constructor()
// eslint-disable-next-line guard-for-in
for (const k in x) {
y[k] = f(x[k], k, x)
}
return y
}
export function set(xs: Set, f: SetMapper) {
const ys = new Set()
xs.forEach(x => ys.add(f(x, xs)))
return ys
}
export function map(
xs: Map,
valueMapper: MapValueMapper,
keyMapper?: MapKeyMapper,
): Map {
const ys = new Map()
xs.forEach((av, ak) => {
const bv = valueMapper(av, ak, xs)
const bk = keyMapper ? keyMapper(av, ak, xs) : (ak as any as BK)
ys.set(bk, bv)
})
return ys
}
export function nodeList(
xs: NodeListOf | HTMLCollectionOf,
f: NodeListElementMapper,
) {
const ys = new Array(xs.length)
for (let i = 0; i < xs.length; i++) {
ys[i] = f(xs.item(i) as A, i, xs)
}
return ys
}
export function any(o: any, f: (a: any) => any): any {
if (Array.isArray(o)) {
return array(o, f)
}
// skip this data type if in node.js
if (
(typeof NodeList !== 'undefined' && o instanceof NodeList) ||
(typeof HTMLCollection !== 'undefined' && o instanceof HTMLCollection)
) {
return nodeList(o as any, f)
}
switch (getObjectType(o)) {
case 'Array':
return array(o, f)
case 'Set':
return set(o, f)
case 'Map':
return map(o, f)
case 'Object':
return object(o, f)
default:
return f(o)
}
}
}
export const map_array = maps.array
export const map_object = maps.object
export const map_set = maps.set
export const map_map = maps.map
export const map_nodeList = maps.nodeList
export const map_any = maps.any