3
\$\begingroup\$

Here's a function that allows you to convert an array of functions into an object of functions where each property is set to the name of the function.

var _ = require("underscore")

function functionName(fn){
  //http://stackoverflow.com/a/17923727/340688
  if(fn.name) return fn.name
  return /^function\s+([\w\$]+)\s*\(/.exec(fn.toString())[1]
}

function objecfify(arr){
  return _.chain(arr)
    .map(function(fn){
      return [functionName(fn), fn]
    })
    .object()
    .value()
}

Usage:

var model = objecfify([
  function create(){
    return "create"
  },
  function read(){
    return "read"
  },
  function update(){
    return "update"
  },
  function remove(){
    return "delete"
  }
])

console.log(model)

Thoughts?

\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

Why use the underscore at all.

For simple array manipulation, the objecfify can be modified as below:

function objecfify(arr) {
    var res = {};
    for (var i = 0, l = arr.length; i < l; i++) {
        res[functionName(arr[i])] = arr[i];
    }
    return res;
}
\$\endgroup\$
2
\$\begingroup\$

You want to reduce an array into a single value (in this case, an object), why not use .reduce()?

function objectify(arr) {
    return arr.reduce(function(result, current) {
        result[functionName(current)] = current;
        return result;
    }, {});
}

Reduce takes two parameters:

  1. A reduction function, which in turn takes two parameters

    1. The previous value, as returned by the previous iteration of the reduction function
    2. The current value, changes with each iteration to reflect the current element

      Note: The reduction function also takes two more, optional parameters. The index of the current element in the original array, and the array itself.

  2. An initial value, we're building an object, so our initial value is an empty object.


Bonus

we can make it more general by passing the key generation function as a second parameter to objectify, then it can work with every array, even if they aren't functions:

function objectify(arr, keyFunction) {
    return arr.reduce(function(result, current) {
        result[keyFunction(current)] = current;
        return result;
    }, {});
}

Then use like this:

objectify(arrayOfFunctions, functionName)
\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.