Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: universal helpers for all iterable data structures #38

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions spec/iterable.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { map, flatMap } from '../src'

describe('flatMap', () => {
it('maps array', () => {
expect<number[]>(map([1, 2, 3, 4], (x) => x * 2)).toEqual([2, 4, 6, 8])
})

it('maps read-only array', () => {
expect<ReadonlyArray<number>>(map([1, 2, 3, 4] as const, (x) => x * 2)).toEqual([2, 4, 6, 8])
})

it('maps object', () => {
expect<Record<string, string>>(map({a: 'b'}, ([k, v]) => [v, k])).toEqual({b: 'a'})
})

it('maps set', () => {
expect<Set<number>>(map(new Set([1, 2, 3, 4]), (x) => x * 2)).toEqual(new Set([2, 4, 6, 8]))
})

it('maps map', () => {
expect<Map<string, string>>(map(new Map([['a', 'b']]), ([k, v]) => [v, k])).toEqual(new Map([['b', 'a']]))
})
})

describe('flatMap', () => {
it('flattens array', () => {
expect<number[]>(flatMap([1, 2, 3, 4], (x) => [x * 2])).toEqual([2, 4, 6, 8])
})

it('flattens readonly-array', () => {
expect<ReadonlyArray<number>>(flatMap([1, 2, 3, 4] as const, (x) => [x * 2])).toEqual([2, 4, 6, 8])
})

it('only one level is flattened', () => {
expect(flatMap([1, 2, 3, 4], (x) => [[x * 2]])).toEqual([
[2],
[4],
[6],
[8],
])
})

it('create multiple items from object', () => {
expect<Record<string, string>>(
flatMap({ a: 'b' }, ([k, v]) => [
[k, v],
[`${k}2`, v],
])
).toEqual({ a: 'b', a2: 'b' })
})

it('filters object items', () => {
expect<Record<string, string>>(
flatMap({ a: 'b', b: 'c' }, ([k, v]) =>
k === 'a' ? [[k, v]] : []
)
).toEqual({ a: 'b' })
})

it('flattens Set', () => {
expect<Set<number>>(flatMap(new Set([1, 2, 3, 4]), (x) => [x * 2])).toEqual(new Set([2, 4, 6, 8]))
})

it('flattens Map', () => {
expect<Map<string, string>>(
flatMap(new Map([['a', 'b']]), ([k, v]) => [
[k, v],
[`${k}2`, v],
])
).toEqual(new Map([['a', 'b'], ['a2', 'b']]))
})
})
50 changes: 0 additions & 50 deletions src/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,56 +160,6 @@ export function generateRange(
return result
}

/**
* Calls a defined callback function on each element of an array. Then, flattens the result into
* a new array.
* This is identical to a map followed by flat with depth 1.
*
* Use [Array.flatMap](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap) if possible or polyfill globally:
*
* ```
* Array.prototype.flatMap = function(callback) {
* return flatMap(this, callback)
* }
* ```
*
* @example
* ```
* const arr1 = [1, 2, 3, 4]
*
* arr1.map(x => [x * 2])
* // [[2], [4], [6], [8]]
*
* flatMap(arr1, x => [x * 2])
* // [2, 4, 6, 8]
*
* // only one level is flattened
* flatMap(arr1, x => [[x * 2]])
* // [[2], [4], [6], [8]]
* ```
* @category Array
* @tutorial https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap
* @param array any array
* @param callback A function that accepts up to three arguments. The flatMap method calls the callback function one time for each element in the array.
*/
export function flatMap<T, U>(
array: T[],
callback: (item: T, index: number, array: T[]) => U | readonly U[]
): U[]
export function flatMap<T, U>(
array: readonly T[],
callback: (item: T, index: number, array: readonly T[]) => U | readonly U[]
): readonly U[]
export function flatMap<T, U>(
array: readonly T[],
callback: (item: T, index: number, array: T[]) => U | readonly U[]
): readonly U[] {
return array.reduce(
(acc, v, index) => acc.concat(callback(v, index, array as T[])),
[] as U[]
)
}

type FlatArray<Arr, Depth extends number> = {
done: Arr
recur: Arr extends ReadonlyArray<infer InnerArr>
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ export * from './cache'
export * from './async'
export * from './types'
export * from './random'
export * from './iterable'
179 changes: 179 additions & 0 deletions src/iterable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
import { isPlainObject, isArray } from '.'

/**
* Builds a new iterable data structure by applying a function to all elements.
*
* Supported structures:
* * Array
* * Simple object
* * Set
* * Map
*
* @example
* ```
* map([1, 2], v => v + 1)
* // [2, 3]
*
* map({'a': 2}, ([k, v]) => [v, k])
* // {'2': 'a, '3': 'b}
*
* map(new Map([['a', 2]]), ([k, v]) => [v, k])
* // Map({2: 'a'})
*
* map(new Set([1, 2]), v => v + 1)
* // Set([2, 3])
* ```
* @category Iterable
*/
export function map<T, R>(
obj: T[],
callback: (entry: T) => R
): R[]
export function map<T, R>(
obj: ReadonlyArray<T>,
callback: (entry: T) => R
): ReadonlyArray<R>
export function map<T, R>(
obj: Set<T>,
callback: (entry: T) => R
): Set<R>
export function map<K extends keyof any, V, RK extends keyof any, RV>(
obj: Map<K, V>,
callback: (entry: [K, V]) => [RK, RV]
): Map<RK, RV>
export function map<K extends keyof any, V, RK extends keyof any, RV>(
obj: Record<K, V>,
callback: (entry: [K, V]) => [RK, RV]
): Record<RK, RV>
export function map(
value: unknown,
callback: (entry: any) => unknown
): unknown {
return flatMap(value as any, v => [callback(v)])
}

/**
* Calls a defined callback function on each element of an array. Then, flattens the result into
* a new array.
*
* Supported structures:
* * Array
* * Simple object
* * Set
* * Map
*
* @example
* ```
* flatMap([1, 2], v => [v + 1])
* // [2, 3]
*
* flatMap({'a': 2}, ([k, v]) => [[v, k]])
* // {'2': 'a, '3': 'b}
*
* flatMap(new Map([['a', 2]]), ([k, v]) => [[v, k]])
* // Map({2: 'a'})
*
* flatMap(new Set([1, 2]), v => [v + 1])
* // Set([2, 3])
* ```
* @category Iterable
*/
export function flatMap<T, R>(
obj: T[],
callback: (entry: T) => ReadonlyArray<R>
): R[]
export function flatMap<T, R>(
obj: ReadonlyArray<T>,
callback: (entry: T) => ReadonlyArray<R>
): ReadonlyArray<R>
export function flatMap<T, R>(
obj: Set<T>,
callback: (entry: T) => ReadonlyArray<R>
): Set<R>
export function flatMap<K extends keyof any, V, RK extends keyof any, RV>(
obj: Map<K, V>,
callback: (entry: [K, V]) => ReadonlyArray<[RK, RV]>
): Map<RK, RV>
export function flatMap<K extends keyof any, V, RK extends keyof any, RV>(
obj: Record<K, V>,
callback: (entry: [K, V]) => ReadonlyArray<[RK, RV]>
): Record<RK, RV>
export function flatMap(
value: unknown,
callback: (entry: any) => ReadonlyArray<unknown>
): unknown {
if (isArray(value)) {
return value.reduce<unknown[]>(
(acc, cur) => {
acc.push(...callback(cur))
return acc
},
[]
)
}

if (typeof Set !== 'undefined' && value instanceof Set) {
const newSet = new Set()
value.forEach(cur => {
callback(cur).forEach(v => {
newSet.add(v)
})
})
return newSet
}

if (typeof Map !== 'undefined' && value instanceof Map) {
const newMap = new Map()
value.forEach((v, k) => {
const values = callback([k, v]) as [keyof any, unknown][]
values.forEach(([newK, newV]) => {
newMap.set(newK, newV)
})
})
return newMap
}

if (isPlainObject(value)) {
return Object.entries(value).reduce((acc, [key, value]) => {
const entries = callback([key, value]) as [string | number, unknown][]
entries.forEach(([newK, newV]) => {
acc[newK] = newV
})
return acc
}, {} as Record<keyof any, unknown>) as any
}

return value
}

/**
*
* @param obj
* @param callback
*/
export function filter<T>(
obj: T[],
callback: (entry: T) => boolean
): T[]
export function filter<T>(
obj: boolean,
callback: (entry: T) => boolean
): ReadonlyArray<T>
export function filter<T>(
obj: Set<T>,
callback: (entry: T) => boolean
): Set<T>
export function filter<K extends keyof any, V>(
obj: Map<K, V>,
callback: (entry: [K, V]) => boolean
): Map<K, V>
export function filter<K extends keyof any, V>(
obj: Record<K, V>,
callback: (entry: [K, V]) => boolean
): Record<K, V>
export function filter(
value: unknown,
callback: (entry: any) => boolean
): unknown {
return flatMap(value as any, (v) => (callback(v) ? [v] : []))
}
15 changes: 5 additions & 10 deletions src/object.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isPlainObject } from '.'
import { isPlainObject, map, flatMap } from '.'

/**
* Compares two values.
Expand Down Expand Up @@ -53,19 +53,13 @@ export function isEqual(a: unknown, b: unknown): boolean {
* @param obj `Record` like object
* @param callback map callback, accepts entry pair (`[key, value]`) and should return list of entry pairs
* @returns new mapped object
* @deprecated use [[flatMap]]
*/
export function flatMapRecord<K extends keyof any, V, RK extends keyof any, RV>(
obj: Record<K, V>,
callback: (entry: [K, V]) => Array<[RK, RV]>
): Record<RK, RV> {
const entries = Object.entries(obj) as Array<[K, V]>

return entries.map(callback).reduce((prev, values) => {
values.forEach(([key, value]) => {
prev[key] = value
})
return prev
}, {} as Record<RK, RV>)
return flatMap(obj, callback)
}

/**
Expand All @@ -82,12 +76,13 @@ export function flatMapRecord<K extends keyof any, V, RK extends keyof any, RV>(
* @param obj `Record` like plain object
* @param callback map callback, accepts entry pair (`[key, value]`) and should return entry pair
* @returns new mapped object
* @deprecated use [[map]]
*/
export function mapRecord<K extends keyof any, V, RK extends keyof any, RV>(
obj: Record<K, V>,
callback: (entry: [K, V]) => [RK, RV]
): Record<RK, RV> {
return flatMapRecord(obj, (v) => [callback(v)])
return map(obj, callback)
}

/**
Expand Down