Skip to content

Commit

Permalink
map.setIfUndefined supports inheritance. fixes #82
Browse files Browse the repository at this point in the history
  • Loading branch information
dmonad committed Nov 22, 2023
1 parent e77a341 commit 00fbf0b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 8 deletions.
16 changes: 8 additions & 8 deletions map.js
Expand Up @@ -18,9 +18,9 @@ export const create = () => new Map()
* Copy a Map object into a fresh Map object.
*
* @function
* @template X,Y
* @param {Map<X,Y>} m
* @return {Map<X,Y>}
* @template K,V
* @param {Map<K,V>} m
* @return {Map<K,V>}
*/
export const copy = m => {
const r = create()
Expand All @@ -37,12 +37,12 @@ export const copy = m => {
* ```
*
* @function
* @template V,K
* @template {Map<K,V>} MAP
* @template {Map<any, any>} MAP
* @template {MAP extends Map<any,infer V> ? function():V : unknown} CF
* @param {MAP} map
* @param {K} key
* @param {function():V} createT
* @return {V}
* @param {MAP extends Map<infer K,any> ? K : unknown} key
* @param {CF} createT
* @return {ReturnType<CF>}
*/
export const setIfUndefined = (map, key, createT) => {
let set = map.get(key)
Expand Down
27 changes: 27 additions & 0 deletions map.test.js
Expand Up @@ -26,3 +26,30 @@ export const testMap = _tc => {
t.assert(!map.all(m, (v, k) => k === 1 && v === 2))
t.assert(map.all(m, (v) => v === 2 || v === 3 || v === numberOfWrites))
}

/**
* @param {t.TestCase} _tc
*/
export const testTypeDefinitions = _tc => {
// setIfUndefined supports inheritance properly: See https://github.com/dmonad/lib0/issues/82
class A {
constructor () {
this.a = 4
}
}
class B extends A {
constructor () {
super()
this.b = 4
}
}
/**
* @type {Map<number, A>}
*/
const m = map.create()
/**
* @type {B}
*/
const b = map.setIfUndefined(m, 0, () => new B())
console.log(b)
}

0 comments on commit 00fbf0b

Please sign in to comment.