|
Last change
on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago |
|
Fix frontend appearance
|
-
Property mode
set to
100644
|
|
File size:
1.1 KB
|
| Line | |
|---|
| 1 | /*
|
|---|
| 2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
|---|
| 3 | Author Tobias Koppers @sokra
|
|---|
| 4 | */
|
|---|
| 5 |
|
|---|
| 6 | "use strict";
|
|---|
| 7 |
|
|---|
| 8 | /**
|
|---|
| 9 | * getOrInsert is a helper function for maps that allows you to get a value
|
|---|
| 10 | * from a map if it exists, or insert a new value if it doesn't. If it value doesn't
|
|---|
| 11 | * exist, it will be computed by the provided function.
|
|---|
| 12 | * @template K
|
|---|
| 13 | * @template V
|
|---|
| 14 | * @param {Map<K, V>} map The map object to check
|
|---|
| 15 | * @param {K} key The key to check
|
|---|
| 16 | * @param {() => V} computer function which will compute the value if it doesn't exist
|
|---|
| 17 | * @returns {V} The value from the map, or the computed value
|
|---|
| 18 | * @example
|
|---|
| 19 | * ```js
|
|---|
| 20 | * const map = new Map();
|
|---|
| 21 | * const value = getOrInsert(map, "key", () => "value");
|
|---|
| 22 | * console.log(value); // "value"
|
|---|
| 23 | * ```
|
|---|
| 24 | */
|
|---|
| 25 | module.exports.getOrInsert = (map, key, computer) => {
|
|---|
| 26 | // Grab key from map
|
|---|
| 27 | const value = map.get(key);
|
|---|
| 28 | // If the value already exists, return it
|
|---|
| 29 | if (value !== undefined) return value;
|
|---|
| 30 | // Otherwise compute the value, set it in the map, and return it
|
|---|
| 31 | const newValue = computer();
|
|---|
| 32 | map.set(key, newValue);
|
|---|
| 33 | return newValue;
|
|---|
| 34 | };
|
|---|
Note:
See
TracBrowser
for help on using the repository browser.