-
Notifications
You must be signed in to change notification settings - Fork 594
/
Copy pathvalidateBlocksExist.ts
53 lines (48 loc) · 1.82 KB
/
validateBlocksExist.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import * as Blockly from "blockly";
export function validateBlocksExist({ usedBlocks, requiredBlockCounts }: {
usedBlocks: Blockly.Block[],
requiredBlockCounts: pxt.Map<number>,
}): {
missingBlocks: string[],
disabledBlocks: string[],
insufficientBlocks: string[],
successfulBlocks: pxt.Map<Blockly.Block[]>,
passed: boolean
} {
let missingBlocks: string[] = [];
let disabledBlocks: string[] = [];
let insufficientBlocks: string[] = [];
let successfulBlocks: pxt.Map<Blockly.Block[]> = {};
const userBlocksEnabledByType = usedBlocks?.reduce((acc: pxt.Map<number>, block) => {
acc[block.type] = (acc[block.type] || 0) + (block.isEnabled() ? 1 : 0);
return acc;
}, {});
for (const [requiredBlockId, requiredCount] of Object.entries(requiredBlockCounts || {})) {
const countForBlock = userBlocksEnabledByType[requiredBlockId];
const passedBlocks = usedBlocks.filter((block) => block.isEnabled() && block.type === requiredBlockId);
if (passedBlocks.length > 0) {
successfulBlocks[requiredBlockId] = passedBlocks;
}
if (countForBlock === undefined) {
// user did not use a specific block
missingBlocks.push(requiredBlockId);
} else if (!countForBlock) {
// all instances of block are disabled
disabledBlocks.push(requiredBlockId);
} else if (countForBlock < requiredCount) {
// instances of block exists, but not enough.
insufficientBlocks.push(requiredBlockId);
}
}
const passed =
missingBlocks.length === 0 &&
disabledBlocks.length === 0 &&
insufficientBlocks.length === 0;
return {
missingBlocks,
disabledBlocks,
insufficientBlocks,
successfulBlocks,
passed
}
}