patternjavascriptMinor
Creating an object out of an array of functions
Viewed 0 times
creatingarrayfunctionsobjectout
Problem
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.
Usage:
Thoughts?
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?
Solution
Why use the underscore at all.
For simple array manipulation, the objecfify can be modified as below:
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;
}Code Snippets
function objecfify(arr) {
var res = {};
for (var i = 0, l = arr.length; i < l; i++) {
res[functionName(arr[i])] = arr[i];
}
return res;
}Context
StackExchange Code Review Q#97435, answer score: 3
Revisions (0)
No revisions yet.