11import List "mo:base/List" ;
22import Option "mo:base/Option" ;
3- import Trie "mo:base/Trie " ;
3+ import Map "mo:base/OrderedMap " ;
44import Nat32 "mo:base/Nat32" ;
55
66actor Superheroes {
@@ -15,18 +15,19 @@ actor Superheroes {
1515 // The type of a superhero.
1616 public type Superhero = {
1717 name : Text ;
18- superpowers : List . List < Text > ;
18+ superpowers : List . List < Text >
1919 };
2020
2121 /**
2222 * Application State
2323 */
2424
2525 // The next available superhero identifier.
26- private stable var next : SuperheroId = 0 ;
26+ stable var next : SuperheroId = 0 ;
2727
2828 // The superhero data store.
29- private stable var superheroes : Trie . Trie < SuperheroId , Superhero > = Trie . empty();
29+ let Ops = Map . Make < SuperheroId > (Nat32 . compare);
30+ stable var map : Map . Map < SuperheroId , Superhero > = Ops . empty();
3031
3132 /**
3233 * High-Level API
@@ -36,57 +37,33 @@ actor Superheroes {
3637 public func create(superhero : Superhero ) : async SuperheroId {
3738 let superheroId = next;
3839 next += 1 ;
39- superheroes := Trie . replace(
40- superheroes,
41- key(superheroId),
42- Nat32 . equal,
43- ?superhero,
44- ). 0 ;
45- return superheroId;
40+ map := Ops . put(map, superheroId, superhero);
41+ return superheroId
4642 };
4743
4844 // Read a superhero.
4945 public query func read(superheroId : SuperheroId ) : async ?Superhero {
50- let result = Trie . find(superheroes, key( superheroId), Nat32 . equal );
51- return result;
46+ let result = Ops . get(map, superheroId);
47+ return result
5248 };
5349
5450 // Update a superhero.
5551 public func update(superheroId : SuperheroId , superhero : Superhero ) : async Bool {
56- let result = Trie . find(superheroes, key( superheroId), Nat32 . equal );
57- let exists = Option . isSome(result );
52+ let ( result, old_value) = Ops . replace(map, superheroId, superhero );
53+ let exists = Option . isSome(old_value );
5854 if (exists) {
59- superheroes := Trie . replace(
60- superheroes,
61- key(superheroId),
62- Nat32 . equal,
63- ?superhero,
64- ). 0 ;
55+ map := result
6556 };
66- return exists;
57+ return exists
6758 };
6859
6960 // Delete a superhero.
7061 public func delete(superheroId : SuperheroId ) : async Bool {
71- let result = Trie . find(superheroes, key( superheroId), Nat32 . equal );
72- let exists = Option . isSome(result );
62+ let ( result, old_value) = Ops . remove(map, superheroId);
63+ let exists = Option . isSome(old_value );
7364 if (exists) {
74- superheroes := Trie . replace(
75- superheroes,
76- key(superheroId),
77- Nat32 . equal,
78- null ,
79- ). 0 ;
65+ map := result
8066 };
81- return exists;
82- };
83-
84- /**
85- * Utilities
86- */
87-
88- // Create a trie key from a superhero identifier.
89- private func key(x : SuperheroId ) : Trie . Key < SuperheroId > {
90- return { hash = x; key = x };
91- };
92- };
67+ return exists
68+ }
69+ }
0 commit comments