1

I have a function that accepts a function parameter that I'd like to use as the key to an object...

function foo(func) {
    return { func: true };
}

This, of course, returns an object with the string 'func' as the key (not what I want).

Is the right solution to create a string from func and then create the object?

Is there a way to create a hash from a function?

sfletche
  • 47,248
  • 30
  • 103
  • 119
  • 2
    What functionality do you want to achieve? / That you can not when using the functions _name_ as the key...? – fast Apr 29 '15 at 16:48
  • 2
    The keys in a object are always strings or numbers. Here you can read more :http://stackoverflow.com/questions/6066846/keys-in-javascript-objects-can-only-be-strings – vjdhama Apr 29 '15 at 16:50

2 Answers2

1

Bearing in mind that object keys are always strings you should be able to use this syntax:

result = {};
result[func] = true;
return result;
Community
  • 1
  • 1
D-side
  • 9,150
  • 3
  • 28
  • 44
  • 1
    @sfletche sure. But beware: keys are always strings. And even though other types may appear to work at a first glance, they might bite you with awkward bugs in future. – D-side Apr 29 '15 at 17:04
1

Though you can use functions as keys directly, you can use a hash code function to get the string representation of the function to create integer keys. I got one from http://erlycoder.com/49/javascript-hash-functions-to-convert-string-into-integer-hash-.

function hashFunc(func){
    var str = func.toString();

    var hash = 0;
    if (str.length == 0) return hash;
    for (i = 0; i < str.length; i++) {
        char = str.charCodeAt(i);
        hash = ((hash<<5)-hash)+char;
        hash = hash & hash; // Convert to 32bit integer
    }
    console.log(hash);
    return hash;
}

var col = {}

function add(func) {
    col[hashFunc(func)] = true;
}

function get(func) {
    return col[hashFunc(func)] || false;
}

// test
add(hashFunc);
console.log(get(add)); // false
console.log(get(hashFunc)); // true
Daniel Gimenez
  • 18,530
  • 3
  • 50
  • 70