lettersoup 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,33 @@
1
+ # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
2
+ # For more information see: https://docs.github.com/en/actions/publishing-packages/publishing-nodejs-packages
3
+
4
+ name: Node.js Package
5
+
6
+ on:
7
+ release:
8
+ types: [created]
9
+
10
+ jobs:
11
+ build:
12
+ runs-on: ubuntu-latest
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ - uses: actions/setup-node@v4
16
+ with:
17
+ node-version: 20
18
+ - run: npm ci
19
+ - run: npm test
20
+
21
+ publish-npm:
22
+ needs: build
23
+ runs-on: ubuntu-latest
24
+ steps:
25
+ - uses: actions/checkout@v4
26
+ - uses: actions/setup-node@v4
27
+ with:
28
+ node-version: 20
29
+ registry-url: https://registry.npmjs.org/
30
+ - run: npm ci
31
+ - run: npm publish
32
+ env:
33
+ NODE_AUTH_TOKEN: ${{secrets.npm_token}}
package/.nvmrc ADDED
@@ -0,0 +1 @@
1
+ v22.4.1
package/README.md ADDED
@@ -0,0 +1,62 @@
1
+ # LetterSoup (Algorithm) (no Production now)
2
+
3
+ Algorithm for make letterSoups (sopa de letras)
4
+
5
+
6
+ ## Import/Examples
7
+
8
+ ```Javascript
9
+ import letterSoup from 'letterSoup'
10
+
11
+ const listWords = ['Doctor', 'Dog', 'Banana']
12
+
13
+ const result = letterSoup.generate(listWords)
14
+ ```
15
+
16
+
17
+ ## Run Locally
18
+
19
+ Clone repository
20
+
21
+ ```bash
22
+ git clone https://github.com/FabianEscarate/letterSoup
23
+ ```
24
+
25
+ Go to the project directory
26
+
27
+ ```bash
28
+ cd letterSoup
29
+ ```
30
+
31
+ use current node version
32
+
33
+ ```bash
34
+ nvm use
35
+ ```
36
+
37
+ Install dependencies
38
+
39
+ ```bash
40
+ npm install
41
+ ```
42
+
43
+ Start the server
44
+
45
+ ```bash
46
+ npm start
47
+ ```
48
+
49
+
50
+ ## Running Tests
51
+
52
+ To run tests, run the following command
53
+
54
+ ```bash
55
+ npm run test
56
+ ```
57
+
58
+
59
+ ## Authors
60
+
61
+ - [@Fabian Escarate](https://www.github.com/FabianEscarate)
62
+
@@ -0,0 +1,36 @@
1
+ import { WordSearch } from "../src"
2
+
3
+ describe('letterSoup generator', () => {
4
+
5
+ const wordsArray = [
6
+ "tarjetas",
7
+ "Weaselling",
8
+ "Pinwales",
9
+ "populoso",
10
+ "participio",
11
+ "Cuddliest",
12
+ "Especias",
13
+ "teléfonos",
14
+ "epigráfico",
15
+ "hidrométrico",
16
+ "licitador",
17
+ "partición",
18
+ "miembros",
19
+ "nuestra",
20
+ "restituciones"
21
+ ]
22
+
23
+ test('should return a object when call generate function', () => {
24
+ const {
25
+ getPuzzle,
26
+ getWords
27
+ } = new WordSearch(wordsArray)
28
+
29
+ const listOfWord = getWords()
30
+ const puzzle = getPuzzle()
31
+
32
+ expect(puzzle).toBeDefined()
33
+ expect(listOfWord).toBeDefined()
34
+
35
+ })
36
+ })
@@ -0,0 +1,80 @@
1
+ import {
2
+ hasAnotherLetters,
3
+ generateRegexByGroupOfSpacesAndLetters,
4
+ isWhiteSpace,
5
+ splitsGroupOfSpacesAndLetter,
6
+ chunkListCharactersByCriterial,
7
+ joinRegexStringWithPipe
8
+ } from "../../src/utils/regex";
9
+
10
+
11
+ describe('Regex Suite', () => {
12
+
13
+ test('should validate if line has letters', () => {
14
+ const lineWithLetters = ' sa '
15
+ const lineWithOutLetters = ' '
16
+
17
+ expect(hasAnotherLetters(lineWithLetters)).toBeTruthy()
18
+ expect(hasAnotherLetters(lineWithOutLetters)).toBeFalsy()
19
+ })
20
+
21
+ test('should valid a empty string', () => {
22
+ const lineEmpty = ' '
23
+
24
+ expect(isWhiteSpace(lineEmpty)).toBeTruthy()
25
+ })
26
+
27
+ test('should valid a string with letters', () => {
28
+ const lineEmpty = 'asdf'
29
+
30
+ expect(!isWhiteSpace(lineEmpty)).toBeTruthy()
31
+ })
32
+
33
+ test('should return groups of space and letters', () => {
34
+ const lineGenerate = ' i a '.toUpperCase()
35
+
36
+ const splittedLine = splitsGroupOfSpacesAndLetter(lineGenerate)
37
+
38
+ if (!splittedLine) return
39
+
40
+ expect(splittedLine.length).toBe(5)
41
+ expect(splittedLine[1]).toBe('I')
42
+ expect(splittedLine[3]).toBe('A')
43
+ })
44
+
45
+ test('should join regex string with pipes', () => {
46
+ const firstRegex = '(^.{1,7}i.{4}a.{1,4}$)'
47
+ const secondRegex = '(^.{1,7}i.{1,4}$)'
48
+ const thirdRegex = '(^.{1,4}a.{1,4}$)'
49
+ const expectedStringRegex = '(^.{1,7}i.{4}a.{1,4}$)|(^.{1,7}i.{1,4}$)|(^.{1,4}a.{1,4}$)'
50
+
51
+ expect(
52
+ joinRegexStringWithPipe(
53
+ firstRegex,
54
+ secondRegex,
55
+ thirdRegex
56
+ )
57
+ ).toBe(expectedStringRegex)
58
+ })
59
+
60
+ test('should return chunked array', () => {
61
+ const groupToGenerate = [' ', 'i', ' ', 'a', ' '] as RegExpMatchArray
62
+ const secondGroupToGenerate = ['s',' ', 'i', ' ', 'a', ' ', 'e'] as RegExpMatchArray
63
+
64
+ const chunkedArray = chunkListCharactersByCriterial(groupToGenerate)
65
+ const secondChunkedArray = chunkListCharactersByCriterial(secondGroupToGenerate)
66
+
67
+ expect(chunkedArray.length).toBe(2)
68
+ expect(secondChunkedArray.length).toBe(4)
69
+
70
+ })
71
+
72
+ test('should return regex expresion from expecific group of spaces and letters', () => {
73
+ const groupGenerate = [' ', 'i', ' ', 'a', ' '] as RegExpMatchArray
74
+ const regexExpected = '/(^.{1,7}i.{4}a.{1,4}$)|(^.{1,7}i.{1,4}$)|(^.{1,4}a.{1,4}$)/gm'
75
+ const regexExpresionResult = generateRegexByGroupOfSpacesAndLetters(groupGenerate)
76
+
77
+ expect(regexExpresionResult.toString()).toBe(regexExpected)
78
+ })
79
+
80
+ })
package/jest.config.js ADDED
@@ -0,0 +1,7 @@
1
+ /** @type {import('ts-jest').JestConfigWithTsJest} **/
2
+ module.exports = {
3
+ testEnvironment: "node",
4
+ transform: {
5
+ "^.+.tsx?$": ["ts-jest",{}],
6
+ },
7
+ };
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "lettersoup",
3
+ "version": "1.0.0",
4
+ "description": "generate letterSoup",
5
+ "main": "src/index.ts",
6
+ "scripts": {
7
+ "start": "ts-node -e \"require('./src/index.ts').main()\"",
8
+ "test": "jest"
9
+ },
10
+ "keywords": [
11
+ "letterSoup",
12
+ "letters",
13
+ "search",
14
+ "searchword",
15
+ "word"
16
+ ],
17
+ "author": "Fabian Escarate",
18
+ "license": "ISC",
19
+ "devDependencies": {
20
+ "@types/jest": "^29.5.12",
21
+ "jest": "^29.7.0",
22
+ "ts-jest": "^29.2.2",
23
+ "ts-node": "^10.9.2",
24
+ "typescript": "^5.5.3"
25
+ }
26
+ }
@@ -0,0 +1,127 @@
1
+ import { orientationEnum, orientationType } from "../Types"
2
+ import { DimensionType } from "./Dimension"
3
+ import Lines from "./Lines"
4
+ import Matrix from "./Matrix"
5
+
6
+
7
+
8
+ export class Cord {
9
+ cordX: number
10
+ cordY: number
11
+
12
+ constructor(cordX: number, cordY: number) {
13
+ this.cordX = cordX
14
+ this.cordY = cordY
15
+ }
16
+ }
17
+
18
+ export default class Cords {
19
+ private matrix: Matrix
20
+ private currentPosition?: Cord = undefined
21
+ private allCordsOfMatrix: Cord[]
22
+ constructor(matrix: Matrix) {
23
+ this.matrix = matrix
24
+ this.allCordsOfMatrix = this.getAllCordsOfMatrix(matrix.dimension.getDimension())
25
+ }
26
+
27
+ private getAllCordsOfMatrix = (dimensionMatrix: DimensionType) => {
28
+ const {
29
+ width,
30
+ height
31
+ } = dimensionMatrix
32
+
33
+ const result = []
34
+
35
+ for (let x = 0; x < height; x++)
36
+ for (let y = 0; y < width; y++)
37
+ result.push(new Cord(x, y))
38
+
39
+ return result
40
+ }
41
+
42
+ scrambleCordsOfMatrix = () => {
43
+ let scrambleCords = []
44
+ const cordsOfMatrix = this.allCordsOfMatrix
45
+ while (cordsOfMatrix.length > 0) {
46
+ scrambleCords.push(cordsOfMatrix.splice(Math.floor(Math.random() * cordsOfMatrix.length), 1)[0])
47
+ }
48
+ return scrambleCords
49
+ }
50
+
51
+ setCordPosition = (cord: Cord) => {
52
+ this.currentPosition = cord
53
+ this.matrix.setLines(new Lines(this.matrix))
54
+ }
55
+
56
+ getCordPosition = () => {
57
+ if (!this.currentPosition)
58
+ throw new Error("Undefined current cord position ");
59
+
60
+ return this.currentPosition
61
+ }
62
+
63
+ private horizontalCords = (): Cord[] => {
64
+ const result = []
65
+ const { width } = this.matrix.dimension.getDimension()
66
+ const { cordX } = this.matrix.cords.getCordPosition()
67
+
68
+ for (let i = 0; i < width; i++) {
69
+ result.push(new Cord(cordX,i))
70
+ }
71
+ return result
72
+ }
73
+
74
+ private verticalCords = (): Cord[] => {
75
+ const result = []
76
+ const { height } = this.matrix.dimension.getDimension()
77
+ const { cordY } = this.matrix.cords.getCordPosition()
78
+
79
+ for (let i = 0; i < height; i++) {
80
+ result.push(new Cord(i, cordY))
81
+ }
82
+ return result
83
+ }
84
+
85
+ private diagonalCords = (): Cord[] => {
86
+ const result = []
87
+ const { width, height } = this.matrix.dimension.getDimension()
88
+ const { cordX, cordY } = this.matrix.cords.getCordPosition()
89
+
90
+ for (let x = Math.max(0, cordX - cordY); x < Math.min(height, height + cordX - cordY); x++) {
91
+ const y = x - (cordX - cordY);
92
+ if (0 <= y && y < width) {
93
+ result.push(new Cord(x, y));
94
+ }
95
+ }
96
+ return result
97
+ }
98
+
99
+ private antiDiagonalCords = (): Cord[] => {
100
+ const result = []
101
+ const { width, height } = this.matrix.dimension.getDimension()
102
+ const { cordX, cordY } = this.matrix.cords.getCordPosition()
103
+
104
+ for (let x = Math.max(0, cordX + cordY - width + 1); x < Math.min(height, cordX + cordY + 1); x++) {
105
+ const y = cordX + cordY - x;
106
+ if (0 <= y && y < width) {
107
+ result.push(new Cord(x, y))
108
+ }
109
+ }
110
+
111
+ return result.reverse()
112
+ }
113
+
114
+ getCordsFromCurrentPositionByOrientation = (orientation: orientationType): Cord[] => {
115
+ switch (orientation) {
116
+ case "horizontally":
117
+ return this.horizontalCords()
118
+ case "vertically":
119
+ return this.verticalCords()
120
+ case "diagonally":
121
+ return this.diagonalCords()
122
+ case "antidiagonally":
123
+ return this.antiDiagonalCords()
124
+ }
125
+ }
126
+
127
+ }
@@ -0,0 +1,24 @@
1
+
2
+ const MARGIN_PUZZLE = 1
3
+
4
+ export type DimensionType = {
5
+ width: number,
6
+ height: number
7
+ }
8
+
9
+ export default class DimensionPuzzle {
10
+ private width: number
11
+ private height: number
12
+
13
+ constructor(length: number) {
14
+ this.width = MARGIN_PUZZLE + length + MARGIN_PUZZLE
15
+ this.height = MARGIN_PUZZLE + length + MARGIN_PUZZLE
16
+ }
17
+
18
+ getDimension(): DimensionType {
19
+ return {
20
+ width: this.width,
21
+ height: this.height
22
+ }
23
+ }
24
+ }
@@ -0,0 +1,59 @@
1
+ import { orientationEnum, orientationType, regexValueByLineType } from "../Types";
2
+ import { generateRegexByLine } from "../utils/regex";
3
+ import Matrix from "./Matrix";
4
+
5
+ export default class Lines {
6
+ horizontallyLine: string = ''
7
+ verticallyLine: string = ''
8
+ diagonallyDownLine: string = ''
9
+ diagonallyUpLine: string = ''
10
+
11
+ constructor(matrix?: Matrix) {
12
+ if (!matrix)
13
+ return
14
+
15
+ const {
16
+ cords: { getCordsFromCurrentPositionByOrientation },
17
+ getSlot
18
+ } = matrix
19
+
20
+ this.horizontallyLine = getCordsFromCurrentPositionByOrientation(orientationEnum.horizontally).map(cord => getSlot(cord.cordX, cord.cordY)).join('')
21
+ this.verticallyLine = getCordsFromCurrentPositionByOrientation(orientationEnum.vertically).map(cord => getSlot(cord.cordX, cord.cordY)).join('')
22
+ this.diagonallyDownLine = getCordsFromCurrentPositionByOrientation(orientationEnum.diagonally).map(cord => getSlot(cord.cordX, cord.cordY)).join('')
23
+ this.diagonallyUpLine = getCordsFromCurrentPositionByOrientation(orientationEnum.antidiagonally).map(cord => getSlot(cord.cordX, cord.cordY)).join('')
24
+ }
25
+
26
+ getLinesWithRegex = (): regexValueByLineType => {
27
+ const lines = {
28
+ horizontallyLine: this.horizontallyLine,
29
+ verticallyLine: this.verticallyLine,
30
+ diagonallyDownLine: this.diagonallyDownLine,
31
+ diagonallyUpLine: this.diagonallyUpLine
32
+ }
33
+
34
+ const regexForLines = Object.keys(lines).reduce((result, key) => {
35
+ const newObj = {} as any
36
+ newObj[`regex${key.capitalize()}`] = generateRegexByLine(lines[key as keyof typeof lines])
37
+ return {
38
+ ...result,
39
+ ...newObj
40
+ }
41
+ }, {} as regexValueByLineType)
42
+
43
+ return regexForLines
44
+ }
45
+
46
+ getLineByOrientation = (orientation: orientationType) => {
47
+ switch (orientation) {
48
+ case "horizontally":
49
+ return this.horizontallyLine
50
+ case "vertically":
51
+ return this.verticallyLine
52
+ case "diagonally":
53
+ return this.diagonallyDownLine
54
+ case "antidiagonally":
55
+ return this.diagonallyUpLine
56
+
57
+ }
58
+ }
59
+ }
@@ -0,0 +1,43 @@
1
+ import { puzzleType } from "../Types";
2
+ import Cords, { Cord } from "./Cords";
3
+ import DimensionPuzzle from "./Dimension";
4
+ import Lines from "./Lines";
5
+
6
+ const BLANK_SPACE = ' '
7
+
8
+ export default class Matrix {
9
+ dimension: DimensionPuzzle
10
+ cords: Cords
11
+ lines: Lines
12
+ private matrix: string[][]
13
+
14
+ constructor(length: number) {
15
+ this.dimension = new DimensionPuzzle(length)
16
+ this.matrix = this.generate()
17
+ this.cords = new Cords(this)
18
+ this.lines = new Lines()
19
+
20
+ }
21
+
22
+ private generate = () => {
23
+ const {
24
+ width,
25
+ height
26
+ } = this.dimension.getDimension()
27
+
28
+ const matrix: puzzleType = Array(...Array(width * height)).reduce((resultValue, currentValue, index, array) => {
29
+ resultValue = [...resultValue, array.splice(0, width).map(index => BLANK_SPACE)]
30
+ return resultValue
31
+ }, [])
32
+
33
+ return matrix
34
+ }
35
+
36
+ setSlot = (cordX: number, cordY: number, letter: string) => { this.matrix[cordX][cordY] = letter }
37
+
38
+ getSlot = (cordX: number, cordY: number) => this.matrix[cordX][cordY]
39
+
40
+ setLines = (lines: Lines) => { this.lines = lines }
41
+
42
+ getMatrix = () => this.matrix
43
+ }
@@ -0,0 +1,115 @@
1
+ import { orientationType, wordListByLineType } from "../Types"
2
+ import { Cord } from "./Cords"
3
+ import Matrix from "./Matrix"
4
+
5
+ const LETTERS = 'ABCDEFGHIJKLMNÑOPQRSTUVWXYZ'
6
+
7
+ export default class Words {
8
+ private matrix: Matrix
9
+ private listOfWords: string[]
10
+
11
+ constructor(matrix: Matrix, listOfWords: string[]) {
12
+ this.matrix = matrix
13
+ this.listOfWords = listOfWords.slice()
14
+ }
15
+
16
+ removeWord = (word: string) => {
17
+ this.listOfWords.splice(this.listOfWords.indexOf(word), 1)
18
+ }
19
+
20
+ private putWordHorizontally = (word: string, padStart: number = 0) => {
21
+ const { width } = this.matrix.dimension.getDimension()
22
+
23
+ const { cordX } = this.matrix.cords.getCordPosition()
24
+ let wordIndex = 0
25
+ for (let horizontalIndex = 0; horizontalIndex < width; horizontalIndex++) {
26
+ if (horizontalIndex >= padStart && wordIndex < word.length) {
27
+ this.matrix.setSlot(cordX, horizontalIndex, word.charAt(wordIndex))
28
+ wordIndex++
29
+ }
30
+ }
31
+ }
32
+
33
+ private putWordVertically = (word: string, padStart: number = 0) => {
34
+ const { height } = this.matrix.dimension.getDimension()
35
+
36
+ const { cordY } = this.matrix.cords.getCordPosition()
37
+ let wordIndex = 0
38
+ for (let verticalIndex = 0; verticalIndex < height; verticalIndex++) {
39
+ if (verticalIndex >= padStart && wordIndex < word.length) {
40
+ this.matrix.setSlot(verticalIndex, cordY, word.charAt(wordIndex))
41
+ wordIndex++
42
+ }
43
+ }
44
+ }
45
+
46
+ private putWordDiagonally = (word: string, padStart: number = 0) => {
47
+ const { height, width } = this.matrix.dimension.getDimension()
48
+ const { cordX, cordY } = this.matrix.cords.getCordPosition()
49
+
50
+ let wordIndex = 0
51
+ let spaceToStart = padStart
52
+ for (let i = Math.max(0, cordX - cordY); i < Math.min(height, height + cordX - cordY); i++) {
53
+ const j = i - (cordX - cordY);
54
+ if (0 <= j && j < width) {
55
+ if (spaceToStart > 0) {
56
+ spaceToStart--
57
+ continue
58
+ }
59
+ this.matrix.setSlot(i, j, wordIndex < word.length ? word.charAt(wordIndex) : this.matrix.getSlot(i, j))
60
+ wordIndex++
61
+ }
62
+ }
63
+ }
64
+
65
+ private putWordAntiDiagonally = (word: string, padStart: number = 0) => {
66
+ const { height, width } = this.matrix.dimension.getDimension()
67
+ const { cordX, cordY } = this.matrix.cords.getCordPosition()
68
+
69
+ let wordIndex = 0
70
+ let spaceToStart = padStart
71
+ for (let x = Math.max(0, cordX + cordY - width + 1); x < Math.min(height, cordX + cordY + 1); x++) {
72
+ const y = cordX + cordY - x;
73
+ if (0 <= y && y < width) {
74
+ if (spaceToStart > 0) {
75
+ spaceToStart--
76
+ continue
77
+ }
78
+ this.matrix.setSlot(x, y, wordIndex < word.length ? word.charAt(wordIndex) : this.matrix.getSlot(x, y))
79
+ wordIndex++
80
+ }
81
+ }
82
+ }
83
+
84
+ putWord = (word: string, orientation: orientationType, padStart: number = 0) => {
85
+ switch (orientation) {
86
+ case "diagonally":
87
+ this.putWordDiagonally(word, padStart)
88
+ break;
89
+ case "vertically":
90
+ this.putWordVertically(word, padStart)
91
+ break;
92
+ case "horizontally":
93
+ this.putWordHorizontally(word, padStart)
94
+ break;
95
+ case "antidiagonally":
96
+ this.putWordAntiDiagonally(word, padStart)
97
+ break;
98
+ }
99
+ }
100
+
101
+ getWordsEveryOrientation = (): wordListByLineType => {
102
+ const linesWithSearhRegex = this.matrix.lines.getLinesWithRegex()
103
+
104
+ const wordsByLine = Object.keys(linesWithSearhRegex).reduce((result, key) => {
105
+ const newObj = {} as any
106
+ newObj[`match${key.capitalize()}`] = this.listOfWords.filter(word => word.match(linesWithSearhRegex[key as keyof typeof linesWithSearhRegex]) as string[])
107
+ return {
108
+ ...result,
109
+ ...newObj
110
+ }
111
+ }, {} as wordListByLineType)
112
+
113
+ return wordsByLine
114
+ }
115
+ }
package/src/Types.ts ADDED
@@ -0,0 +1,40 @@
1
+
2
+ export type puzzleType = string[][]
3
+ export type orientationType = "horizontally" | "vertically" | "diagonally" | "antidiagonally"
4
+ export type linesByCordsType = {
5
+ horizontallyLine: string;
6
+ verticallyLine: string;
7
+ diagonallyDownLine: string;
8
+ diagonallyUpLine: string;
9
+ }
10
+
11
+ export enum matchRegexLines {
12
+ matchRegexDiagonallyDownLine = "diagonally",
13
+ matchRegexDiagonallyUpLine = "antidiagonally",
14
+ matchRegexHorizontallyLine = "horizontally",
15
+ matchRegexVerticallyLine = "vertically"
16
+ }
17
+
18
+ export type regexValueByLine<Type> = {
19
+ [key in keyof Type as `regex${Capitalize<string & key>}`]: RegExp
20
+ }
21
+
22
+ export type regexValueByLineType = regexValueByLine<linesByCordsType>
23
+ export enum orientationEnum {
24
+ horizontally = "horizontally",
25
+ vertically = "vertically",
26
+ diagonally = "diagonally",
27
+ antidiagonally = "antidiagonally"
28
+ }
29
+ export type wordListByLine<Type> = {
30
+ [key in keyof Type as `match${Capitalize<string & key>}`]: string[]
31
+ }
32
+
33
+ export type wordListByLineType = wordListByLine<regexValueByLineType>
34
+
35
+ export type interectionType = {
36
+ wordIndex: number,
37
+ lineIndex: number
38
+ }
39
+
40
+ export type interectionsType = interectionType[]
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ import './utils/string'
2
+ export { WordSearch } from "./letterSoup"
@@ -0,0 +1,130 @@
1
+ import { Cord } from "./Entities/Cords"
2
+ import Matrix from "./Entities/Matrix"
3
+ import Words from "./Entities/Word"
4
+ import { interectionsType, matchRegexLines, wordListByLineType } from "./Types"
5
+ import { generateRegexByLine } from "./utils/regex"
6
+
7
+ export class WordSearch {
8
+ private listOfWord: string[]
9
+ private puzzle: Matrix
10
+ private words: Words
11
+
12
+ constructor(listOfWords: string[]) {
13
+ this.listOfWord = listOfWords.map(word => word.toUpperCase())
14
+ const maxWordLegth = Math.max(...listOfWords.map(word => word.length))
15
+ this.puzzle = new Matrix(maxWordLegth)
16
+ this.words = new Words(this.puzzle, this.listOfWord)
17
+
18
+ this.generate()
19
+ }
20
+
21
+ private generate() {
22
+ const cordsPuzzle = this.puzzle.cords.scrambleCordsOfMatrix()
23
+
24
+ for (const cord of cordsPuzzle) {
25
+ const canPutWord = this.canPutWordInCurrentPosition(cord)
26
+
27
+ if (canPutWord) {
28
+ const {
29
+ orientation,
30
+ line,
31
+ wordSelected
32
+ } = this.selectAnyMatch(canPutWord)
33
+
34
+ const intersections = this.getIntersections(wordSelected, line)
35
+ const intersection = this.checkIntersections(intersections, wordSelected, line)
36
+
37
+ if (intersection) {
38
+ this.words.putWord(wordSelected, orientation, (intersection.lineIndex - intersection.wordIndex))
39
+ } else {
40
+ this.words.putWord(wordSelected, orientation)
41
+ }
42
+ this.words.removeWord(wordSelected)
43
+ }
44
+ }
45
+ }
46
+
47
+ private canPutWordInCurrentPosition = (cord: Cord) => {
48
+ this.puzzle.cords.setCordPosition(cord)
49
+ const wordsForEveryOrientation = this.words.getWordsEveryOrientation()
50
+ const {
51
+ matchRegexDiagonallyDownLine,
52
+ matchRegexDiagonallyUpLine,
53
+ matchRegexHorizontallyLine,
54
+ matchRegexVerticallyLine
55
+ } = wordsForEveryOrientation
56
+ const canPutWord = [
57
+ matchRegexDiagonallyDownLine.length > 0,
58
+ matchRegexDiagonallyUpLine.length > 0,
59
+ matchRegexHorizontallyLine.length > 0,
60
+ matchRegexVerticallyLine.length > 0
61
+ ].some(Boolean)
62
+
63
+ if (!canPutWord) return false
64
+ return wordsForEveryOrientation
65
+ }
66
+
67
+ private pickRandomElement = <T>(listOfElements: T[]): T => {
68
+ return listOfElements[Math.floor(Math.random() * listOfElements.length)]
69
+ }
70
+
71
+ private selectAnyMatch = (lineMatches: wordListByLineType) => {
72
+ const matchKeyToScramble = Object.keys(lineMatches)
73
+ .filter(
74
+ keyLineMatch => lineMatches[keyLineMatch as keyof wordListByLineType].length > 0
75
+ )
76
+
77
+ const randomSelection = this.pickRandomElement(matchKeyToScramble) as keyof wordListByLineType
78
+
79
+ return {
80
+ orientation: matchRegexLines[randomSelection],
81
+ line: this.puzzle.lines.getLineByOrientation(matchRegexLines[randomSelection]),
82
+ wordSelected: this.pickRandomElement(lineMatches[randomSelection]),
83
+ }
84
+ }
85
+
86
+ private getIntersections = (word: string, line: string): interectionsType => {
87
+ const listOfIntersections = [] as interectionsType
88
+ Array.from(word).forEach((wordLetter, wordIndex) => {
89
+ Array.from(line).forEach((lineLetter, lineIndex) => {
90
+ if (wordLetter === lineLetter)
91
+ listOfIntersections.push({
92
+ lineIndex,
93
+ wordIndex
94
+ })
95
+ })
96
+ })
97
+
98
+ return listOfIntersections
99
+ }
100
+
101
+ private checkIntersections = (intersections: interectionsType, word: string, line: string) => {
102
+
103
+ if (intersections.length === 1)
104
+ return intersections[0]
105
+ if (intersections.length > 1) {
106
+ // console.warn('have more of one intersection')
107
+ const lengthLine = line.length
108
+ const lengthWord = word.length
109
+
110
+ return intersections.filter(intersection => {
111
+ const diffIntersection = (intersection.lineIndex - intersection.wordIndex)
112
+
113
+ if ((diffIntersection + lengthWord) > lengthLine || diffIntersection < 0) {
114
+ return false
115
+ }
116
+ const subStrLine = line.substring(diffIntersection, (diffIntersection + lengthWord))
117
+ const regex = generateRegexByLine(subStrLine)
118
+ if (!regex.test(word)) {
119
+ return false
120
+ }
121
+ return true
122
+ })[0]
123
+ }
124
+ }
125
+
126
+ getPuzzle = () => this.puzzle.getMatrix()
127
+
128
+ getWords = () => this.listOfWord
129
+ }
130
+
@@ -0,0 +1,68 @@
1
+
2
+ const hasAnotherLetters = (space: string) => /[A-Z]|Á|É|Í|Ó|Ú|Ñ/i.test(space)
3
+ const isWhiteSpace = (groupToText: string) => /\s+/.test(groupToText)
4
+ const splitsGroupOfSpacesAndLetter = (line: string): RegExpMatchArray => {
5
+ return line.match(/\s+|\S+/g) as RegExpMatchArray
6
+ }
7
+ const isFirstGroup = (index: number) => index === 0
8
+ const isLastGroup = (index: number, lengthGroup: number) =>
9
+ index === (lengthGroup - 1)
10
+ const isBetweenGroup = (index: number, lengthGroup: number) =>
11
+ 0 < index && index < (lengthGroup - 1)
12
+ const regexByListGroup = (groups: RegExpMatchArray | string[]) =>
13
+ groups.reduce((regex, group, index, groups) => {
14
+
15
+ if (isFirstGroup(index))
16
+ regex += '(^'
17
+ if (isWhiteSpace(group) && isBetweenGroup(index, groups.length))
18
+ regex += `.{${group.length}}`
19
+ else if (isWhiteSpace(group))
20
+ regex += `.{1,${group.length}}`
21
+ if (!isWhiteSpace(group))
22
+ regex += `${group}`
23
+ if (isLastGroup(index, groups.length))
24
+ regex += '$)'
25
+
26
+ return regex
27
+ }, '')
28
+
29
+ const chunkListCharactersByCriterial = (groups: RegExpMatchArray) => {
30
+ let chunked = []
31
+ while (groups.length > 0) {
32
+ const criterial = isWhiteSpace(groups[0]) ? 3 : 2
33
+ chunked.push(groups.slice(0, criterial))
34
+ groups.splice(0, groups.length <= criterial ? criterial : criterial - 1)
35
+ }
36
+ return chunked
37
+ }
38
+
39
+ const joinRegexStringWithPipe = (...stringRegex: string[]) =>
40
+ stringRegex.join('|')
41
+
42
+ const generateRegexByGroupOfSpacesAndLetters = (groups: RegExpMatchArray) => {
43
+ return new RegExp(
44
+ joinRegexStringWithPipe(
45
+ regexByListGroup(groups),
46
+ ...chunkListCharactersByCriterial(groups).map(chunk => regexByListGroup(chunk))
47
+ ),
48
+ 'gm'
49
+ )
50
+ }
51
+
52
+ const generateRegexByLine = (line: string) => {
53
+ const splitedLine = splitsGroupOfSpacesAndLetter(line)
54
+ if (!splitedLine)
55
+ throw 'Error for split line'
56
+
57
+ return generateRegexByGroupOfSpacesAndLetters(splitedLine)
58
+ }
59
+
60
+ export {
61
+ hasAnotherLetters,
62
+ isWhiteSpace,
63
+ splitsGroupOfSpacesAndLetter,
64
+ joinRegexStringWithPipe,
65
+ chunkListCharactersByCriterial,
66
+ generateRegexByGroupOfSpacesAndLetters,
67
+ generateRegexByLine
68
+ }
@@ -0,0 +1,10 @@
1
+
2
+ declare interface String {
3
+ capitalize:() => string
4
+ }
5
+
6
+ function capitalize(this: String): string {
7
+ return `${this.charAt(0).toUpperCase()}${this.substring(1)}`
8
+ }
9
+
10
+ String.prototype.capitalize = capitalize
package/tsconfig.json ADDED
@@ -0,0 +1,108 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig to read more about this file */
4
+
5
+ /* Projects */
6
+ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
+ // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
+
13
+ /* Language and Environment */
14
+ "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
+ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
17
+ // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
18
+ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22
+ // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25
+ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26
+
27
+ /* Modules */
28
+ "module": "commonjs", /* Specify what module code is generated. */
29
+ "rootDir": "./", /* Specify the root folder within your source files. */
30
+ // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
31
+ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34
+ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37
+ // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38
+ // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
39
+ // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
40
+ // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
41
+ // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
42
+ // "resolveJsonModule": true, /* Enable importing .json files. */
43
+ // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
44
+ // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
45
+
46
+ /* JavaScript Support */
47
+ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
48
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
49
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
50
+
51
+ /* Emit */
52
+ // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
53
+ // "declarationMap": true, /* Create sourcemaps for d.ts files. */
54
+ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
55
+ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
56
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
57
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
58
+ // "outDir": "./", /* Specify an output folder for all emitted files. */
59
+ // "removeComments": true, /* Disable emitting comments. */
60
+ // "noEmit": true, /* Disable emitting files from a compilation. */
61
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
62
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
63
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
64
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
65
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
66
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
67
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
68
+ // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
69
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
70
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
71
+ // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
72
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
73
+
74
+ /* Interop Constraints */
75
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
76
+ // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
77
+ // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
78
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
79
+ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
80
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
81
+ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
82
+
83
+ /* Type Checking */
84
+ "strict": true, /* Enable all strict type-checking options. */
85
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
86
+ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
87
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
88
+ // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
89
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
90
+ // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
91
+ // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
92
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
93
+ // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
94
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
95
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
96
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
97
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
98
+ // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
99
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
100
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
101
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
102
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
103
+
104
+ /* Completeness */
105
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
106
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
107
+ }
108
+ }