Last active
March 3, 2019 12:15
-
-
Save romec512/9347750c9adf90629f27cd254a53b7b5 to your computer and use it in GitHub Desktop.
Первая лаба по web
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
'use strict'; | |
function getCurrentArray(originalArray, filterCriteria) { | |
var currentArray = []; | |
for(var i = 0; i < originalArray.length; i++){ | |
if(filterCriteria(originalArray[i])){ | |
currentArray.push(originalArray[i]); | |
} | |
} | |
return currentArray; | |
} | |
var MakeMultiFilter = function MakeMultiFilter(originalArray) { | |
var currentArray = originalArray; | |
/* | |
MakeMultiFilter возвращает функцию, когда мы вызываем эту ф-ию, она выполняется как бы внутри кода ф-ии MakeMultiFilter | |
поэтому если внутри функции MakeMultiFilter объявить currentArray, он будет доступен всегда внутри возвращаемой ф-ии | |
и таким образом мы можем отслеживать текущее состояние массива | |
*/ | |
var func = function returnedFunc(filterCriteria, callback) { | |
//Если нет параметров, возвращаем текущий массив | |
if(typeof filterCriteria === "undefined" && typeof callback === "undefined"){ | |
return currentArray; | |
}//если оба параметры заданы | |
else if(typeof filterCriteria === "function" && typeof callback === "function"){ | |
//находим отфильтрованный массив | |
currentArray = getCurrentArray(originalArray, filterCriteria); | |
//добавляем callback функции контекст оригинальный массив (ссылаем this на массив) | |
var callbackWithNewContext = callback.bind(originalArray); | |
//вызываем эту функцию | |
callbackWithNewContext(currentArray); | |
//возвращаем саму себя | |
return func; | |
} else if(typeof filterCriteria === "function" && typeof callback !== "function"){ | |
//если есть только критерий, без callback ф-ии, то фильтруем массив | |
currentArray = getCurrentArray(currentArray,filterCriteria); | |
//возвращаем саму себя | |
return func; | |
} | |
}; | |
return func; | |
}; |
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
'use strict'; | |
var TemplateProcessor = function TemplateProcessor(_template){ | |
this.template = _template; | |
this.fillIn = function fillIn(dictionary){ | |
for(var key in dictionary){ | |
//производим замену ключей на нужные значения | |
this.template = this.template.replace("{{" + key + "}}", dictionary[key]); | |
} | |
//пока у нас в строке есть любые подстроки вида {{какая_то_строка}} | |
//которых не было в dictionary, мы заменяем их на пустоту | |
while(this.template.search(/{{\w+}}/) !== -1){ | |
this.template = this.template.replace(/{{\w+}}/, ""); | |
} | |
return this.template; | |
}; | |
}; |
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
'use strict'; | |
/* | |
* This file tests the JavaScript assignment problems. It prints what | |
* it finds to the console log and updates the text being displayed in the window with a | |
* summary of the results. | |
*/ | |
// We assume these symbols will be globally defined by the user. These var statements | |
// will assign undefined to the symbol if it isn't global already. | |
// These global symbols are needed to test your file and you don't have to worry about them for Problem 3. | |
var MakeMultiFilter; | |
var TemplateProcessor; | |
/*Паттерн "модуль" подразумевает использование такой конструкции, когда весь код помещается | |
в функцию, которая сразу же вызывается | |
*/ | |
(function () { | |
// Result message for Problems 1-3 | |
var p1Message = 'SUCCESS'; | |
var p2Message = 'SUCCESS'; | |
var p3Message = 'SUCCESS'; | |
// Keep track of all the var statements | |
var varDeclared = ['varDeclared', 'p1Message', 'p2Message', 'p3Message']; | |
// ********************* Test filter | |
if (typeof MakeMultiFilter !== 'function') { | |
console.error('MakeMultiFilter is not a function', typeof MakeMultiFilter); | |
p1Message = 'FAILURE'; | |
} else { | |
var arraysAreTheSame = function arraysAreTheSame(a1, a2) { | |
if (!Array.isArray(a1) || !Array.isArray(a2) || (a1.length !== a2.length)) { | |
return false; | |
} | |
for (var i = 0; i < a1.length; i++) { | |
if (a1[i] !== a2[i]) { | |
return false; | |
} | |
} | |
return true; | |
}; | |
var originalArray = [1, 2, 3]; | |
var filterFunc = new MakeMultiFilter(originalArray); | |
var secondArray = [1, 2, 3, 4]; | |
var filterFuncTwo = new MakeMultiFilter(secondArray); | |
if (typeof filterFunc !== 'function') { | |
console.error('MakeMultiFilter does not return a function', filterFunc); | |
p1Message = 'FAILURE'; | |
} else { | |
var result = filterFunc(); | |
if (!arraysAreTheSame([1, 2, 3], result)) { | |
console.error('filter function with no args does not return the original array', result); | |
p1Message = 'FAILURE'; | |
} | |
var callbackPerformed = false; | |
result = filterFunc(function (item) { | |
return item !== 2; | |
}, function (callbackResult) { | |
callbackPerformed = true; | |
if (!arraysAreTheSame([1, 3], callbackResult)) { | |
console.error('filter function callback does not filter 2 correctly', callbackResult); | |
p1Message = 'FAILURE'; | |
} | |
if (!arraysAreTheSame([1, 2, 3], this)) { | |
console.error('filter function callback does not pass original array as this', this); | |
p1Message = 'FAILURE'; | |
} | |
}); | |
if (!callbackPerformed) { | |
console.error('filter function callback not performed'); | |
p1Message = 'FAILURE'; | |
} | |
if (result !== filterFunc) { | |
console.error('filter function does not return itself', result); | |
p1Message = 'FAILURE'; | |
} | |
result = filterFunc(function (item) { | |
return item !== 3; | |
}); | |
if (result !== filterFunc) { | |
console.error('filter function does not return itself 2', result); | |
p1Message = 'FAILURE'; | |
} | |
result = filterFunc(); | |
if (!arraysAreTheSame([1], result)) { | |
console.error('filter function callback does not filter 3 correctly', result); | |
p1Message = 'FAILURE'; | |
} | |
result = filterFuncTwo(function (item) { | |
return item !== 1; | |
}, function (callbackResult) { | |
if (!arraysAreTheSame([2, 3, 4], callbackResult)) { | |
console.error('second filter does not filter 1 (check for global variable usage)', callbackResult); | |
p1Message = 'FAILURE'; | |
} | |
if (!arraysAreTheSame([1, 2, 3, 4], this)) { | |
console.error('filter function callback does not pass original array as this', this); | |
p1Message = 'FAILURE'; | |
} | |
}); | |
} | |
} | |
console.log('Test MakeMultiFilter:', p1Message); | |
// ********************* Test TemplateProcessor | |
if (typeof TemplateProcessor !== 'function') { | |
console.error('TemplateProcessor is not a function', TemplateProcessor); | |
p2Message = 'FAILURE'; | |
} else { | |
var template = 'My favorite month is {{month}} but not the day {{day}} or the year {{year}}'; | |
var dateTemplate = new TemplateProcessor(template); | |
var dictionary = {month: 'July', day: '1', year: '2016'}; | |
var str = dateTemplate.fillIn(dictionary); | |
if (str !== 'My favorite month is July but not the day 1 or the year 2016') { | |
console.error('TemplateProcessor didn\'t work'); | |
p2Message = 'FAILURE'; | |
} | |
varDeclared.push('template'); | |
varDeclared.push('dateTemplate'); | |
varDeclared.push('dictionary'); | |
varDeclared.push('str'); | |
} | |
console.log('Test TemplateProcessor:', p2Message); | |
// ********************* Test to see if the symbols we defined are in the global address space | |
varDeclared.forEach(function (sym) { | |
if (window[sym] !== undefined) { | |
console.error('Found my symbol', sym, 'in DOM'); | |
p3Message = 'FAILURE'; | |
} | |
}); | |
console.log('Test Problem 3:', p3Message); | |
// Store the result back into the global space under the object name Project2Results | |
window.Project2Results = { | |
p1Message: p1Message, | |
p2Message: p2Message, | |
p3Message: p3Message, | |
}; | |
// Once the browser loads our companion HTML in -test-project2.html we | |
// update it with the results of our testing. This code will make more | |
// sense after the next project. | |
window.onload = function () { | |
document.getElementById("p1").innerHTML = p1Message; | |
document.getElementById("p2").innerHTML = p2Message; | |
document.getElementById("p3").innerHTML = p3Message; | |
}; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment