Skip to content
Open
Show file tree
Hide file tree
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
15 changes: 15 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
// Используйте IntelliSense, чтобы узнать о возможных атрибутах.
// Наведите указатель мыши, чтобы просмотреть описания существующих атрибутов.
// Для получения дополнительной информации посетите: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [

{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/index.js"
}
]
}
117 changes: 100 additions & 17 deletions lego.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,65 +6,132 @@
*/
exports.isStar = true;


const funcPriority = {
select: 2,
filterIn: 0,
sortBy: 1,
format: 3,
limit: 3,
or: 0,
and: 0
};

/**
* Запрос к коллекции
* @param {Array} collection
* @params {...Function} – Функции для запроса
* @returns {Array}
*/
exports.query = function (collection) {
return collection;
exports.query = function (collection, ...functions) {
let copyArray = collection.map(friend => Object.assign({}, friend));
functions.sort((a, b) => funcPriority[a.name] > funcPriority[b.name]);
for (let func of functions) {
copyArray = func(copyArray);
}

return copyArray;
};

/**
* Выбор полей
* @params {...String}
* @param {...String} fields
* @returns {Function}
*/
exports.select = function () {
return;
exports.select = function (...fields) {
return function select(collection) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Зачем здесь имя функции?

return collection.map(item => {
let selector = {};
for (let field of fields) {
if (item[field]) {
selector[field] = item[field];
}
}

return selector;
});
};
};

/**
* Фильтрация поля по массиву значений
* @param {String} property – Свойство для фильтрации
* @param {Array} values – Доступные значения
* @returns {Function}
*/
exports.filterIn = function (property, values) {
console.info(property, values);
return function filterIn(collection) {
let changedCollection = [];
for (let item of collection) {
let isFound = values.some((findingItems) => {
return item[property] === findingItems;
});
if (isFound) {
changedCollection.push(item);
}
}

return;
return changedCollection;
};
};

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

Choose a reason for hiding this comment

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

var countendValue = Math.sign(a[property] - b[property]);
return countedValue * (order === 'asc' ? 1 : -1);

// if (countedValue === 0) {
// return 0;
// }
// return (order === 'asc') ? Math.sign(countedValue) :
// (-1) * Math.sign(countedValue);
if (a[property] < b[property]) {
return (order === 'asc') ? -1 : 1;
}
if (a[property] > b[property]) {
return (order === 'asc') ? 1 : -1;
}

return;
return 0;
}
);
};
};

/**
* Форматирование поля
* @param {String} property – Свойство для фильтрации
* @param {Function} formatter – Функция для форматирования
* @returns {Function}
*/
exports.format = function (property, formatter) {
console.info(property, formatter);
return function format(collection) {
let copyArray = collection.map(friend => Object.assign({}, friend));
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

DRY, это можно вынести в функцию


return copyArray.map(item => {
if (item[property]) {
item[property] = formatter(item[property]);
}

return;
return item;
});
};
};

/**
* Ограничение количества элементов в коллекции
* @param {Number} count – Максимальное количество элементов
* @returns {Function}
*/
exports.limit = function (count) {
console.info(count);

return;
return function limit(collection) {
return collection.slice(0, count);
};
};

if (exports.isStar) {
Expand All @@ -73,17 +140,33 @@ if (exports.isStar) {
* Фильтрация, объединяющая фильтрующие функции
* @star
* @params {...Function} – Фильтрующие функции
* @returns {Function}
*/
exports.or = function () {
return;
let filters = [].slice.call(arguments);

return function or(collection) {
return collection.filter(friend =>
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Хорошим тоном будет вложенную функцию обернуть в {}, иначе следующая же добавленная строка разрушит волшебство

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Хорошим тоном будет вложенную функцию обернуть в {}, иначе следующая же добавленная строка разрушит волшебство

filters.some(filter =>
filter(collection).indexOf(friend) !== -1
));
};
};

/**
* Фильтрация, пересекающая фильтрующие функции
* @star
* @params {...Function} – Фильтрующие функции
* @returns {Function}
*/
exports.and = function () {
return;
let filters = [].slice.call(arguments);

return function and(collection) {
return collection.filter(
friend => filters.every(filter =>
filter(collection).indexOf(friend) !== -1
));
};
};
}