将对象属性作为函数参数传递
Passing object properties as function argument?
我有这三个函数,它们基本上做同样的事情。它们从promise中获取数据,并为每个函数创建具有相同属性的对象。
I would like to DRY this out:
var getFiles = function() {
return wg.getFiles().then(function(data) {
processData(data, {
type: "File",
title: x.filename,
created: x.Created,
path: x.path
})
})
}
var getEvents = function() {
return wg.getEvents().then(function(data) {
processData(data, {
type: "Event",
title: x.Title,
created: x.Created,
path: x.path
})
})
}
var getFeedback = function() {
return wg.getFeedback().then(function(data) {
processData(data, {
type: "Review",
title: "by " + x.Author,
created: x.Created,
path: x.path
})
})
}
var processData = function(data, props) {
var x = _(data)
.map(function(x) {return props})
.value()
.map(function(x) {
activties.push(x)
})
}
我想通过将processData
函数更改为如下内容来DRY:
var processData = function(data, props) {
var x = _(data)
.map(function(x) {
return {
type: x[props[0]],
title: x[props[1]],
created: x[props[3]],
path: "/" + x[props[4]]
}
})
.value()
.map(function(x) {
activties.push(x)
})
}
那么我可以这样命名它:
var getFiles = function() {
return wg.getFiles().then(function(data) {
processData(data, ['filename', 'created', ['FileRef']['lookupValue']])
})
}
这就是我的想法,但如果有人有更好的建议,我愿意接受。
不传递属性名,传递函数:
function getFiles() {
return wg.getFiles().then(processData("File", _.property("filename")));
}
function getEvents() {
return wg.getEvents().then(processData("Event", _.property("Title")));
}
function getFeedback() {
return wg.getFeedback().then(processData("Review", function(x) { return "by " + x.Author; })));
}
function processData(type, makeTitle) {
return function(data) {
return data.map(function(x) {
return {
type: type,
title: makeTitle(x),
created: x.Created,
path: x.path
};
});
};
}
Promise.all([getFiles(), getEvents(), getFeedback()])
.then(function(arrays) {
var activities = _.flatten(arrays);
…
});
为方便起见,我使用了一些下划线/lodash函数,但您也可以不使用它们。
相关文章:
- 在构造控制器、服务等时作为函数参数传递之前列出的角度 JS 变量
- 作为函数参数传递的匿名函数的范围
- 通过函数参数传递id
- 将数组值作为函数参数传递
- 是否需要初始化在 Javascript 中作为“类”构造函数参数传递的变量
- JavaScript 函数参数传递数组
- Angular2 将函数参数传递给构造函数
- 为什么我不能将角度变量作为函数参数传递
- jQuery - 基于作为函数参数传递的对象构建动态 if 语句
- 停止对作为函数参数传递到新列表的对象引用
- 在 JavaScript 中将数组作为内置函数参数传递
- AngularJS将范围变量名称作为函数参数传递
- Javascript 将对象作为函数参数传递
- 在对象上调用方法或将对象作为函数参数传递的差异
- 正确的方法:始终将所有变量作为函数参数传递
- 如何将动态创建的复选框值作为函数参数传递
- 节点简斯 |将对象作为函数参数传递
- 什么是将对象属性作为函数参数传递的良好策略/模式
- 将对象作为函数参数传递.不确定如何访问这些值
- 为什么我们要将函数参数传递到$scope$申请