UNPKG

@logic-pad/core

Version:
60 lines (59 loc) 2.51 kB
import { CachedAccess } from '../dataHelper.js'; import { allRules } from '../rules/index.js'; import { allSymbols } from '../symbols/index.js'; import { instance as undercluedInstance } from '../rules/undercluedRule.js'; /** * Base class that all solvers must extend. */ export default class Solver { /** * Check if the solver supports the current browser environment. This method is called once when the user first clicks * the "Solve" button, and the result is cached for the duration of the editor session. * * The `solve` method will not be called if this method returns `false`, and a message will be displayed to the user * indicating that the solver is not supported. * * @returns A promise that resolves to `true` if the environment is supported, or `false` otherwise. */ isEnvironmentSupported() { return Promise.resolve(true); } environmentCheck = CachedAccess.of(() => this.isEnvironmentSupported()); /** * Check if the solver supports the given instruction. This is used to render a small indication in the UI for each * instruction in the editor. * * @param instructionId The unique identifier of the instruction. */ isInstructionSupported(_grid, instruction) { const symbol = allSymbols.get(instruction.id); if (symbol) { return !symbol.validateWithSolution; } const rule = allRules.get(instruction.id); if (rule) { return !rule.validateWithSolution || rule.id === undercluedInstance.id; } return false; } /** * Check if the solver supports the given grid. This methid is frequently called when the user changes the grid, and * the result is used to enable or disable the "Solve" button. * * The `solve` method will not be called if this method returns `false`, and a message will be displayed to the user * indicating that the grid is not supported by this solver. * * @param grid The grid to check. * @returns `true` if the grid is supported, or `false` otherwise. */ isGridSupported(grid) { if (grid.rules.some(rule => rule.necessaryForCompletion && !this.isInstructionSupported(grid, rule))) { return false; } if ([...grid.symbols.values()].some(symbols => symbols.some(s => s.necessaryForCompletion && !this.isInstructionSupported(grid, s)))) { return false; } return true; } }