Nockawa

Be efficient my friend: use StringDictionary!

Recommended Posts

Hello everybody, so this post is mainly for TypeScript people, even if Javascript folks could find some interest in this class.

As you may all know the Associative Array of Javascript is the most efficient way to store/check/retrieve data based on a string (and a string only), so I've created a little class that wraps this feature nicely in TypeScript with some additional features.

This is a generic class, the type of the value stored in the Dictionary is give at construction.

Then you have many methods to interact with the dictionary:

  • add(), to add an object from its key, will return false if the key is already taken
  • set(), to change the value corresponding to the given key, false will be returned if there's no such key.
  • getOrAdd(), return the value of the given key, if there's no such key the given value will be added.
  • getOrAddWithFactory(), same as above but more efficient: if the key doesn't exist then the given factory will be called to create the object to store.
  • contains(), to check if a given key is stored
  • remove(), to remove the key and its corresponding value.
  • clear(), to reset the whole dictionary
  • forEach(), you give a callback that will be called for each key/value in the dictionary
  • first<TRes>(), you give a callback that will be called for each key/value in the dictionary until the callback returns a valid <TRes> object, then the enumeration will stop.
  • the count read-only property will return the count of key/value stored in the dictionary.

The best way to store/check/retrieve data efficiently is by using a string as a key, so make sure you do! Converting a number to string worth doing it apparently to rely on associative array.

Feedback is welcome. happy coding!

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

  • Recently Browsing   0 members

    No registered users viewing this page.