Skip to content
This repository has been archived by the owner on Jan 8, 2022. It is now read-only.

Commit

Permalink
feat: add Collection#ensure (#52)
Browse files Browse the repository at this point in the history
Co-authored-by: Antonio Román <kyradiscord@gmail.com>
Co-authored-by: muchnameless <12682826+muchnameless@users.noreply.github.com>
Co-authored-by: Rodry <38259440+ImRodry@users.noreply.github.com>
Co-authored-by: Kyran Mendoza <mendozakyran8@gmail.com>
Co-authored-by: kxmndz <71072915+kxmndz@users.noreply.github.com>
  • Loading branch information
6 people committed Dec 24, 2021
1 parent 3f19298 commit 3809eb4
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
25 changes: 25 additions & 0 deletions __tests__/collection.test.ts
Expand Up @@ -435,3 +435,28 @@ describe('random thisArg tests', () => {
}, array);
});
});

describe('ensure() tests', () => {
function createTestCollection() {
return new Collection([
['a', 1],
['b', 2],
]);
}

test('set new value if key does not exist', () => {
const coll = createTestCollection();
coll.ensure('c', () => 3);
expect(coll.size).toStrictEqual(3);
expect(coll.get('c')).toStrictEqual(3);
});

test('return existing value if key exists', () => {
const coll = createTestCollection();
const ensureB = coll.ensure('b', () => 3);
const getB = coll.get('b');
expect(ensureB).toStrictEqual(2);
expect(getB).toStrictEqual(2);
expect(coll.size).toStrictEqual(2);
});
});
16 changes: 16 additions & 0 deletions src/index.ts
Expand Up @@ -25,6 +25,22 @@ export interface Collection<K, V> extends Map<K, V> {
export class Collection<K, V> extends Map<K, V> {
public static readonly default: typeof Collection = Collection;

/**
* Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator.
*
* @param key The key to get if it exists, or set otherwise
* @param defaultValueGenerator A function that generates the default value
*
* @example
* collection.ensure(guildId, () => defaultGuildConfig);
*/
public ensure(key: K, defaultValueGenerator: (key: K, collection: this) => V): V {
if (this.has(key)) return this.get(key)!;
const defaultValue = defaultValueGenerator(key, this);
this.set(key, defaultValue);
return defaultValue;
}

/**
* Checks if all of the elements exist in the collection.
*
Expand Down

0 comments on commit 3809eb4

Please sign in to comment.