Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a function as dictionary

Tags:

javascript

I am designing a small library, and trying to keep the API as small as possible, the idea of using a function as a dictionary/object itself looks appealing.

The idea is to be able to call a function normally like:

fn('hello', 'some other extra info to be processed', etc...)

This call will process the information and then store it somewhere. This processed information can be accessed in certain conditions (not the typical use case), and it would be great to fetch information in this fashion:

fn['hello']
//-> some stuff

In python for instance it would be very easy to overload the [] operator, but AFAIK there is not an easy and reliable way in JS that works in most environments (proxies seem to do the trick, but we are not so far yet). Getters and setters are not an option since the user can input any value.

Therefore, I am left with setting attributes of the function object, which seems hacky because I might overwrite the original attributes of the function, for instance:

  • apply
  • prototype
  • __proto__

However, many things in the JS world are hacky and we happily do them everyday. The question: is this unsafe and will lead to the death of thousands of kittens?

like image 624
bgusach Avatar asked Jan 07 '23 01:01

bgusach


1 Answers

You could use setter and getter functions for it.

The disadvantage is, you have to know in advance which keys you use.

function fn(s) {
    if (!fn[s]) {
        Object.defineProperty(fn, s, { get: function () { document.write('hello '+s+'!<br>'); }, set: function () { } });
    }
    document.write('hello ' + s + '<br>');
}

fn('stackoverflow');
fn['stackoverflow'];
fn('42');
fn['42'];
fn['stackoverflow'];
like image 158
Nina Scholz Avatar answered Jan 08 '23 14:01

Nina Scholz