chore: refactor delete undefined logic

This commit is contained in:
fryorcraken.eth 2023-03-14 11:06:27 +11:00
parent 5a8de54d50
commit b3228a2dfe
No known key found for this signature in database
GPG Key ID: A82ED75A8DFC50A4
1 changed files with 21 additions and 17 deletions

View File

@ -126,12 +126,7 @@ export class RawEnr extends Map<ENRKey, ENRValue> {
* ie, without a peer id. * ie, without a peer id.
*/ */
set multiaddrs(multiaddrs: Multiaddr[] | undefined) { set multiaddrs(multiaddrs: Multiaddr[] | undefined) {
if (multiaddrs === undefined) { deleteUndefined(this, "multiaddrs", multiaddrs, encodeMultiaddrs);
this.delete("multiaddrs");
} else {
const multiaddrsBuf = encodeMultiaddrs(multiaddrs);
this.set("multiaddrs", multiaddrsBuf);
}
} }
/** /**
@ -148,12 +143,12 @@ export class RawEnr extends Map<ENRKey, ENRValue> {
* Set the `waku2` field on the ENR. * Set the `waku2` field on the ENR.
*/ */
set waku2(waku2: Waku2 | undefined) { set waku2(waku2: Waku2 | undefined) {
if (waku2 === undefined) { deleteUndefined(
this.delete("waku2"); this,
} else { "waku2",
const byte = encodeWaku2(waku2); waku2,
this.set("waku2", new Uint8Array([byte])); (w) => new Uint8Array([encodeWaku2(w)])
} );
} }
} }
@ -183,11 +178,7 @@ function setStringValue(
proto: string, proto: string,
value: string | undefined value: string | undefined
): void { ): void {
if (value !== undefined) { deleteUndefined(map, key, value, convertToBytes.bind({}, proto));
map.set(key, convertToBytes(proto, value));
} else {
map.delete(key);
}
} }
function setNumberAsStringValue( function setNumberAsStringValue(
@ -198,3 +189,16 @@ function setNumberAsStringValue(
): void { ): void {
setStringValue(map, key, proto, value?.toString(10)); setStringValue(map, key, proto, value?.toString(10));
} }
function deleteUndefined<K, V, W>(
map: Map<K, W>,
key: K,
value: V | undefined,
transform: (v: V) => W
): void {
if (value !== undefined) {
map.set(key, transform(value));
} else {
map.delete(key);
}
}