Reputation: 2556
It's the test task on the job.
A farmer has rabbits. Each rabbit is its weight. When the time comes, he kills them function cut(rabbit)
.
You must write a function of cut so that it had the appearance of
cut(rabbit1)(rabbit2)...(rabbitN)
and deduced the total mass and the number of rabbits.
For example:
var rabbit1 = {weight: 5},
rabbit2 = {weight: 4};
console.log(cut(rabbit1)(rabbit2));
In the console we will see "9 kg of rabbits or 2 pieces".
JSFiddle - https://jsfiddle.net/sjao7ut8/
How I can write function cut()
?
Upvotes: 4
Views: 118
Reputation: 548
You can try following code:
var farmer = {
cut: function(rabits) {
var cutWeight = 10;
var totalCuts = 0;
var totalWeight = 0;
var count = rabits.length;
for(var i=0; i < count; i++) {
var rabit = rabits[i];
if(rabit.weight >= cutWeight) {
totalWeight += rabit.weight;
if(totalCuts === 0) {
totalCuts = 1;
}
else {
totalCuts += 1;
}
}
}
console.log(totalWeight + "Kg of Rabits and " + totalCuts + "cuts.")
}
};
farmer.cut([{weight: 11}, {weight: 5}, {weight: 13}]); // Call the function
Hope this will help you.
Upvotes: 0
Reputation: 238
Function.prototype.toString = function() {
return Function.prototype.rabbitsWeight + "кг кроликов или " + Function.prototype.rabbitsCount + " штук";
};
Function.prototype.rabbitsWeight = 0;
Function.prototype.rabbitsCount = 0;
window.rabbitsCut = eval("new Function('rabbit', 'Function.prototype.rabbitsWeight += rabbit.weight; ++Function.prototype.rabbitsCount; return eval(window.rabbitsCut);');");
var cut = window.rabbitsCut;
console.log(cut({weight: 5})({weight: 4}));
Upvotes: -1
Reputation: 386766
You could use chaining, a fluent interface, which returns the function you called until the environment requires a primitive value.
function cut(rabbit) {
var weight = 0,
count = 0,
fn = function (o) {
weight += o.weight;
count++;
return fn;
};
fn.toString = function () {
return weight + ' kg of rabbits or ' + count + ' piece' + (count > 1 ? 's' : '');
}
return fn(rabbit);
}
var rabbit1 = { weight: 5 },
rabbit2 = { weight: 4 };
console.log(cut(rabbit1)(rabbit2));
Upvotes: 7
Reputation: 6381
what you need to do here is to use recursive call, which returns a function and uses arguments.callee
something like this should do the job:
function cut(firstRabbit) {
var mass = firstRabbit.weight;
return function(nextRabbit) {
if (typeof nextRabbit !== 'undefined') {
mass += nextRabbit.weight;
return arguments.callee;
} else {
return mass;
}
};
}
Example usage (remember to add () at the end):
var rabbit1 = {weight: 5},
rabbit2 = {weight: 4};
console.log(cut(rabbit1)(rabbit2)());
Upvotes: 0