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

Poteat/additional utilities #93

Merged
merged 22 commits into from
Oct 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
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
9 changes: 9 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
# Changelog

## [0.24.7]

- Add `NaturalNumber.Digits` to get the digits of a natural number.
- Add `List.Of` to create a list containing a single value.
- Add `List.SlidingWindow` to slide a window of a certain length over a list.
- Reify various natural number utilities.
- Reify various string and list utilities.
- Fix statefulness bug in reified `List.chunk`.

## [0.24.6]
- Add `String.FromCharCode` to convert a character code to a string.
- Add `String.IsLetter` to check if a string is a letter.
Expand Down
63 changes: 63 additions & 0 deletions src/_internal/hash.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
export function hash(value: unknown): string {
const seen = new WeakMap<object, number>()
let objectCount = 0

function innerHash(val: unknown): string {
if (val === null) return 'null'
if (val === undefined) return 'undefined'

if (
typeof val === 'boolean' ||
typeof val === 'number' ||
typeof val === 'bigint' ||
typeof val === 'symbol'
) {
return `${typeof val}:${String(val)}`
}

if (typeof val === 'string') {
return `string:${val}`
}

if (typeof val === 'function') {
return `function:${val.toString()}`
}

if (typeof val === 'object') {
if (seen.has(val)) {
return `circular#${seen.get(val)}`
}

seen.set(val, objectCount++)

if (Array.isArray(val)) {
const items = val.map((item) => innerHash(item))
return `array:[${items.join(',')}]`
} else if (val instanceof Set) {
const items = Array.from(val.values())
.map((item) => innerHash(item))
.sort()
return `set:{${items.join(',')}}`
} else if (val instanceof Map) {
const entries = Array.from(val.entries())
.map(([key, value]) => `${innerHash(key)}=>${innerHash(value)}`)
.sort()
return `map:{${entries.join(',')}}`
} else if (val instanceof Date) {
return `date:${val.toISOString()}`
} else if (val instanceof RegExp) {
return `regexp:${val.toString()}`
} else {
const keys = Object.keys(val).sort()
const entries = keys.map(
(key) => `${key}:${innerHash(val[key as keyof typeof val])}`
)
return `object:{${entries.join(',')}}`
}
}

return 'unknown'
}

return innerHash(value)
}
8 changes: 8 additions & 0 deletions src/boolean/not.spec.ts → src/boolean/not.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,11 @@ type Not_Spec = [
// @ts-expect-error
Test.Expect<$<Boolean.Not, number>>
]

it('should return the opposite boolean', () => {
expect(Boolean.not(true)).toBe(false)
})

it('should return the opposite boolean', () => {
expect(Boolean.not(false)).toBe(true)
})
15 changes: 15 additions & 0 deletions src/boolean/not.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,18 @@
export interface Not extends Kind.Kind {
f(x: Type._$cast<this[Kind._], boolean>): _$not<typeof x>
}

/**

Check warning on line 42 in src/boolean/not.ts

View workflow job for this annotation

GitHub Actions / build

Missing JSDoc @returns declaration
* Given a boolean, return the opposite boolean.
*
* @param {boolean} b - The boolean to negate.

Check warning on line 45 in src/boolean/not.ts

View workflow job for this annotation

GitHub Actions / build

Types are not permitted on @param
*
* @example
* ```ts
* import { Boolean } from "hkt-toolbelt";
*
* const result = Boolean.not(true)
* // ^? false
* ```
*/
export const not = ((b: boolean) => !b) as Kind._$reify<Not>
20 changes: 11 additions & 9 deletions src/combinator/collate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,15 @@ export interface Collate extends Kind.Kind {
* ```
*/
export const collate = ((n: number) => {
const values: unknown[] = []

const taker = (value: unknown) => {
values.push(value)

return values.length === n ? values : taker
}

return taker
const collector =
(values: unknown[] = []) =>
(value: unknown) => {
const newValues = [...values, value]
if (newValues.length === n) {
return newValues
} else {
return collector(newValues)
}
}
return collector()
}) as Kind._$reify<Collate>
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,21 @@ type NotEquals_Spec = [
Test.Expect<$<$<Conditional.NotEquals, []>, [[]]>>,
Test.Expect<$<$<Conditional.NotEquals, {}>, []>>
]

it('should return true if two values are not equal', () => {
expect(Conditional.notEquals(true)(false)).toBe(true)
})

it('should return false if two values are equal', () => {
expect(Conditional.notEquals(true)(true)).toBe(false)
})

it('can handle deep equality', () => {
expect(Conditional.notEquals([1, [2, [3, [4]]]])([1, [2, [3, [5]]]])).toBe(
true
)
})

it('can handle deep equality', () => {
expect(Conditional.notEquals({ a: 1 })({ a: 1 })).toBe(false)
})
18 changes: 18 additions & 0 deletions src/conditional/not-equals.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Kind } from '..'
import { deepEqual } from '../_internal/deepEqual'

/**
* `_$notEquals` is a type-level function that returns `true` if `T` and `U` are
Expand Down Expand Up @@ -40,3 +41,20 @@ interface NotEquals_T<T> extends Kind.Kind {
export interface NotEquals extends Kind.Kind {
f(x: this[Kind._]): NotEquals_T<typeof x>
}

/**
* Given two values, return whether they are not equal.
*
* @param {unknown} a - The first value.
* @param {unknown} b - The second value.
*
* @example
* ```ts
* import { Conditional } from "hkt-toolbelt";
*
* const result = Conditional.notEquals('foo')('bar')
* // ^? true
* ```
*/
export const notEquals = ((a: unknown) => (b: unknown) =>
!deepEqual(a, b)) as Kind._$reify<NotEquals>
12 changes: 12 additions & 0 deletions src/list/chunk.spec.ts → src/list/chunk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,15 @@ type Chunk_Spec = [
*/
Test.Expect<$<$<List.Chunk, 0>, [1, 2, 3, 4, 5]>, [[1, 2, 3, 4, 5]]>
]

it('should chunk a list into sublists of a specified size', () => {
expect(List.chunk(2)([1, 2, 3, 4, 5])).toEqual([[1, 2], [3, 4], [5]])
})

it('chunking an empty list results in an empty list', () => {
expect(List.chunk(2)([])).toEqual([])
})

it('chunking by 0 results in the original list', () => {
expect(List.chunk(0)([1, 2, 3, 4, 5])).toEqual([[1, 2, 3, 4, 5]])
})
26 changes: 26 additions & 0 deletions src/list/chunk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,29 @@ interface Chunk_T<N extends number> extends Kind.Kind {
export interface Chunk extends Kind.Kind {
f(x: Type._$cast<this[Kind._], number>): Chunk_T<typeof x>
}

/**
* Given a number N, return a list of lists, where each list contains N elements.
*
* @param {number} n - The number of elements to include in each sublist.
* @param {unknown[]} x - The list to chunk.
*
* @example
* ```ts
* import { List } from "hkt-toolbelt";
*
* const result = List.chunk(2)([1, 2, 3, 4, 5])
* // ^? [[1, 2], [3, 4], [5]]
* ```
*/
export const chunk = ((n: number) => (x: unknown[]) => {
const result: unknown[][] = []

if (n === 0) return [x]

for (let i = 0; i < x.length; i += n) {
result.push(x.slice(i, i + n))
}

return result
}) as Kind._$reify<Chunk>
7 changes: 2 additions & 5 deletions src/list/filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ export type _$filter<
: _$filter<F, Tail, O>
: O

interface Filter_T<F extends Kind.Kind<(x: never) => boolean>>
extends Kind.Kind {
interface Filter_T<F extends Kind.Kind> extends Kind.Kind {
f(x: Type._$cast<this[Kind._], Kind._$inputOf<F>[]>): _$filter<F, typeof x>
}

Expand Down Expand Up @@ -78,9 +77,7 @@ interface Filter_T<F extends Kind.Kind<(x: never) => boolean>>
* ], [42.42, null, "hello", undefined, "world"]> // "hello, world"
*/
export interface Filter extends Kind.Kind {
f(
x: Type._$cast<this[Kind._], Kind.Kind<(x: never) => boolean>>
): Filter_T<typeof x>
f(x: Type._$cast<this[Kind._], Kind.Kind>): Filter_T<typeof x>
}

/**
Expand Down
2 changes: 2 additions & 0 deletions src/list/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export * from './map'
export * from './map-n'
export * from './max-by'
export * from './min-by'
export * from './of'
export * from './pair'
export * from './pop'
export * from './pop-n'
Expand All @@ -39,6 +40,7 @@ export * from './reverse'
export * from './shift'
export * from './shift-n'
export * from './slice'
export * from './sliding-window'
export * from './some'
export * from './splice'
export * from './take'
Expand Down
11 changes: 10 additions & 1 deletion src/list/max-by.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,18 @@ type MaxBy_Spec = [
/**
* Can find the maximum element of a list of strings, based on length.
*/
Test.Expect<$<$<List.MaxBy, String.Length>, ['foo', 'bars', 'qux']>, 'bars'>
Test.Expect<$<$<List.MaxBy, String.Length>, ['foo', 'bars', 'qux']>, 'bars'>,

/**
* Returns the first maximal element in the list.
*/
Test.Expect<$<$<List.MaxBy, String.Length>, ['foob', 'bar', 'quxo']>, 'foob'>
]

it('should return the element in the list that has the highest score', () => {
expect(List.maxBy(Function.identity)([1, 2, 3])).toBe(3)
})

it('should return the first maximal element in the list', () => {
expect(List.maxBy(String.length)(['foob', 'bar', 'quxo'])).toBe('foob')
})
22 changes: 22 additions & 0 deletions src/list/of.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { $, List, Test } from '..'

type Of_Spec = [
/**
* Can create a list containing a single value.
*/
Test.Expect<$<List.Of, 42>, [42]>,

/**
* Can create a list containing a single value.
*/
Test.Expect<$<List.Of, 42>, [42]>,

/**
* Can create a 1-tuple containg a list.
*/
Test.Expect<$<List.Of, [1, 2, 3]>, [[1, 2, 3]]>
]

it('should create a list containing a single value', () => {
expect(List.of(42)).toEqual([42])
})
48 changes: 48 additions & 0 deletions src/list/of.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { Kind } from '..'

/**
* `_$of` is a type-level function that takes in a value `X` and returns a list
* containing only that value.
*
* @template {unknown} X - The value to include in the list.
*
* @example
* ```ts
* import { List } from "hkt-toolbelt";
*
* type Result = List._$of<42>; // [42]
* ```
*/
export type _$of<X> = [X]

/**
* `Of` is a type-level function that takes in a value `X` and returns a list
* containing only that value.
*
* @template {unknown} X - The value to include in the list.
*
* @example
* ```ts
* import { $, List } from "hkt-toolbelt";
*
* type Result = $<List.Of, 42>; // [42]
* ```
*/
export interface Of extends Kind.Kind {
f(x: this[Kind._]): _$of<typeof x>
}

/**
* Given a value, return a list containing only that value.
*
* @param {unknown} x - The value to include in the list.
*
* @example
* ```ts
* import { List } from "hkt-toolbelt";
*
* const result = List.of(42)
* // ^? [42]
* ```
*/
export const of = ((x: unknown) => [x]) as Kind._$reify<Of>
27 changes: 27 additions & 0 deletions src/list/pop.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { $, List, Test } from '..'

type Pop_Spec = [
/**
* Can pop the last element of a list.
*/
Test.Expect<$<List.Pop, ['a', 'b', 'c']>, ['a', 'b']>,

/**
* Popping an empty list results in never.
*/
Test.Expect<$<List.Pop, []>, never>,

/**
* Popping a list with a single element results in an empty list.
*/
Test.Expect<$<List.Pop, ['a']>, []>,

/**
* Popping a list with a single element results in an empty list.
*/
Test.Expect<$<List.Pop, [1, 2, 3]>, [1, 2]>
]

it('should remove the last element from the list', () => {
expect(List.pop(['a', 'b', 'c'])).toEqual(['a', 'b'])
})
Loading
Loading