Nockawa

Be efficient my friend: use StringDictionary!

3 posts in this topic

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!

NasimiAsl, Dal and jerome like this

Share this post


Link to post
Share on other sites

impressive and smart

mmmh.. don't you intend to add also a decent multithread model to js please ? :D

Dal likes this

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.