如何在 JavaScript 中组合原型函数样式?
How To Combine Prototype Function Styles in JavaScript?
我因 5 "simular" 原型函数的重复而受到 CodeClimate 的指责,因为重复导致了 D 评级。
我缺乏关于如何组合/不重复类似代码以改进我的知识 "code style"。非常感谢您的帮助。
原型:
SomeThing.prototype.destination = function(path) {
if (!arguments.length) {
return this.path(this._destination);
}
assert(is.string(path), 'You must pass a destination path string.');
SomeThing.prototype.frontmatter = function(frontmatter) {
if (!arguments.length) {
return this._frontmatter;
}
assert(is.boolean(frontmatter), 'You must pass a boolean.');
SomeThing.prototype.clean = function(clean) {
if (!arguments.length) {
return this._clean;
}
assert(is.boolean(clean), 'You must pass a boolean.');
SomeThing.prototype.concurrency = function(max) {
if (!arguments.length) {
return this._concurrency;
}
assert(is.number(max), 'You must pass a number for concurrency.');
这会干掉你的代码:
function makeProp(prop, type) {
return function(someArg) {
if (!arguments.length) return this['_' + prop];
var msg = 'You must pass a ' + type + ' for ' + prop;
assert(is[type], msg)
}
}
Something.prototype = {
destination: makeProp('destination', 'string'),
frontmatter: makeProp('frontmatter', 'boolean'),
clean: makeProp('clean', 'boolean'),
concurrency: makeProp('concurrency', 'number')
}
我因 5 "simular" 原型函数的重复而受到 CodeClimate 的指责,因为重复导致了 D 评级。
我缺乏关于如何组合/不重复类似代码以改进我的知识 "code style"。非常感谢您的帮助。
原型:
SomeThing.prototype.destination = function(path) {
if (!arguments.length) {
return this.path(this._destination);
}
assert(is.string(path), 'You must pass a destination path string.');
SomeThing.prototype.frontmatter = function(frontmatter) {
if (!arguments.length) {
return this._frontmatter;
}
assert(is.boolean(frontmatter), 'You must pass a boolean.');
SomeThing.prototype.clean = function(clean) {
if (!arguments.length) {
return this._clean;
}
assert(is.boolean(clean), 'You must pass a boolean.');
SomeThing.prototype.concurrency = function(max) {
if (!arguments.length) {
return this._concurrency;
}
assert(is.number(max), 'You must pass a number for concurrency.');
这会干掉你的代码:
function makeProp(prop, type) {
return function(someArg) {
if (!arguments.length) return this['_' + prop];
var msg = 'You must pass a ' + type + ' for ' + prop;
assert(is[type], msg)
}
}
Something.prototype = {
destination: makeProp('destination', 'string'),
frontmatter: makeProp('frontmatter', 'boolean'),
clean: makeProp('clean', 'boolean'),
concurrency: makeProp('concurrency', 'number')
}