vulpes
Version:
Job management framework
94 lines (84 loc) • 2.85 kB
JavaScript
;
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var multisort = require("multisort");
/**
* Job sorting step configuration
* @typedef {Object} JobSortingStep
* @property {String} property - The job property to sort by
* @property {String} direction - The direction to sort in (desc/asc)
*/
var SORT_STEPS_DEFAULT = [{
property: "created",
direction: "desc"
}];
var SORT_MAP = {
created: {
asc: "created",
desc: "!created"
},
priority: {
asc: "priority",
desc: "!priority"
},
status: {
asc: "status",
desc: "!status"
},
type: {
asc: "type",
desc: "!type"
}
};
function filterDuplicateJobs(jobs) {
return jobs.filter(function (job, index, original) {
var jobIndex = original.findIndex(function (searchJob) {
return job.id === searchJob.id;
});
return jobIndex === index;
});
}
/**
* Sort jobs by some criteria
* @param {Array.<Job>} jobs The jobs to sort
* @param {JobSortingStep=} sortSteps Sorting criteia for sorting the jobs
* @example
* // Sort jobs by priority:
* sortJobs(
* [{ id: "some job" }],
* [
* { property: "priority", direction: "desc" },
* { property: "created", direction: "asc" }
* ]
* );
* // This sorts the jobs by priority (highest) first, and then by created
* // (oldest) second..
* @returns {Array.<Job>} An array of sorted jobs
*/
function sortJobs(jobs) {
var sortSteps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : SORT_STEPS_DEFAULT;
var sortCriteria = sortSteps.reduce(function (criteria, step) {
var property = step.property,
direction = step.direction;
if (!/^(asc|desc)$/i.test(direction)) {
throw new Error("Failed sorting jobs: Invalid sort direction: " + direction);
} else if (Object.keys(SORT_MAP).includes(property) === false) {
throw new Error("Failed sorting jobs: Invalid sort property: " + property);
}
return [].concat(_toConsumableArray(criteria), [SORT_MAP[property][direction.toLowerCase()]]);
}, []);
return multisort([].concat(_toConsumableArray(jobs)), sortCriteria);
}
/**
* Sort jobs by priority
* @param {Array.<Job>} jobs An array of jobs
* @returns {Array.<Job>} An array of sorted jobs
* @see sortJobs
*/
function sortJobsByPriority(jobs) {
return sortJobs(jobs, [{ property: "priority", direction: "desc" }, { property: "created", direction: "asc" }]);
}
module.exports = {
filterDuplicateJobs: filterDuplicateJobs,
sortJobs: sortJobs,
sortJobsByPriority: sortJobsByPriority
};