|
| 1 | +function getChildElementsByTagName(element, tag) { |
| 2 | + return Array.from(element.children).filter((element) => element.tagName === tag); |
| 3 | +} |
| 4 | +/** maximum value for `lnInst` attribute */ |
| 5 | +const maxLnInst = 99; |
| 6 | +const lnInstRange = Array(maxLnInst) |
| 7 | + .fill(1) |
| 8 | + .map((_, i) => `${i + 1}`); |
| 9 | +/** |
| 10 | + * Generator function returning unique `inst` or `lnInst` attribute for element |
| 11 | + * [[`tagName`]] within [[`parent`]]. |
| 12 | + * ```md |
| 13 | + * Valid range for both `inst` and `lnInst` is between 1 and 99 |
| 14 | + * ``` |
| 15 | + * @param parent - The parent element to be scanned for `inst` or `lnInst` |
| 16 | + * values already in use. Be sure to create a new generator every time the |
| 17 | + * children of this element change in SCL. |
| 18 | + * @param tagName - Tag name of the child elements containing the |
| 19 | + * `lnInst` or `inst` attribute |
| 20 | + * @returns a function generating increasing unused `inst` or `lnInst` values |
| 21 | + * element with [[`tagName`]] within [[`parent`]] on subsequent invocations |
| 22 | + */ |
| 23 | +function lnInstGenerator(parent, tagName) { |
| 24 | + const generators = new Map(); |
| 25 | + const generatedAttribute = tagName === "LN" ? "inst" : "lnInst"; |
| 26 | + return (lnClass) => { |
| 27 | + if (!generators.has(lnClass)) { |
| 28 | + const lnInstOrInst = new Set(getChildElementsByTagName(parent, tagName) |
| 29 | + .filter((element) => element.getAttribute("lnClass") === lnClass) |
| 30 | + .map((element) => element.getAttribute(generatedAttribute))); |
| 31 | + generators.set(lnClass, () => { |
| 32 | + const uniqueLnInstOrInst = lnInstRange.find((lnInst) => !lnInstOrInst.has(lnInst)); |
| 33 | + if (uniqueLnInstOrInst) |
| 34 | + lnInstOrInst.add(uniqueLnInstOrInst); |
| 35 | + return uniqueLnInstOrInst; |
| 36 | + }); |
| 37 | + } |
| 38 | + return generators.get(lnClass)(); |
| 39 | + }; |
| 40 | +} |
| 41 | + |
| 42 | +export { lnInstGenerator }; |
0 commit comments