我在Ruby中有一段代码我希望将其转换为Javascript但我对这个过程并不太熟悉,因为我还在学习。任何人都可以翻译这个例子,这对我的学习很有帮助,谢谢!
class TestFunky < MiniTest::Test
def setup
@funky = Funky.new
end
def test_adds_when_you_input_a_plus_5_6_plus
assert_equal 11, @funky.push(5).push(6).push(:+)
end
def test_adds_when_you_input_a_plus_6_6_plus
assert_equal 12, @funky.push(6).push(6).push(:+)
end
和另一个
class NumberArray < Array
def sum_or_multiply(operator)
self.inject(operator)
end
def push(number)
raise TypeError unless number.is_a? (Numeric)
super
end
end
class Funky
def initialize
@numbers = NumberArray.new
end
def push(something)
if operator?(something)
process_operator(something)
else
store(something)
self
end
end
答案 0 :(得分:0)
以下是我认为您正在寻找的内容的粗略概念。
这些类定义基于Coffeescript implementation of classes和Mozilla guide on Object-Oriented Javascript
TestFunky = (function(_super) {
function TestFunky() {
}
TestFunky.prototype = Object.create(_super.prototype);
TestFunky.prototype.constructor = TestFunky;
TestFunky.prototype.setup = function() {
this.funky = new Funky();
};
TestFunky.prototype.testAddsWhenYouInputAPlus56Plus = function() {
assert.equal(11, this.funky.push(5).push(6).push('+'));
};
TestFunky.prototype.testAddsWhenYouInputAPlus66Plus = function() {
assert.equal(12, this.funky.push(6).push(6).push('+'));
};
return TestFunky;
})(MiniTest);
NumberArray = (function(_super) {
function NumberArray() {
}
NumberArray.prototype = Object.create(_super.prototype);
NumberArray.prototype.constructor = NumberArray;
NumberArray.prototype.sumOrMultiply = function(operator) {
this.inject(operator);
};
NumberArray.prototype.push = function(number) {
if (typeof number !== 'number') {
throw new Error();
}
_super.prototype.push.apply(this, arguments);
};
return NumberArray;
})(Array);
Funky = (function() {
function Funky() {
this.numbers = new NumberArray();
}
Funky.prototype.push = function(something) {
if (this.operator(something)) {
return this.processOperator(something);
} else {
this.store(something);
return this;
}
};
return Funky;
})();
一旦定义了这些,就像这样实例化它们
var funkyInstance = new Funky()