Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 95 additions & 0 deletions Task1/mysort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*jslint nomen: true*/
/*global alert: true*/
/*global _testElAscending: true*/
/*global _testElNotAscending: true*/
/*global _testElAscendingAndEqualsElement: true*/
/*global _runTestSortArray: true*/
/*global _testElNotAscendingAndEqualsElement: true*/
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

вместо глобалов можно было сначало объявить функцию, а потом ее использовать те runTestsSort опустить в самый конец скрипта

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Но тогда код будет неопрятным. Так как в начале файла, модуля, класса должно быть самое важное. Ну это на мой взгляд.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Код должен быть максимально самодокументированным. Используй тогда модуль заодно и от _ избавишься

var mySpecialFunction = (function () {

    function myPrivate() {

    }

    return function () {
        var stuff = myPrivate();

        return stuff * 42;
    };

}());

mySpecialFunction(100500);

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Я не понял комментария на счет "самодокументированности кода".
    Писать комментарии? - мне кажется это избыточно в данной ситуации (так как не очевидного кода нет) - DRY
    Писать тесты в которых описано как и что работает? - я это вроде бы написал в той или иной степени
    Писать вики документацию? - когда я устраивался на стажировку мой код с вики документацией "обсмеяли" - DRY.
  2. Если мы засунем все в функцию:
    • ограничили видимость функции
    • я не понимаю как протестировать "внутренние" функции.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

самодокументированности кода - всмысле, что код должен быть понятен и без коментариев. Коментарии только для не очевидных штук (алгоритмы, датафлоу, пояснения к аргументам функции итп).

Совсем не посмотрел на имена функций - все они тесты. Оставь как есть. Не заморачивайся :)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А можете выложить под тестовым пользователем, вашу версию данной задачи? хочется научиться чему, то хорошему.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот что бы я сделал по максимуму:

  • Сделал бы из файла модуль (LMD или AMD)
  • JSDoc для всех публичных функций (те, что на экспорт из модуля) с @example
  • Сделал бы из модуля npm-пакет - package.json (прописал бы все зависимости)
  • Добавил бы юнит-тестов на основе QUnit или Mocha test/*
  • Сделал бы автоматизированный и безбраузерный запускатель тестов на node.js и PhantomJS
  • Сделал бы автоматизированную проверку кода JSHint (не JSLint)
  • Предыдущие 2 должны запускаться по make test и npm test
  • Сделал бы git-hook на основе JSHint, который не давал бы мне коммитить говнокод (желательно это сделать сразу иначе потом забиваешь).
  • Сделал бы автоматизированную сборку документации make docs
  • Прописал бы проект в TravisCI для автоматизированного тестирования каждого моего коммита в git origin
    • TravisCI при каждом коммите скачивает к себе мой репозиторий выполняет npm install && npm test (вобщем автоматом ставит и запускает базбраузерные тесты)

Почти все это я сделал тут https://github.com/azproduction/lmd

function bubbleSort(arr) {
"use strict";
if (!((typeof (arr) === 'object') && (arr instanceof Array))) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typeof - оператор, а не функция - можно скобки не ставить

throw "You get me not array";
}
var i = 0, j = 0, temp;
for (i = 0; i < arr.length; i += 1) {
for (j = 0; j < arr.length; j += 1) {
if (arr[i] < arr[j]) {
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
}
//Ниже функции для проверки сортировки
//За эталонную сортировку я взял Sort
//Да для этого лучше всего использовать библиотеку для Unit тестирования.
//Но мне было лениго в ней разбираться. ПОэтому написан небольшой свой велосипед

function runTestsSort() {
"use strict";
var numberTest;
try {
numberTest = 1;
_testElAscending();
numberTest += 1;
_testElNotAscending();
numberTest += 1;
_testElAscendingAndEqualsElement();
numberTest += 1;
_testElNotAscendingAndEqualsElement();
numberTest += 1;
//_testNoArray();
//numberTest++;
} catch (e) {
//Это конечно лучше писать в лог
alert("Тест " + numberTest + " упал");
return;
}
//И это тоже
alert("Тесты пройдены успешно");
}

function _testElAscending() {
"use strict";
var array = [1, 2, 3, 4, 5];
_runTestSortArray(array, bubbleSort);
}
function _testElNotAscending() {
"use strict";
var array = [5, 4, 3, 2, 1];
_runTestSortArray(array, bubbleSort);
}
function _testElAscendingAndEqualsElement() {
"use strict";
var array = [1, 2, 3, 4, 4, 5];
_runTestSortArray(array, bubbleSort);
}
function _testElNotAscendingAndEqualsElement() {
"use strict";
var array = [5, 4, 3, 2, 2, 1];
_runTestSortArray(array, bubbleSort);
}
function _testNoArray() {
"use strict";
var array = 124;
_runTestSortArray(array, bubbleSort);
}
function _runTestSortArray(arr, algorithm) {
"use strict";
var copy = [], i = 0;
for (i = 0; i < arr.length; i += 1) {
copy[i] = arr[i];
}
copy.sort();
algorithm(arr);
if (copy.length !== arr.length) {
throw "Your algorithm dont work!";
}
for (i = 0; i < copy.length; i += 1) {
if (copy[i] !== arr[i]) {
throw "Your algorithm dont work!";
}
}
}
}
10 changes: 10 additions & 0 deletions Task1/runMe.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<html>
<head>
<script src="mysort.js" type="text/javascript"></script>

</head>
<body onload="runTestsSort();">

</body>

</html>