Skip to content
Open
Changes from all commits
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
132 changes: 83 additions & 49 deletions lego.js
Original file line number Diff line number Diff line change
@@ -1,70 +1,104 @@
'use strict';

/**
* Сделано задание на звездочку
* Реализованы методы or и and
*/
exports.isStar = true;

/**
* Запрос к коллекции
* @param {Array} collection
* @params {...Function} – Функции для запроса
* @returns {Array}
*/
exports.isStar = false;

// Чем больше число тем ниже приоритет функции
var priority = {
Copy link
Member

Choose a reason for hiding this comment

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

Стоит написать комментарий, что значат эти цифры – больше число выполнится "быстрее" или в последнюю очередь

filterIn: 1,
sortBy: 2,
select: 3,
limit: 4,
format: 5
};

exports.query = function (collection) {
return collection;
var newCollection = copyCollection(collection);
var functions = Array.prototype.slice.call(arguments).slice(1);
function compare(one, another) {

Choose a reason for hiding this comment

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

Эту функцию можно сильно сократить, возвращая, например, x - y

return priority[one.name] - priority[another.name];
}
Copy link
Member

Choose a reason for hiding this comment

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

Зачем поудаляла все jsdoc?

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.

Их же можно сворачивать в IDE :) В данном случае, да маленький, но стоит привыкать с ним работать. Писать *doc – хороший тон.

functions.sort(compare);
Copy link
Member

Choose a reason for hiding this comment

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

Не старайся усложнять там, где всё можно сделать проще. Когда функция сортировки достаточно простая, не стоит выносить её в отдельную функцию. К тому же её можно написать сильно короче и проще:

functions.sort(function (a, b) {
    return priority[a.name] - priority[b.name];
});

functions.forEach(function (eachQuery) {
newCollection = eachQuery(newCollection);
});

return newCollection;
};

/**
* Выбор полей
* @params {...String}
*/
function copyCollection(collection) {

return (collection.map(function (friend) {

return Object.assign({}, friend);
}));
}

exports.select = function () {
return;
};
var fields = Array.prototype.slice.call(arguments);

/**
* Фильтрация поля по массиву значений
* @param {String} property – Свойство для фильтрации
* @param {Array} values – Доступные значения
*/
exports.filterIn = function (property, values) {
console.info(property, values);
return function select(collection) {

return;
return collection.reduce(function (prev, curr) {
var friend = {};
for (var field in curr) {
if (fields.indexOf(field) !== -1) {
friend[field] = curr[field];
}
}
prev.push(friend);

return prev;
}, []);

};
};

/**
* Сортировка коллекции по полю
* @param {String} property – Свойство для фильтрации
* @param {String} order – Порядок сортировки (asc - по возрастанию; desc – по убыванию)
*/
exports.sortBy = function (property, order) {
console.info(property, order);
return function sortBy(collection) {

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.

Ульяна, у тебя есть идеи как оптимизировать эту функцию?

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.

👍
Супер! Спасибо

function compare(one, another) {
return (one[property] > another[property]) ? 1 : -1;
}

return;
if (order === 'asc') {
collection.sort(compare);
Copy link
Member

Choose a reason for hiding this comment

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

Метод sort – не чистая функция. Только что ты мутировала коллекцию. Требования задания не учтены.

} else {
collection.sort(compare).reverse();
}

return collection;
};
};

/**
* Форматирование поля
* @param {String} property – Свойство для фильтрации
* @param {Function} formatter – Функция для форматирования
*/
exports.format = function (property, formatter) {
console.info(property, formatter);
exports.limit = function (count) {
return function limit(collection) {
return collection.slice(0, count);
};
};

return;
exports.filterIn = function (property, values) {
return function filterIn(collection) {

Choose a reason for hiding this comment

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

попробуй метод filter

var newSorted = [];
collection.forEach(function (friend) {
for (var field in friend) {
if (property === field.toString() &&
values.indexOf(friend[field]) !== -1) {
newSorted.push(Object.assign({}, friend));
}
}
});

return newSorted;
};
};

/**
* Ограничение количества элементов в коллекции
* @param {Number} count – Максимальное количество элементов
*/
exports.limit = function (count) {
console.info(count);
exports.format = function (property, formatter) {
return function format(collection) {
return collection.map(function (friend) {
friend[property] = formatter(friend[property]);

return;
return friend;
});
};
};

if (exports.isStar) {
Expand Down