Update prettier and reformat code

This commit is contained in:
Anton Vakhrushev 2020-10-10 10:21:30 +03:00
parent ecaa98b69c
commit 60078e94b2
39 changed files with 149 additions and 146 deletions

15
package-lock.json generated
View File

@ -410,6 +410,15 @@
"prettier": "^1.18.2", "prettier": "^1.18.2",
"source-map": "~0.6.1", "source-map": "~0.6.1",
"vue-template-es2015-compiler": "^1.9.0" "vue-template-es2015-compiler": "^1.9.0"
},
"dependencies": {
"prettier": {
"version": "1.19.1",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-1.19.1.tgz",
"integrity": "sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew==",
"dev": true,
"optional": true
}
} }
}, },
"@webassemblyjs/ast": { "@webassemblyjs/ast": {
@ -4107,9 +4116,9 @@
"dev": true "dev": true
}, },
"prettier": { "prettier": {
"version": "1.19.1", "version": "2.1.2",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-1.19.1.tgz", "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.1.2.tgz",
"integrity": "sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew==", "integrity": "sha512-16c7K+x4qVlJg9rEbXl7HEGmQyZlG4R9AgP+oHKRMsMsuk8s+ATStlf1NpDqyBI1HpVyfjLOeMhH2LvuNvV5Vg==",
"dev": true "dev": true
}, },
"process": { "process": {

View File

@ -35,7 +35,7 @@
"mocha": "^7.2.0", "mocha": "^7.2.0",
"mocha-junit-reporter": "^1.23.3", "mocha-junit-reporter": "^1.23.3",
"nyc": "^15.1.0", "nyc": "^15.1.0",
"prettier": "^1.19.1", "prettier": "^2.1.2",
"raw-loader": "^4.0.2", "raw-loader": "^4.0.2",
"sass": "^1.27.0", "sass": "^1.27.0",
"sass-loader": "^8.0.2", "sass-loader": "^8.0.2",

View File

@ -113,12 +113,12 @@ export class ControlPanel {
this.villageFactory this.villageFactory
.createTaskCollection(villageId) .createTaskCollection(villageId)
.getTasks() .getTasks()
.filter(t => t.name === UpgradeBuildingTask.name) .filter((t) => t.name === UpgradeBuildingTask.name)
.map(t => t.args.buildId || 0); .map((t) => t.args.buildId || 0);
if (p.pathname === '/dorf1.php') { if (p.pathname === '/dorf1.php') {
showResourceSlotIds(getBuildingsInQueue()); showResourceSlotIds(getBuildingsInQueue());
onResourceSlotCtrlClick(buildId => { onResourceSlotCtrlClick((buildId) => {
this.onSlotCtrlClick(villageId, buildId); this.onSlotCtrlClick(villageId, buildId);
showResourceSlotIds(getBuildingsInQueue()); showResourceSlotIds(getBuildingsInQueue());
}); });
@ -126,7 +126,7 @@ export class ControlPanel {
if (p.pathname === '/dorf2.php') { if (p.pathname === '/dorf2.php') {
showBuildingSlotIds(getBuildingsInQueue()); showBuildingSlotIds(getBuildingsInQueue());
onBuildingSlotCtrlClick(buildId => { onBuildingSlotCtrlClick((buildId) => {
this.onSlotCtrlClick(villageId, buildId); this.onSlotCtrlClick(villageId, buildId);
showBuildingSlotIds(getBuildingsInQueue()); showBuildingSlotIds(getBuildingsInQueue());
}); });
@ -151,7 +151,7 @@ export class ControlPanel {
el: `#${appId}`, el: `#${appId}`,
data: gameState, data: gameState,
store: createStore(villageFactory), store: createStore(villageFactory),
render: h => h(DashboardApp), render: (h) => h(DashboardApp),
}); });
} }

View File

@ -36,8 +36,8 @@ export default {
}, },
computed: { computed: {
...mapState({ ...mapState({
isLogsVisible: state => state.views.logs, isLogsVisible: (state) => state.views.logs,
isVillageEditorVisible: state => state.views.villageEditor, isVillageEditorVisible: (state) => state.views.villageEditor,
}), }),
isSecondaryDashboardVisible() { isSecondaryDashboardVisible() {
return this.isLogsVisible || this.isVillageEditorVisible; return this.isLogsVisible || this.isVillageEditorVisible;

View File

@ -43,7 +43,7 @@ export function createStore(villageFactory: VillageFactory) {
}, },
}, },
getters: { getters: {
reverseLogs: state => { reverseLogs: (state) => {
return state.logs.slice().reverse(); return state.logs.slice().reverse();
}, },
}, },

View File

@ -27,7 +27,7 @@ import { mapState } from 'vuex';
export default { export default {
computed: { computed: {
...mapState({ ...mapState({
villageName: state => state.villageSettings.villageName, villageName: (state) => state.villageSettings.villageName,
}), }),
sendResourcesThreshold: { sendResourcesThreshold: {
get() { get() {

View File

@ -44,9 +44,7 @@ export class SendOnAdventureAction extends BaseAction {
private checkConfig(adventure: Adventure, health: number) { private checkConfig(adventure: Adventure, health: number) {
for (let conf of CONFIG) { for (let conf of CONFIG) {
if (adventure.level === conf.level && health >= conf.health) { if (adventure.level === conf.level && health >= conf.health) {
return jQuery(adventure.el) return jQuery(adventure.el).find('td.goTo .gotoAdventure').trigger('click');
.find('td.goTo .gotoAdventure')
.trigger('click');
} }
} }
} }
@ -55,11 +53,7 @@ export class SendOnAdventureAction extends BaseAction {
const adventures: Array<Adventure> = []; const adventures: Array<Adventure> = [];
jQuery('tr[id^=adventure]').each((index, el) => { jQuery('tr[id^=adventure]').each((index, el) => {
const imgClass = const imgClass = jQuery(el).find('.difficulty img').attr('class')?.toString() || '';
jQuery(el)
.find('.difficulty img')
.attr('class')
?.toString() || '';
const level = Number(trimPrefix(imgClass, 'adventureDifficulty')); const level = Number(trimPrefix(imgClass, 'adventureDifficulty'));
if (!isNaN(level)) { if (!isNaN(level)) {
adventures.push({ el, level: level }); adventures.push({ el, level: level });

View File

@ -22,7 +22,7 @@ export class UpgradeResourceToLevelAction extends BaseAction {
const requiredLevel = getNumber(args.level); const requiredLevel = getNumber(args.level);
const notUpgraded = deposits.filter( const notUpgraded = deposits.filter(
dep => !dep.isUnderConstruction && requiredLevel > dep.level (dep) => !dep.isUnderConstruction && requiredLevel > dep.level
); );
if (notUpgraded.length === 0) { if (notUpgraded.length === 0) {
@ -59,7 +59,7 @@ export class UpgradeResourceToLevelAction extends BaseAction {
return ( return (
undefined === undefined ===
tasks.find( tasks.find(
task => (task) =>
task.name === UpgradeBuildingTask.name && task.name === UpgradeBuildingTask.name &&
task.args.villageId === villageId && task.args.villageId === villageId &&
task.args.buildId === dep.buildId task.args.buildId === dep.buildId

View File

@ -12,7 +12,7 @@ export class UpdateResourceContractsTask extends BaseTask {
const villages = this.factory.getAllVillages(); const villages = this.factory.getAllVillages();
const tasks = villages const tasks = villages
.map(v => this.factory.createTaskCollection(v.id).getTasks()) .map((v) => this.factory.createTaskCollection(v.id).getTasks())
.reduce((acc, tasks) => acc.concat(tasks), []); .reduce((acc, tasks) => acc.concat(tasks), []);
const paths = uniqPaths([ const paths = uniqPaths([
@ -20,7 +20,7 @@ export class UpdateResourceContractsTask extends BaseTask {
...this.walkImprovementTask(tasks), ...this.walkImprovementTask(tasks),
]); ]);
return paths.map(p => ({ return paths.map((p) => ({
name: GoToPageAction.name, name: GoToPageAction.name,
args: { path: path(p.name, p.query) }, args: { path: path(p.name, p.query) },
})); }));
@ -28,8 +28,10 @@ export class UpdateResourceContractsTask extends BaseTask {
private walkUpgradeTasks(tasks: ImmutableTaskList): PathList { private walkUpgradeTasks(tasks: ImmutableTaskList): PathList {
return tasks return tasks
.filter(t => t.name === UpgradeBuildingTask.name && t.args.villageId && t.args.buildId) .filter(
.map(t => ({ (t) => t.name === UpgradeBuildingTask.name && t.args.villageId && t.args.buildId
)
.map((t) => ({
name: '/build.php', name: '/build.php',
query: { newdid: t.args.villageId, id: t.args.buildId }, query: { newdid: t.args.villageId, id: t.args.buildId },
})); }));
@ -37,8 +39,10 @@ export class UpdateResourceContractsTask extends BaseTask {
private walkImprovementTask(tasks: ImmutableTaskList): PathList { private walkImprovementTask(tasks: ImmutableTaskList): PathList {
return tasks return tasks
.filter(t => t.name === ForgeImprovementTask.name && t.args.villageId && t.args.buildId) .filter(
.map(t => ({ (t) => t.name === ForgeImprovementTask.name && t.args.villageId && t.args.buildId
)
.map((t) => ({
name: '/build.php', name: '/build.php',
query: { newdid: t.args.villageId, id: t.args.buildId }, query: { newdid: t.args.villageId, id: t.args.buildId },
})); }));

View File

@ -23,7 +23,7 @@ interface TaskMap {
const taskMap: TaskMap = {}; const taskMap: TaskMap = {};
export function registerTask(options: TaskOptions = {}) { export function registerTask(options: TaskOptions = {}) {
return function(ctor: Function) { return function (ctor: Function) {
taskMap[ctor.name] = { taskMap[ctor.name] = {
ctor, ctor,
queue: options.queue, queue: options.queue,
@ -55,7 +55,7 @@ export function createTaskHandler(
/** /**
* List on non intersected task queue predicates. * List on non intersected task queue predicates.
*/ */
const TASK_TYPE_PREDICATES: Array<TaskNamePredicate> = OrderedProductionQueues.map(queue => { const TASK_TYPE_PREDICATES: Array<TaskNamePredicate> = OrderedProductionQueues.map((queue) => {
return (taskName: string) => getProductionQueue(taskName) === queue; return (taskName: string) => getProductionQueue(taskName) === queue;
}); });

View File

@ -1,7 +1,7 @@
import * as URLParse from 'url-parse'; import * as URLParse from 'url-parse';
export async function waitForLoad() { export async function waitForLoad() {
return new Promise(resolve => jQuery(resolve)); return new Promise((resolve) => jQuery(resolve));
} }
export function parseLocation(location?: string | undefined) { export function parseLocation(location?: string | undefined) {

View File

@ -7,7 +7,7 @@ export function elClassId(classes: string | undefined, prefix: string): number |
return undefined; return undefined;
} }
let result: number | undefined = undefined; let result: number | undefined = undefined;
classes.split(/\s/).forEach(part => { classes.split(/\s/).forEach((part) => {
const match = part.match(new RegExp(prefix + '(\\d+)')); const match = part.match(new RegExp(prefix + '(\\d+)'));
if (match) { if (match) {
result = toNumber(match[1]); result = toNumber(match[1]);

View File

@ -1,7 +1,7 @@
import { around, randomInRange } from './Random'; import { around, randomInRange } from './Random';
export function sleep(ms: number) { export function sleep(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms)); return new Promise((resolve) => setTimeout(resolve, ms));
} }
export async function sleepMicro() { export async function sleepMicro() {

View File

@ -26,7 +26,7 @@ export function createBuildButton(
const resElement = $el.find('.resourceWrapper .resource'); const resElement = $el.find('.resourceWrapper .resource');
const resources = grabResourcesFromList(resElement); const resources = grabResourcesFromList(resElement);
$el.append(`<div style="padding: 8px"><a id="${btnId}" href="#">Построить</a></div>`); $el.append(`<div style="padding: 8px"><a id="${btnId}" href="#">Построить</a></div>`);
jQuery(`#${btnId}`).on('click', evt => { jQuery(`#${btnId}`).on('click', (evt) => {
evt.preventDefault(); evt.preventDefault();
onClickHandler(buildTypeId, resources); onClickHandler(buildTypeId, resources);
}); });
@ -50,17 +50,14 @@ export function createUpgradeButton(onClickHandler: (resources: Resources) => vo
const btn = `<div style="padding: 8px"><a id="${id}" href="#">В очередь</a></div>`; const btn = `<div style="padding: 8px"><a id="${id}" href="#">В очередь</a></div>`;
upgradeContainer.append(btn); upgradeContainer.append(btn);
const resources = grabContractResources(); const resources = grabContractResources();
jQuery(`#${id}`).on('click', evt => { jQuery(`#${id}`).on('click', (evt) => {
evt.preventDefault(); evt.preventDefault();
onClickHandler(resources); onClickHandler(resources);
}); });
} }
export function grabResourcesFromList($els: JQuery) { export function grabResourcesFromList($els: JQuery) {
const getText = (n: number) => const getText = (n: number) => jQuery($els.get(n)).find('.value').text();
jQuery($els.get(n))
.find('.value')
.text();
const grab = (n: number) => getNumber(getText(n)); const grab = (n: number) => getNumber(getText(n));
return new Resources(grab(0), grab(1), grab(2), grab(3)); return new Resources(grab(0), grab(1), grab(2), grab(3));
} }

View File

@ -22,7 +22,7 @@ function createResearchButton($researchBlockEl: JQuery, onClickHandler: Research
<a id="${id}" href="#">Исследовать</a> <a id="${id}" href="#">Исследовать</a>
</div>`); </div>`);
jQuery(`#${id}`).on('click', evt => { jQuery(`#${id}`).on('click', (evt) => {
evt.preventDefault(); evt.preventDefault();
onClickHandler(resources, unitId); onClickHandler(resources, unitId);
}); });

View File

@ -45,7 +45,7 @@ function createCelebrationButton(
<a id="${id}" href="#">Праздновать</a> <a id="${id}" href="#">Праздновать</a>
</div>`); </div>`);
jQuery(`#${id}`).on('click', evt => { jQuery(`#${id}`).on('click', (evt) => {
evt.preventDefault(); evt.preventDefault();
onClickHandler(resources, idx); onClickHandler(resources, idx);
}); });

View File

@ -23,7 +23,7 @@ export function createTrainTroopButtons(
); );
const resElement = $el.find('.resourceWrapper .resource'); const resElement = $el.find('.resourceWrapper .resource');
const resources = grabResourcesFromList(resElement); const resources = grabResourcesFromList(resElement);
jQuery(`#${id}`).on('click', evt => { jQuery(`#${id}`).on('click', (evt) => {
evt.preventDefault(); evt.preventDefault();
const input = $el.find(`input[name="t${troopId}"]`); const input = $el.find(`input[name="t${troopId}"]`);
const count = getNumber(input.val()); const count = getNumber(input.val());

View File

@ -46,7 +46,7 @@ export class BuildingPageController {
this.logger.info('BUILD PAGE DETECTED', 'ID', this.attributes.buildId, this.attributes); this.logger.info('BUILD PAGE DETECTED', 'ID', this.attributes.buildId, this.attributes);
if (buildTypeId) { if (buildTypeId) {
createUpgradeButton(res => this.onScheduleUpgradeBuilding(res)); createUpgradeButton((res) => this.onScheduleUpgradeBuilding(res));
} else { } else {
createBuildButton((buildTypeId, res) => this.onScheduleBuildBuilding(buildTypeId, res)); createBuildButton((buildTypeId, res) => this.onScheduleBuildBuilding(buildTypeId, res));
} }
@ -126,7 +126,7 @@ export class BuildingPageController {
private onSendResources(coordinates: Coordinates) { private onSendResources(coordinates: Coordinates) {
const villageId = grabActiveVillageId(); const villageId = grabActiveVillageId();
const targetVillage = grabVillageList().find(v => v.crd.eq(coordinates)); const targetVillage = grabVillageList().find((v) => v.crd.eq(coordinates));
this.scheduler.scheduleTask(SendResourcesTask.name, { this.scheduler.scheduleTask(SendResourcesTask.name, {
villageId: villageId, villageId: villageId,
targetVillageId: targetVillage?.id, targetVillageId: targetVillage?.id,

View File

@ -18,8 +18,8 @@ function slotElements(prefix: string): Array<SlotElement> {
function showSlotIds(prefix: string, buildingIds: Array<number>): void { function showSlotIds(prefix: string, buildingIds: Array<number>): void {
const slots = slotElements(prefix); const slots = slotElements(prefix);
slots.forEach(slot => { slots.forEach((slot) => {
const upCount = buildingIds.filter(id => id === slot.buildId).length; const upCount = buildingIds.filter((id) => id === slot.buildId).length;
const $slotEl = jQuery(slot.el); const $slotEl = jQuery(slot.el);
const $labelEl = $slotEl.find('.labelLayer'); const $labelEl = $slotEl.find('.labelLayer');
const oldLabel = $labelEl.data('oldLabel') || $labelEl.text(); const oldLabel = $labelEl.data('oldLabel') || $labelEl.text();
@ -53,10 +53,10 @@ export function showBuildingSlotIds(buildingIds: number[]): void {
function onSlotCtrlClick(prefix: string, onClickHandler: (buildId: number) => void): void { function onSlotCtrlClick(prefix: string, onClickHandler: (buildId: number) => void): void {
const slots = slotElements(prefix); const slots = slotElements(prefix);
slots.forEach(slot => { slots.forEach((slot) => {
jQuery(slot.el) jQuery(slot.el)
.find('.labelLayer') .find('.labelLayer')
.on('click', evt => { .on('click', (evt) => {
if (evt.ctrlKey) { if (evt.ctrlKey) {
evt.preventDefault(); evt.preventDefault();
evt.stopPropagation(); evt.stopPropagation();

View File

@ -47,7 +47,7 @@ export class ActionQueue {
const items = serialized as Array<{ [key: string]: any }>; const items = serialized as Array<{ [key: string]: any }>;
return items.map(i => { return items.map((i) => {
const command = { name: '', args: {} }; const command = { name: '', args: {} };
return Object.assign(command, i); return Object.assign(command, i);
}); });

View File

@ -24,7 +24,7 @@ export class DataStorageTaskProvider implements TaskProvider {
const storedItems = serialized as Array<{ [key: string]: any }>; const storedItems = serialized as Array<{ [key: string]: any }>;
return storedItems.map(i => { return storedItems.map((i) => {
const task = new Task(uniqTaskId(), 0, '', {}); const task = new Task(uniqTaskId(), 0, '', {});
return Object.assign(task, i); return Object.assign(task, i);
}); });

View File

@ -19,7 +19,7 @@ export class TaskQueue {
} }
get(ts: number): Task | undefined { get(ts: number): Task | undefined {
const readyItems = this.getItems().filter(t => t.ts <= ts); const readyItems = this.getItems().filter((t) => t.ts <= ts);
if (readyItems.length === 0) { if (readyItems.length === 0) {
return undefined; return undefined;
} }
@ -27,7 +27,7 @@ export class TaskQueue {
} }
findById(taskId: TaskId): Task | undefined { findById(taskId: TaskId): Task | undefined {
const [matched, _] = this.split(t => t.id === taskId); const [matched, _] = this.split((t) => t.id === taskId);
return matched.shift(); return matched.shift();
} }
@ -58,7 +58,7 @@ export class TaskQueue {
private split(predicate: (t: Task) => boolean): [TaskList, TaskList] { private split(predicate: (t: Task) => boolean): [TaskList, TaskList] {
const matched: TaskList = []; const matched: TaskList = [];
const other: TaskList = []; const other: TaskList = [];
this.getItems().forEach(t => { this.getItems().forEach((t) => {
if (predicate(t)) { if (predicate(t)) {
matched.push(t); matched.push(t);
} else { } else {

View File

@ -141,10 +141,10 @@ export class Scheduler {
let alreadyHasTask; let alreadyHasTask;
if (args.villageId) { if (args.villageId) {
alreadyHasTask = this.taskQueue.has( alreadyHasTask = this.taskQueue.has(
t => t.name === name && t.args.villageId === args.villageId (t) => t.name === name && t.args.villageId === args.villageId
); );
} else { } else {
alreadyHasTask = this.taskQueue.has(t => t.name === name); alreadyHasTask = this.taskQueue.has((t) => t.name === name);
} }
if (!alreadyHasTask) { if (!alreadyHasTask) {
@ -153,7 +153,7 @@ export class Scheduler {
} }
removeTask(taskId: TaskId) { removeTask(taskId: TaskId) {
this.taskQueue.remove(t => t.id === taskId); this.taskQueue.remove((t) => t.id === taskId);
this.actionQueue.clear(); this.actionQueue.clear();
} }
@ -168,7 +168,7 @@ export class Scheduler {
} }
postponeTask(taskId: TaskId, seconds: number) { postponeTask(taskId: TaskId, seconds: number) {
const task = this.taskQueue.seeItems().find(t => t.id === taskId); const task = this.taskQueue.seeItems().find((t) => t.id === taskId);
if (!task) { if (!task) {
return; return;
} }
@ -179,7 +179,7 @@ export class Scheduler {
this.removeTask(taskId); this.removeTask(taskId);
} else { } else {
const modifyTime = withTime(timestamp() + seconds); const modifyTime = withTime(timestamp() + seconds);
this.taskQueue.modify(t => t.id === taskId, modifyTime); this.taskQueue.modify((t) => t.id === taskId, modifyTime);
} }
} }

View File

@ -42,10 +42,7 @@ export class Statistics {
private getTopStatKeys(stat: ActionStatistics) { private getTopStatKeys(stat: ActionStatistics) {
const keys = Object.keys(stat); const keys = Object.keys(stat);
return keys return keys.sort().reverse().slice(0, KEEP_RECORD_COUNT);
.sort()
.reverse()
.slice(0, KEEP_RECORD_COUNT);
} }
getActionStatistics(): ActionStatistics { getActionStatistics(): ActionStatistics {

View File

@ -6,7 +6,7 @@ const NAMESPACE = 'travian:v1';
const storage = localStorage; const storage = localStorage;
function join(...parts: Array<string>) { function join(...parts: Array<string>) {
return parts.map(p => p.replace(/[:]+$/g, '').replace(/^[:]+/g, '')).join(':'); return parts.map((p) => p.replace(/[:]+$/g, '').replace(/^[:]+/g, '')).join(':');
} }
export class DataStorage { export class DataStorage {

View File

@ -19,7 +19,7 @@ export function createMapper<T>(options: ObjectMapperOptions<T>): ObjectMapper<T
} }
if (factory) { if (factory) {
return plain => { return (plain) => {
let item = factory(); let item = factory();
if (typeof plain === 'object' && typeof item === 'object') { if (typeof plain === 'object' && typeof item === 'object') {
return Object.assign(item, plain) as T; return Object.assign(item, plain) as T;

View File

@ -74,7 +74,7 @@ export class VillageStorage {
storeIncomingMerchants(merchants: ReadonlyArray<IncomingMerchant>): void { storeIncomingMerchants(merchants: ReadonlyArray<IncomingMerchant>): void {
this.storage.set( this.storage.set(
INCOMING_MERCHANTS_KEY, INCOMING_MERCHANTS_KEY,
merchants.map(m => ({ ...m.resources, ts: m.ts })) merchants.map((m) => ({ ...m.resources, ts: m.ts }))
); );
} }

View File

@ -6,18 +6,16 @@ const ID = uniqId();
export class TaskQueueRenderer { export class TaskQueueRenderer {
render(tasks: ImmutableTaskList) { render(tasks: ImmutableTaskList) {
const ul = jQuery('<ul></ul>') const ul = jQuery('<ul></ul>').attr({ id: ID }).css({
.attr({ id: ID }) 'position': 'absolute',
.css({ 'background-color': 'white',
'position': 'absolute', 'left': 0,
'background-color': 'white', 'top': '40px',
'left': 0, 'color': 'black',
'top': '40px', 'z-index': '9999',
'color': 'black', 'padding': '8px 6px',
'z-index': '9999', });
'padding': '8px 6px', tasks.forEach((task) => {
});
tasks.forEach(task => {
ul.append( ul.append(
jQuery('<li></li>').text(formatDate(task.ts) + ' ' + task.name + ' ' + task.id) jQuery('<li></li>').text(formatDate(task.ts) + ' ' + task.name + ' ' + task.id)
); );

View File

@ -171,19 +171,21 @@ export class VillageController {
const resourceSlots = this.storage.getResourceSlots(); const resourceSlots = this.storage.getResourceSlots();
const tasks = this.taskCollection.getTasks(); const tasks = this.taskCollection.getTasks();
const cropSlots = resourceSlots.filter(s => s.type === ResourceType.Crop && !s.isMaxLevel); const cropSlots = resourceSlots.filter(
(s) => s.type === ResourceType.Crop && !s.isMaxLevel
);
if (cropSlots.length === 0) { if (cropSlots.length === 0) {
return; return;
} }
// Check, if crop field is building now // Check, if crop field is building now
const underContraction = cropSlots.find(s => s.isUnderConstruction); const underContraction = cropSlots.find((s) => s.isUnderConstruction);
if (underContraction !== undefined) { if (underContraction !== undefined) {
return; return;
} }
// Check, if we already have crop task in queue // Check, if we already have crop task in queue
const cropBuildIds = cropSlots.map(s => s.buildId); const cropBuildIds = cropSlots.map((s) => s.buildId);
for (let buildId of cropBuildIds) { for (let buildId of cropBuildIds) {
const upgradeTask = tasks.find( const upgradeTask = tasks.find(
isBuildingPlanned(UpgradeBuildingTask.name, buildId, undefined) isBuildingPlanned(UpgradeBuildingTask.name, buildId, undefined)
@ -207,11 +209,11 @@ export class VillageController {
} }
private planWarehouseBuilding(): void { private planWarehouseBuilding(): void {
this.planStorageBuilding(WAREHOUSE_ID, t => !t.isEnoughWarehouseCapacity); this.planStorageBuilding(WAREHOUSE_ID, (t) => !t.isEnoughWarehouseCapacity);
} }
private planGranaryBuilding(): void { private planGranaryBuilding(): void {
this.planStorageBuilding(GARNER_ID, t => !t.isEnoughGranaryCapacity); this.planStorageBuilding(GARNER_ID, (t) => !t.isEnoughGranaryCapacity);
} }
private planStorageBuilding( private planStorageBuilding(
@ -221,14 +223,14 @@ export class VillageController {
const buildingSlots = this.storage.getBuildingSlots(); const buildingSlots = this.storage.getBuildingSlots();
const storageSlots = buildingSlots.filter( const storageSlots = buildingSlots.filter(
s => s.buildTypeId === buildTypeId && !s.isMaxLevel (s) => s.buildTypeId === buildTypeId && !s.isMaxLevel
); );
if (storageSlots.length === 0) { if (storageSlots.length === 0) {
return; return;
} }
// Check, if storage is building now // Check, if storage is building now
const underConstruction = storageSlots.find(s => s.isUnderConstruction); const underConstruction = storageSlots.find((s) => s.isUnderConstruction);
if (underConstruction !== undefined) { if (underConstruction !== undefined) {
return; return;
} }
@ -236,7 +238,7 @@ export class VillageController {
const tasks = this.state.tasks; const tasks = this.state.tasks;
// Check, if we have storage is in building queue // Check, if we have storage is in building queue
const storageBuildIds = storageSlots.map(s => s.buildId); const storageBuildIds = storageSlots.map((s) => s.buildId);
for (let buildId of storageBuildIds) { for (let buildId of storageBuildIds) {
const upgradeTask = tasks.find( const upgradeTask = tasks.find(
isBuildingPlanned(UpgradeBuildingTask.name, buildId, buildTypeId) isBuildingPlanned(UpgradeBuildingTask.name, buildId, buildTypeId)

View File

@ -13,7 +13,7 @@ export class VillageRepository implements VillageRepositoryInterface {
} }
get(villageId: number): Village { get(villageId: number): Village {
const village = this.all().find(vlg => vlg.id === villageId); const village = this.all().find((vlg) => vlg.id === villageId);
if (!village) { if (!village) {
throw new VillageNotFound('Active village not found'); throw new VillageNotFound('Active village not found');
} }
@ -21,7 +21,7 @@ export class VillageRepository implements VillageRepositoryInterface {
} }
getByCrd(crd: Coordinates): Village { getByCrd(crd: Coordinates): Village {
const village = this.all().find(vlg => vlg.crd.eq(crd)); const village = this.all().find((vlg) => vlg.crd.eq(crd));
if (!village) { if (!village) {
throw new VillageNotFound('Village not found'); throw new VillageNotFound('Village not found');
} }
@ -29,7 +29,7 @@ export class VillageRepository implements VillageRepositoryInterface {
} }
getActive(): Village { getActive(): Village {
const village = this.all().find(vlg => vlg.active); const village = this.all().find((vlg) => vlg.active);
if (!village) { if (!village) {
throw new VillageNotFound('Active village not found'); throw new VillageNotFound('Active village not found');
} }

View File

@ -220,7 +220,7 @@ function createTaskQueueStates(
storage: VillageStorage storage: VillageStorage
) { ) {
let result: Array<VillageProductionQueueState> = []; let result: Array<VillageProductionQueueState> = [];
const possibleTasks = tasks.filter(task => task.canBeBuilt); const possibleTasks = tasks.filter((task) => task.canBeBuilt);
for (let taskQueueInfo of getGroupedByQueueTasks(possibleTasks, storage)) { for (let taskQueueInfo of getGroupedByQueueTasks(possibleTasks, storage)) {
result.push(createProductionQueueState(taskQueueInfo, warehouse)); result.push(createProductionQueueState(taskQueueInfo, warehouse));
} }
@ -230,12 +230,14 @@ function createTaskQueueStates(
function getReadyForProductionTask( function getReadyForProductionTask(
queues: ReadonlyArray<VillageProductionQueueState> queues: ReadonlyArray<VillageProductionQueueState>
): TaskState | undefined { ): TaskState | undefined {
const firstReadyQueue = queues.find(queue => queue.isWaiting); const firstReadyQueue = queues.find((queue) => queue.isWaiting);
if (!firstReadyQueue) { if (!firstReadyQueue) {
return undefined; return undefined;
} }
return firstReadyQueue.tasks.find(task => task.name === TrainTroopTask.name || task.canBeBuilt); return firstReadyQueue.tasks.find(
(task) => task.name === TrainTroopTask.name || task.canBeBuilt
);
} }
function getTaskResources(task: TaskCore | undefined): Resources { function getTaskResources(task: TaskCore | undefined): Resources {
@ -284,7 +286,7 @@ function createVillageOwnState(
const storageState = makeStorageState(resources, storageResources, performance); const storageState = makeStorageState(resources, storageResources, performance);
const tasks = taskCollection const tasks = taskCollection
.getTasks() .getTasks()
.map(t => makeTaskState(t, storageState.optimumFullness)); .map((t) => makeTaskState(t, storageState.optimumFullness));
const queues = createTaskQueueStates(storageState, tasks, storage); const queues = createTaskQueueStates(storageState, tasks, storage);
const firstReadyTask = getReadyForProductionTask(queues); const firstReadyTask = getReadyForProductionTask(queues);
const requiredResources = getTaskResources(firstReadyTask); const requiredResources = getTaskResources(firstReadyTask);
@ -323,7 +325,7 @@ function createVillageState(
state: VillageOwnState, state: VillageOwnState,
ownStates: VillageOwnStateDictionary ownStates: VillageOwnStateDictionary
): VillageState { ): VillageState {
const villageIds = Object.keys(ownStates).map(k => +k); const villageIds = Object.keys(ownStates).map((k) => +k);
const commitments = villageIds.reduce((memo, shipmentVillageId) => { const commitments = villageIds.reduce((memo, shipmentVillageId) => {
const shipmentVillageState = ownStates[shipmentVillageId]; const shipmentVillageState = ownStates[shipmentVillageId];
const shipmentVillageRequired = shipmentVillageState.required; const shipmentVillageRequired = shipmentVillageState.required;
@ -342,7 +344,7 @@ function getVillageStates(
taskCollectionFactory: VillageTaskCollectionFactory taskCollectionFactory: VillageTaskCollectionFactory
): Array<VillageState> { ): Array<VillageState> {
const ownStates = createVillageOwnStates(villages, storageFactory, taskCollectionFactory); const ownStates = createVillageOwnStates(villages, storageFactory, taskCollectionFactory);
return villages.map(village => createVillageState(ownStates[village.id], ownStates)); return villages.map((village) => createVillageState(ownStates[village.id], ownStates));
} }
interface VillageStorageFactory { interface VillageStorageFactory {
@ -382,7 +384,7 @@ export class VillageStateFactory {
this.storageFactory, this.storageFactory,
this.taskCollectionFactory this.taskCollectionFactory
); );
const needle = states.find(s => s.id === villageId); const needle = states.find((s) => s.id === villageId);
if (!needle) { if (!needle) {
throw new VillageNotFound(`Village ${villageId} not found`); throw new VillageNotFound(`Village ${villageId} not found`);
} }

View File

@ -24,13 +24,13 @@ export class VillageTaskCollection {
private modifyTasks(predicate: (t: Task) => boolean, modifier: (t: Task) => Task): void { private modifyTasks(predicate: (t: Task) => boolean, modifier: (t: Task) => Task): void {
const tasks = this.getTasks(); const tasks = this.getTasks();
const modified = tasks.map(t => (predicate(t) ? modifier(t) : t)); const modified = tasks.map((t) => (predicate(t) ? modifier(t) : t));
this.storage.storeTaskList(modified); this.storage.storeTaskList(modified);
} }
private removeTasks(predicate: (t: Task) => boolean): void { private removeTasks(predicate: (t: Task) => boolean): void {
const tasks = this.getTasks(); const tasks = this.getTasks();
const remaining = tasks.filter(t => !predicate(t)); const remaining = tasks.filter((t) => !predicate(t));
this.storage.storeTaskList(remaining); this.storage.storeTaskList(remaining);
} }
@ -55,12 +55,12 @@ export class VillageTaskCollection {
} }
removeTask(taskId: TaskId) { removeTask(taskId: TaskId) {
this.removeTasks(t => t.id === taskId); this.removeTasks((t) => t.id === taskId);
} }
upTask(taskId: TaskId): void { upTask(taskId: TaskId): void {
const tasks = this.storage.getTasks(); const tasks = this.storage.getTasks();
const index = tasks.findIndex(t => t.id === taskId); const index = tasks.findIndex((t) => t.id === taskId);
if (index < 0 || index === 0) { if (index < 0 || index === 0) {
return; return;
} }
@ -71,7 +71,7 @@ export class VillageTaskCollection {
downTask(taskId: TaskId) { downTask(taskId: TaskId) {
const tasks = this.storage.getTasks(); const tasks = this.storage.getTasks();
const index = tasks.findIndex(t => t.id === taskId); const index = tasks.findIndex((t) => t.id === taskId);
if (index < 0 || index === tasks.length - 1) { if (index < 0 || index === tasks.length - 1) {
return; return;
} }
@ -82,7 +82,7 @@ export class VillageTaskCollection {
postponeTask(taskId: TaskId, seconds: number) { postponeTask(taskId: TaskId, seconds: number) {
const modifyTime = withTime(timestamp() + seconds); const modifyTime = withTime(timestamp() + seconds);
this.modifyTasks(task => task.id === taskId, modifyTime); this.modifyTasks((task) => task.id === taskId, modifyTime);
} }
updateResourcesInTasks(resources: Resources, attr: ContractAttributes): void { updateResourcesInTasks(resources: Resources, attr: ContractAttributes): void {

View File

@ -4,23 +4,23 @@ import { expect } from 'chai';
import { Resources } from '../../src/Core/Resources'; import { Resources } from '../../src/Core/Resources';
import { calcGatheringTimings, GatheringTimings } from '../../src/Core/GatheringTimings'; import { calcGatheringTimings, GatheringTimings } from '../../src/Core/GatheringTimings';
describe('Gathering timings', function() { describe('Gathering timings', function () {
it('Can calc common from numbers', function() { it('Can calc common from numbers', function () {
const timings = GatheringTimings.create(10, 20, 15, 5); const timings = GatheringTimings.create(10, 20, 15, 5);
expect(20).to.equals(timings.slowest.seconds); expect(20).to.equals(timings.slowest.seconds);
}); });
it('Can calc common with never', function() { it('Can calc common with never', function () {
const timings = GatheringTimings.create(10, 20, 'never', 5); const timings = GatheringTimings.create(10, 20, 'never', 5);
expect(true).to.equals(timings.slowest.never); expect(true).to.equals(timings.slowest.never);
}); });
it('Can calc common with all never', function() { it('Can calc common with all never', function () {
const timings = GatheringTimings.create('never', 'never', 'never', 'never'); const timings = GatheringTimings.create('never', 'never', 'never', 'never');
expect(true).to.equals(timings.slowest.never); expect(true).to.equals(timings.slowest.never);
}); });
it('Can calc timings', function() { it('Can calc timings', function () {
const resources = new Resources(10, 10, 10, 10); const resources = new Resources(10, 10, 10, 10);
const desired = new Resources(60, 60, 60, 60); const desired = new Resources(60, 60, 60, 60);
const speed = new Resources(5, 5, 5, 5); const speed = new Resources(5, 5, 5, 5);
@ -28,7 +28,7 @@ describe('Gathering timings', function() {
expect(10 * 3600).to.equals(timings.slowest.seconds); expect(10 * 3600).to.equals(timings.slowest.seconds);
}); });
it('Can calc timings with different speed', function() { it('Can calc timings with different speed', function () {
const resources = new Resources(10, 10, 10, 10); const resources = new Resources(10, 10, 10, 10);
const desired = new Resources(60, 60, 60, 60); const desired = new Resources(60, 60, 60, 60);
const speed = new Resources(5, 10, 25, 5); const speed = new Resources(5, 10, 25, 5);
@ -40,7 +40,7 @@ describe('Gathering timings', function() {
expect(10 * 3600).to.equals(timings.slowest.seconds); expect(10 * 3600).to.equals(timings.slowest.seconds);
}); });
it('Can calc timings with negative speed', function() { it('Can calc timings with negative speed', function () {
const resources = new Resources(10, 10, 10, 10); const resources = new Resources(10, 10, 10, 10);
const desired = new Resources(60, 60, 60, 60); const desired = new Resources(60, 60, 60, 60);
const speed = new Resources(5, 10, 25, -5); const speed = new Resources(5, 10, 25, -5);

View File

@ -5,14 +5,14 @@ import { calcHeroResource } from '../../src/Core/HeroBalance';
import { Resources } from '../../src/Core/Resources'; import { Resources } from '../../src/Core/Resources';
import { ResourceType } from '../../src/Core/ResourceType'; import { ResourceType } from '../../src/Core/ResourceType';
describe('HeroBalance', function() { describe('HeroBalance', function () {
it('Get resource for single requirement', function() { it('Get resource for single requirement', function () {
const req = new Resources(0, 0, -100, 0); const req = new Resources(0, 0, -100, 0);
const heroRes = calcHeroResource([req]); const heroRes = calcHeroResource([req]);
expect(heroRes).to.equals(ResourceType.Iron); expect(heroRes).to.equals(ResourceType.Iron);
}); });
it('Get resource for second requirement', function() { it('Get resource for second requirement', function () {
const req1 = new Resources(0, 0, 100, 0); const req1 = new Resources(0, 0, 100, 0);
const req2 = new Resources(0, -200, 20, 0); const req2 = new Resources(0, -200, 20, 0);
const heroRes = calcHeroResource([req1, req2]); const heroRes = calcHeroResource([req1, req2]);

View File

@ -3,45 +3,45 @@ import { expect } from 'chai';
import { Resources } from '../../src/Core/Resources'; import { Resources } from '../../src/Core/Resources';
describe('Resources', function() { describe('Resources', function () {
it('Can compare with lt', function() { it('Can compare with lt', function () {
const x = new Resources(0, 0, 0, 0); const x = new Resources(0, 0, 0, 0);
const y = new Resources(5, 5, 5, 5); const y = new Resources(5, 5, 5, 5);
expect(x.anyLower(y)).is.true; expect(x.anyLower(y)).is.true;
}); });
it('Can compare with lt (mixed)', function() { it('Can compare with lt (mixed)', function () {
const x = new Resources(20, 20, 5, 20); const x = new Resources(20, 20, 5, 20);
const y = new Resources(10, 10, 10, 10); const y = new Resources(10, 10, 10, 10);
expect(x.anyLower(y)).is.true; expect(x.anyLower(y)).is.true;
}); });
it('Can compare with gt', function() { it('Can compare with gt', function () {
const x = new Resources(5, 5, 5, 5); const x = new Resources(5, 5, 5, 5);
const y = new Resources(0, 0, 0, 0); const y = new Resources(0, 0, 0, 0);
expect(x.allGreater(y)).is.true; expect(x.allGreater(y)).is.true;
}); });
it('Can compare with gt (mixed)', function() { it('Can compare with gt (mixed)', function () {
const x = new Resources(30, 30, 10, 30); const x = new Resources(30, 30, 10, 30);
const y = new Resources(20, 20, 20, 20); const y = new Resources(20, 20, 20, 20);
expect(x.allGreater(y)).is.false; expect(x.allGreater(y)).is.false;
}); });
it('Can up to 1', function() { it('Can up to 1', function () {
const resources = new Resources(0, 4, 10, 18); const resources = new Resources(0, 4, 10, 18);
const upped = resources.upTo(1); const upped = resources.upTo(1);
expect(upped.eq(resources)).is.true; expect(upped.eq(resources)).is.true;
}); });
it('Can up to 10', function() { it('Can up to 10', function () {
const resources = new Resources(0, 4, 10, 18); const resources = new Resources(0, 4, 10, 18);
const expected = new Resources(0, 10, 10, 20); const expected = new Resources(0, 10, 10, 20);
const upped = resources.upTo(10); const upped = resources.upTo(10);
expect(upped.eq(expected)).is.true; expect(upped.eq(expected)).is.true;
}); });
it('Can down to 10', function() { it('Can down to 10', function () {
const resources = new Resources(0, 4, 10, 18); const resources = new Resources(0, 4, 10, 18);
const expected = new Resources(0, 0, 10, 10); const expected = new Resources(0, 0, 10, 10);
const lowed = resources.downTo(10); const lowed = resources.downTo(10);

View File

@ -2,36 +2,36 @@ import { it, describe } from 'mocha';
import { expect } from 'chai'; import { expect } from 'chai';
import { elClassId, getNumber } from '../../src/Helpers/Convert'; import { elClassId, getNumber } from '../../src/Helpers/Convert';
describe('Utils', function() { describe('Utils', function () {
describe('getNumber', function() { describe('getNumber', function () {
it('Can parse positive number', function() { it('Can parse positive number', function () {
const text = '123'; const text = '123';
expect(getNumber(text)).to.be.equals(123); expect(getNumber(text)).to.be.equals(123);
}); });
it('Can parse positive number with noise', function() { it('Can parse positive number with noise', function () {
const text = ' 123 '; const text = ' 123 ';
expect(getNumber(text)).to.be.equals(123); expect(getNumber(text)).to.be.equals(123);
}); });
it('Can parse negative number', function() { it('Can parse negative number', function () {
const text = '-146'; const text = '-146';
expect(getNumber(text)).to.be.equals(-146); expect(getNumber(text)).to.be.equals(-146);
}); });
it('Can parse negative number with minus sign', function() { it('Can parse negative number with minus sign', function () {
const text = '\u2212132'; const text = '\u2212132';
expect(getNumber(text)).to.be.equals(-132); expect(getNumber(text)).to.be.equals(-132);
}); });
}); });
describe('elClassId', function() { describe('elClassId', function () {
it('Can parse number with prefix', function() { it('Can parse number with prefix', function () {
const text = 'foo bar12 baz'; const text = 'foo bar12 baz';
expect(elClassId(text, 'bar')).to.be.equals(12); expect(elClassId(text, 'bar')).to.be.equals(12);
}); });
it('Can parse number from parts with same prefix', function() { it('Can parse number from parts with same prefix', function () {
const text = 'foo12 foobar'; const text = 'foo12 foobar';
expect(elClassId(text, 'foo')).to.be.equals(12); expect(elClassId(text, 'foo')).to.be.equals(12);
}); });

View File

@ -2,28 +2,28 @@ import { it, describe } from 'mocha';
import { expect } from 'chai'; import { expect } from 'chai';
import { path, uniqPaths } from '../../src/Helpers/Path'; import { path, uniqPaths } from '../../src/Helpers/Path';
describe('Path', function() { describe('Path', function () {
it('Can build path with empty query', function() { it('Can build path with empty query', function () {
const p = path('/info.php'); const p = path('/info.php');
expect(p).to.be.equals('/info.php'); expect(p).to.be.equals('/info.php');
}); });
it('Can build path with query', function() { it('Can build path with query', function () {
const p = path('/info.php', { foo: 'bar' }); const p = path('/info.php', { foo: 'bar' });
expect(p).to.be.equals('/info.php?foo=bar'); expect(p).to.be.equals('/info.php?foo=bar');
}); });
it('Can build path with complex query', function() { it('Can build path with complex query', function () {
const p = path('/info.php', { a: 'x', b: 'y', c: 5 }); const p = path('/info.php', { a: 'x', b: 'y', c: 5 });
expect(p).to.be.equals('/info.php?a=x&b=y&c=5'); expect(p).to.be.equals('/info.php?a=x&b=y&c=5');
}); });
it('Can build path with query (undefined part)', function() { it('Can build path with query (undefined part)', function () {
const p = path('/info.php', { foo: 'bar', foobar: undefined }); const p = path('/info.php', { foo: 'bar', foobar: undefined });
expect(p).to.be.equals('/info.php?foo=bar'); expect(p).to.be.equals('/info.php?foo=bar');
}); });
it('Can keep uniq paths', function() { it('Can keep uniq paths', function () {
const p1 = { name: '/info.php', query: { a: 'b' } }; const p1 = { name: '/info.php', query: { a: 'b' } };
const p2 = { name: '/info.php', query: { a: 'b' } }; const p2 = { name: '/info.php', query: { a: 'b' } };
const up = uniqPaths([p1, p2]); const up = uniqPaths([p1, p2]);

View File

@ -15,15 +15,15 @@ class MemoryStatisticsStorage implements StatisticsStorageInterface {
} }
} }
describe('Statistics', function() { describe('Statistics', function () {
it('Can save statistics item', function() { it('Can save statistics item', function () {
const storage = new MemoryStatisticsStorage(); const storage = new MemoryStatisticsStorage();
const statistics = new Statistics(storage); const statistics = new Statistics(storage);
statistics.incrementAction(1588408294); statistics.incrementAction(1588408294);
expect(Object.keys(statistics.getActionStatistics())).to.has.lengthOf(1); expect(Object.keys(statistics.getActionStatistics())).to.has.lengthOf(1);
}); });
it('Can trim statistics', function() { it('Can trim statistics', function () {
const storage = new MemoryStatisticsStorage(); const storage = new MemoryStatisticsStorage();
const statistics = new Statistics(storage); const statistics = new Statistics(storage);
const baseTime = 1588408294; const baseTime = 1588408294;

View File

@ -6,34 +6,34 @@ import { NullLogger } from '../../src/Logger';
import { ArrayTaskProvider } from '../../src/Queue/TaskProvider/ArrayTaskProvider'; import { ArrayTaskProvider } from '../../src/Queue/TaskProvider/ArrayTaskProvider';
import { Task } from '../../src/Queue/Task'; import { Task } from '../../src/Queue/Task';
describe('Task Queue', function() { describe('Task Queue', function () {
it('Can get task from queue', function() { it('Can get task from queue', function () {
const provider = new ArrayTaskProvider([new Task('1', 0, 'task', {})]); const provider = new ArrayTaskProvider([new Task('1', 0, 'task', {})]);
const queue = new TaskQueue(provider, new NullLogger()); const queue = new TaskQueue(provider, new NullLogger());
const task = queue.get(1); const task = queue.get(1);
expect(task).to.be.instanceOf(Task); expect(task).to.be.instanceOf(Task);
}); });
it("Don't get unready task from queue", function() { it("Don't get unready task from queue", function () {
const provider = new ArrayTaskProvider([new Task('1', 5, 'task', {})]); const provider = new ArrayTaskProvider([new Task('1', 5, 'task', {})]);
const queue = new TaskQueue(provider, new NullLogger()); const queue = new TaskQueue(provider, new NullLogger());
const task = queue.get(1); const task = queue.get(1);
expect(task).to.be.undefined; expect(task).to.be.undefined;
}); });
it('Can remove task by id', function() { it('Can remove task by id', function () {
const provider = new ArrayTaskProvider([ const provider = new ArrayTaskProvider([
new Task('id1', 1, 'task1', {}), new Task('id1', 1, 'task1', {}),
new Task('id2', 2, 'task2', {}), new Task('id2', 2, 'task2', {}),
]); ]);
const queue = new TaskQueue(provider, new NullLogger()); const queue = new TaskQueue(provider, new NullLogger());
queue.remove(t => t.id === 'id1'); queue.remove((t) => t.id === 'id1');
const tasks = provider.getTasks(); const tasks = provider.getTasks();
expect(tasks).to.have.lengthOf(1); expect(tasks).to.have.lengthOf(1);
expect(tasks[0].ts).to.be.equals(2); expect(tasks[0].ts).to.be.equals(2);
}); });
it('Can modify tasks', function() { it('Can modify tasks', function () {
const provider = new ArrayTaskProvider([ const provider = new ArrayTaskProvider([
new Task('1', 1, 'task1', {}), new Task('1', 1, 'task1', {}),
new Task('2', 3, 'task2', {}), new Task('2', 3, 'task2', {}),
@ -41,8 +41,8 @@ describe('Task Queue', function() {
]); ]);
const queue = new TaskQueue(provider, new NullLogger()); const queue = new TaskQueue(provider, new NullLogger());
queue.modify( queue.modify(
t => t.ts < 4, (t) => t.ts < 4,
t => new Task(t.id, 10, t.name, t.args) (t) => new Task(t.id, 10, t.name, t.args)
); );
const tasks = provider.getTasks(); const tasks = provider.getTasks();
expect(4).is.equals(tasks[0].ts); expect(4).is.equals(tasks[0].ts);