UNPKG

911 BJavaScriptView Raw
1/**
2 * Validates a cost for a node
3 *
4 * @private
5 * @param {number} val - Cost to validate
6 * @return {bool}
7 */
8function isValidNode(val) {
9 const cost = Number(val);
10
11 if (isNaN(cost) || cost <= 0) {
12 return false;
13 }
14
15 return true;
16}
17
18/**
19 * Creates a deep `Map` from the passed object.
20 *
21 * @param {Object} source - Object to populate the map with
22 * @return {Map} New map with the passed object data
23 */
24function toDeepMap(source) {
25 const map = new Map();
26 const keys = Object.keys(source);
27
28 keys.forEach((key) => {
29 const val = source[key];
30
31 if (val !== null && typeof val === 'object' && !Array.isArray(val)) {
32 return map.set(key, toDeepMap(val));
33 }
34
35 if (!isValidNode(val)) {
36 throw new Error(`Could not add node at key "${key}", make sure it's a valid node`, val);
37 }
38
39 return map.set(key, Number(val));
40 });
41
42 return map;
43}
44
45module.exports = toDeepMap;