Created
January 17, 2024 21:14
-
-
Save tripolskypetr/c44e2472f17e6b23cbf6af1577a10264 to your computer and use it in GitHub Desktop.
SpellerService.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { makeObservable } from "mobx"; | |
import { singleshot } from "react-declarative"; | |
// @ts-ignore | |
import { Hunspell, loadModule } from 'hunspell-asm/dist/cjs'; | |
import XRegExp from 'xregexp' | |
export class SpellerService { | |
private _hunspell: Hunspell = null as never; | |
constructor() { | |
makeObservable(this, {}); | |
} | |
public validate = (text: string) => { | |
const errors = this._check(text); | |
return errors.length ? `Проверьте слова: ${errors.join(', ')}` : null; | |
}; | |
private _check = (text: string) => { | |
const regex = XRegExp('[^\\p{N}\\p{L}-_]', 'g') | |
return text | |
.replace(regex, ' ') | |
.split(' ') | |
.filter(item => item) | |
.filter(item => isNaN(Number(item))) | |
.filter(item => !/[0-9]/g.test(item)) | |
.filter(item => !this._hunspell.spell(item)) | |
}; | |
protected prefetch = singleshot(async () => { | |
const hunspellFactory = await loadModule(); | |
const aff = await fetch('/lang/ru_RU.aff'); | |
const affBuffer = new Uint8Array(await aff.arrayBuffer()); | |
const affFile = hunspellFactory.mountBuffer(affBuffer, 'lang.aff'); | |
const dic = await fetch('/lang/ru_RU.dic'); | |
const dicBuffer = new Uint8Array(await dic.arrayBuffer()); | |
const dictFile = hunspellFactory.mountBuffer(dicBuffer, 'lang.dic'); | |
this._hunspell = hunspellFactory.create(affFile, dictFile); | |
}); | |
} | |
export default SpellerService; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment