Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Помогите сделать задание (https://javascript.ru/forum/misc/64493-pomogite-sdelat-zadanie.html)

malin 15.08.2016 20:04

Помогите сделать задание
 
Задание такое

5. JavaScript

Description:

Write a functions that will make basic math calculations to produce results like in the following example. Please, do not use "eval":

three(times(five())); // must return 15
four(plus(eight())); // must return 12
eight(minus(two())); // must return 6
six(dividedBy(three())); // must return 2

Your Solution (you can change the template whatever you want):

function zero(x) {}
function one(x) {}
function two(x) {}
function three(x) {}
function four(x) {}
function five(x) {}
function six(x) {}
function seven(x) {}
function eight(x) {}
function nine(x) {}

function plus(x) {}
function minus(x) {}
function times(x) {}
function dividedBy(x) {}

function checkCalculations() {
console.log(three(times(five())));
console.log(four(plus(eight())));
console.log(eight(minus(two())));
console.log(six(dividedBy(three())));
}

рони 15.08.2016 20:47

malin,
первые десять проверяют аргумент наличие x и возвращают x ? x(num) : num -- это содержимое всех этих функций, следующие 4 должны вернуть функции - 90% задания выполнено :)

nerv_ 15.08.2016 22:24

Сделал, как сказал рони :)

alert(three(times(five()))); // must return 15

function three(x) {
	return x ? x(3) : 3;
}

function five(x) {
	return x ? x(5) : 5;
}

function times(x) {
	return function(y) {
  	return x * y;
  }
}


Еще можно составить задание под это
class MathChain {
	constructor(n) {
  	this.n = n || 0;
  }
  plus(k) {
  	this.n += k;
  	return this;
  }
  minus(k) {
  	this.n -= k;
    return this;
  }
  multiply(k) {
  	this.n *= k;
    return this;
  }
  divide(k) {
  	this.n /= k;
    return this;
  }
  valueOf() {
  	return this.n;
  }
  toString() {
  	return this.n;
  }
  toJSON() {
  	return this.n;
  }
}

let n = new MathChain(3).plus(4).multiply(2);

alert(n);

рони 15.08.2016 22:29

nerv_,
:victory:

malin 16.08.2016 11:00

спасибо


Часовой пояс GMT +3, время: 01:55.