Skip to content

Commit

Permalink
feat(effect): get or set
Browse files Browse the repository at this point in the history
  • Loading branch information
Hfutsora committed Nov 1, 2022
1 parent aeb1534 commit 3858be2
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
19 changes: 19 additions & 0 deletions src/Effect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,22 @@ export const also = <A>(a: A, f: (a: A) => void): A => (f(a), a)
*/
export const match = <A, B>(onTrue: () => A, onFalse: () => B) => (condition: boolean): A | B => condition ? onTrue() : onFalse()

/**
* Gets a value from source by the given key.
*
* Sets a value with the initial function if source doesn't [has](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn) the key.
*
* @example
*
* ```ts
* const source: Record<string, number> = { a: 0 }
* assert.deepStrictEqual(getOrSet(source, 'a', () => 1), 0)
* assert.deepStrictEqual(getOrSet(source, 'b', () => 1), 1)
* assert.deepStrictEqual(source['b']), 1)
* ```
*/
export const getOrSet = <T extends Record<string, unknown>, K extends keyof T>(
source: T,
key: K,
initialValue: () => T[K]
): T[K] => Object.hasOwn(source, key) ? source[key] : (source[key] = initialValue())
12 changes: 11 additions & 1 deletion test/Effect.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { pipe } from '../src/Pipe'
import { also, map, match, use } from '../src/Effect'
import { also, map, match, use, getOrSet } from '../src/Effect'


test('map', () => {
Expand Down Expand Up @@ -28,3 +28,13 @@ test('match', () => {
expect(m(true)).toBe(1)
expect(m(false)).toBe(0)
})

test('ge or set', () => {
const source: Record<string, number> = {
a: 0
}

expect(getOrSet(source, 'a', () => 1)).toBe(0)
expect(getOrSet(source, 'b', () => 1)).toBe(1)
expect(source['b']).toBe(1)
})

0 comments on commit 3858be2

Please sign in to comment.