Skip to content

Commit

Permalink
🛠 Refactor: Replace RNIIdentifiable counterID
Browse files Browse the repository at this point in the history
Summary: Replace `RNIIdentifiable`'s `counterID` with `Counter.typeToCounterMap`.
  • Loading branch information
dominicstop committed Apr 6, 2023
1 parent 48b4582 commit 6307c00
Showing 1 changed file with 45 additions and 9 deletions.
54 changes: 45 additions & 9 deletions ios/src_library/Helpers+Utilities/RNIIdentifiable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,50 @@

import Foundation

public final class RNIObjectIdentifier {
static var counterID = -1;

fileprivate class Counter {
static var typeToCounterMap: Dictionary<String, Int> = [:];

static func getTypeString(ofType _type: Any) -> String {
return String(describing: type(of: _type));
};

let id: Int = {
RNIObjectIdentifier.counterID += 1;
return RNIObjectIdentifier.counterID;
}();
static func set(forType type: Any, counter: Int) {
let typeString = Self.getTypeString(ofType: type);
Self.typeToCounterMap[typeString] = counter;
};

static func set(forType typeString: String, counter: Int) {
Self.typeToCounterMap[typeString] = counter;
};

static func get(forType type: Any) -> Int {
let typeString = Self.getTypeString(ofType: type);

guard let counter = Self.typeToCounterMap[typeString] else {
Self.set(forType: typeString, counter: -1);
return -1;
};

return counter;
};

static func getAndIncrement(forType type: Any) -> Int {
let prevCount = Self.get(forType: type);
let nextCount = prevCount + 1;

Self.set(forType: type, counter: nextCount);
return nextCount;
};
};

public final class RNIObjectIdentifier {
let id: Int;
let uuid = UUID();

init(type: Any) {
self.id = Counter.getAndIncrement(forType: type);
};
};

public protocol RNIIdentifiable:
Expand All @@ -30,20 +65,21 @@ public protocol RNIIdentifiable:
};

extension RNIIdentifiable {
public static var synthesizedIdPrefix: String {
String(describing: Self.self) + "-";
};

public var synthesizedIdentifier: RNIObjectIdentifier {
if let identifier = self.metadata {
return identifier;
};

let identifier = RNIObjectIdentifier();
let identifier = RNIObjectIdentifier(type: Self.self);
self.metadata = identifier;

return identifier;
};

static var synthesizedIdPrefix: String { "" };

public var synthesizedID: Int {
self.synthesizedIdentifier.id;
};
Expand Down

0 comments on commit 6307c00

Please sign in to comment.