Skip to content

Instantly share code, notes, and snippets.

@SerafimArts
Last active February 21, 2016 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SerafimArts/f6538436bd5b6cc7f00b to your computer and use it in GitHub Desktop.
Save SerafimArts/f6538436bd5b6cc7f00b to your computer and use it in GitHub Desktop.
Яндекс: Задача на собеседование №2
/**
* Вменяемый код
*
* Функция предоставляет вменяемый и расшираемый интерфейс
* для работы с требуемой функцией.
*
* Плюс такого подхода в чистоте кода и возможности
* для будущей поддержки без извращений (например
* логгирование, всякие другие плюшки, в том числе наследоваться).
*
* Так же генерация объекта предоставляет возможность
* использования множества независимых инстансов блокировщиков вызовов.
*
* Использование:
*
* var foo = new FunctionTimeout(function(){
* console.log(42);
* });
* foo.call(); // вызывается раз в одну секунду
*
*/
var FunctionTimeout = (function(){
/**
* Конструктор
*
* @param cb
* @param interval
* @constructor
*/
function FunctionTimeout(cb, interval){
this.callback = cb != null
? cb
: (function(){});
this.interval = interval != null
? interval
: 1000;
}
/**
* Проверка доступности метода на выполнение
* @returns {*}
*/
FunctionTimeout.prototype.check = function(){
if (this.constructor.name != 'FunctionTimeout') {
throw new Error('Невозможно вызвать метод из контекста прототипа');
}
if (this.timeout){ return null; }
var _this = this;
this.timeout = setTimeout(function(){
return _this.timeout = false;
}, this.interval);
return true;
};
/**
* Вызов (попытка вызова) нужного метода
* @returns {*}
*/
FunctionTimeout.prototype.call = function() {
if (this.constructor.name != 'FunctionTimeout') {
throw new Error('Невозможно вызвать метод из контекста прототипа');
}
return this.check()
? this.callback()
: null;
};
return FunctionTimeout;
})();
/**
* Невменяемый код.
*
* Нет никаких плюсов, кроме скорости.
*
* Алгоритм отличается от предыдущего тем, что
* основывается на временных интервалах, а не таймаутах.
*/
var N = 1000;
var time = false;
function check(foo) {
if (!time || time + 1000 < (new Date()).getTime()) {
time = (new Date()).getTime();
foo();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment