-
Notifications
You must be signed in to change notification settings - Fork 6
Solutions for function course tasks #6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Dmitriy-Yarygin
wants to merge
3
commits into
dmtrKovalenko:master
Choose a base branch
from
Dmitriy-Yarygin:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| // Реализовать композирующую функцию compose которая будет принимать неограниченное количество функций и вызывать их справа налево | ||
| function compose(...functionsArray) { | ||
| return (arg) => functionsArray.reduceRight( (temp,f) => { f(arg) }, 0); | ||
| } | ||
| // const validator = сompose(isEmail, maxLength(5)); | ||
| // const isValid = validate(“someemail@emal.com”) | ||
|
|
||
|
|
||
| // Переписать функцию из первого задания чтобы она вызывала каждую функцию с аргументом того что вернула предыдущая функция | ||
| function compose2(...functionsArray) { | ||
| return (argStart) => functionsArray.reduceRight( (argNext,f) => { return f(argNext) }, argStart); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
|
|
||
| // Напиши функцию создания генератора sequence(start, step). Она при вызове возвращает другую функцию-генератор, которая при каждом вызове дает число на 1 больше, и так до бесконечности. Начальное число, с которого начинать отсчет, и шаг, задается при создании генератора. Шаг можно не указывать, тогда он будет равен одному. Начальное значение по умолчанию равно 0. Генераторов можно создать сколько угодно | ||
| function sequence(start, step) { | ||
| f.count = start; | ||
| f.step = step; | ||
| function f() { | ||
| let res = f.count; | ||
| f.count += f.step; | ||
| return res; | ||
| } | ||
| return f; | ||
| } | ||
| const generator = sequence(10, 3); | ||
| const generator2 = sequence(7, 1); | ||
|
|
||
| console.log(generator()); // 10 | ||
| console.log(generator()); // 13 | ||
|
|
||
| console.log(generator2()); // 7 | ||
|
|
||
| console.log(generator()); // 16 | ||
|
|
||
| console.log(generator2()); // 8 | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| // Реализовать функцию шпиона которая будет сохранять количество вызовов функции | ||
| function makeSpyOn(f) { | ||
| counter.calls = 0; | ||
| function counter() { | ||
| counter.calls++; | ||
| f(); | ||
| } | ||
| return counter; | ||
| } | ||
| function c(msg = new Date().toLocaleString()) { | ||
| console.log(msg); | ||
| } | ||
| const spy = makeSpyOn(c) | ||
| spy() | ||
| spy() | ||
| console.log(spy.calls) // 2 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
|
|
||
| // Реализовать объект калькулятор у которого есть методы input, sum, mul, sub (ввод данных, сумма, умножение и вычитание). input должен вызывать ввод 2 цифр от пользователя через prompt и сохранять в себе. Остальные методы должны производить над цифрами соответствующие операции | ||
| let calculator = { | ||
| input: function () { | ||
| this.a = +prompt('Enter value A', 1); | ||
| this.b = +prompt('Enter value B', 2); | ||
| }, | ||
| sum: function () { | ||
| let res = this.a + this.b | ||
| console.log(res) | ||
| return res; | ||
| }, | ||
| mul: function () { | ||
| let res = this.a * this.b | ||
| console.log(res) | ||
| return res; | ||
| }, | ||
| sub: function () { | ||
| let res = this.a - this.b | ||
| console.log(res) | ||
| return res; | ||
| } | ||
| } | ||
|
|
||
| calculator.input(); | ||
| calculator.sum(); | ||
|
|
||
| // Реализовать другой калькулятор который не запрашивает данные, а работает с цепочкой вызовов | ||
| let calculator2 = { | ||
| res: 0, | ||
| input: function (x) { | ||
| this.res = x; | ||
| console.log(this.res); | ||
| return this; | ||
| }, | ||
| sum: function (x) { | ||
| this.res += x; | ||
| console.log(this.res); | ||
| return this; | ||
| }, | ||
| mul: function (x) { | ||
| this.res *= x; | ||
| console.log(this.res); | ||
| return this; | ||
| }, | ||
| sub: function (x) { | ||
| this.res -= x; | ||
| console.log(this.res); | ||
| return this; | ||
| } | ||
| } | ||
|
|
||
| calculator2.input(1).sum(2).mul(3).sub(4) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| // Реализовать свою функцию setTimeout которая бы не потеряла контекст вызова | ||
| var user = { | ||
| name: "John Smith", | ||
| sayHi: function () { | ||
| console.log(this.name) | ||
| }, | ||
| timeoutSayHi: function () { | ||
| setTimeout(this.sayHi.call(this), 1000); | ||
| } | ||
| }; | ||
| user.timeoutSayHi(); | ||
|
|
||
| // Сделать возможность дополнительно передать массив аргументов для вызываемой функции | ||
| var user2 = { | ||
| name: "John Smith", | ||
| sayHi: function (msg = this.name) { | ||
| console.log(msg) | ||
| }, | ||
| timeoutSayHi: function (...args) { | ||
| myTimeout(this, this.sayHi, args, 1000); | ||
| } | ||
| }; | ||
| function myTimeout(context, f, args, delay) { | ||
| setTimeout(f.apply(context, args), delay); | ||
| } | ||
|
|
||
| user2.timeoutSayHi("Hello!"); | ||
|
|
||
| // Написать функцию которая принимает функцию и количество миллисекунд и возвращает функцию обертку. Каждый раз когда обертка будет вызвана, | ||
| // должна вызываться внутренняя функция, НО внутренняя функция не должна быть вызвана чаще чем раз в переданное кол-во миллисекунд. | ||
| function myTimeoutWrapper(f, delay) { | ||
| let timerId = null; | ||
| return function () { | ||
| if (timerId === null) { | ||
| f(); | ||
| } else { | ||
| timerId = setTimeout(() => { timerId = null; }, delay); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Написать функцию которая принимает функцию и количество миллисекунд и возвращает функцию обертку. Каждый раз когда обертка будет вызвана, | ||
| // должна вызываться внутренняя функция, НО внутренняя функция не должна быть вызвана если с момента предыдущего вызова не прошло заданное кол-во миллисекунд. | ||
| function myTimeoutWrapper2(f, delay) { | ||
| let timerId = null; | ||
| return function () { | ||
| if (timerId === null) { | ||
| f(); | ||
| } | ||
| timerId = setTimeout(() => { timerId = null; }, delay); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| // Написать свою систему модулей которая позволит инкапсулировать локальное состояние. | ||
| const module = createModule('module',() => { | ||
| return { | ||
| sayHi: () => alert('HI') | ||
| } | ||
| }) | ||
|
|
||
| const anotherModule = createModule('newModule', () => { | ||
| const myFirstModule = require('module') | ||
| }) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why indent here?