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?

2
  • 2
    What functionality do you want to achieve? / That you can not when using the functions name as the key...? Commented Apr 29, 2015 at 16:48
  • 2
    The keys in a object are always strings or numbers. Here you can read more :stackoverflow.com/questions/6066846/… Commented Apr 29, 2015 at 16:50

2 Answers 2

1

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

result = {};
result[func] = true;
return result;
Sign up to request clarification or add additional context in comments.

1 Comment

@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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.