UNPKG

2.73 kBJavaScriptView Raw
1
2import { re } from './swuquery-re';
3import { re as reSWU } from '../swu/swu-re';
4import { swu2coord } from '../convert';
5
6const parsePrefix = (text) => {
7 return {
8 required: true,
9 parts: text == 'T' ? undefined :
10 text.match(new RegExp(`(${re.list})`, 'g'))
11 .map(part => {
12 if (part.includes('o')) {
13 return ['or'].concat(part.match(new RegExp(`(${re.item})`, 'g'))
14 .map(part => part[0] != 'R' ? part : [part.slice(1, 3), part.slice(3, 5)]))
15 } else {
16 return part[0] != 'R' ? part : [part.slice(1, 3), part.slice(3, 5)]
17 }
18 })
19 }
20}
21const parseSignbox = (text) => {
22 return text.match(new RegExp(`(${re.list}${re.coord})`, 'g'))
23 .map(part => {
24 let coord, front;
25 coord = part.match(new RegExp(`${reSWU.coord}`));
26
27 if (coord) {
28 coord = swu2coord(coord[0]);
29 front = part.slice(0, -4);
30 } else {
31 coord = undefined;
32 front = part;
33 }
34
35 if (front.includes('o')) {
36 return {
37 or: front.split('o').map(part => {
38 if (!part.includes('R')) {
39 return part;
40 } else {
41 return [part.slice(1, 3), part.slice(3, 5)];
42 }
43 }),
44 coord, coord
45 }
46 } else if (!front.includes('R')) {
47 return {
48 symbol: front,
49 coord: coord
50 }
51 } else {
52 return {
53 range: [front.slice(1, 3), front.slice(3, 5)],
54 coord: coord
55 }
56 }
57 })
58}
59
60/**
61 * Function to parse SWU query string to object
62 * @function swuquery.parse
63 * @param {string} swuQueryString - an SWU query string
64 * @returns {object} elements of an SWU query string
65 * @example
66 * swuquery.parse('QA񀀁R񀀁񆆑񆇡T񆀁R񀀁񀇱𝤆𝤆V5-')
67 *
68 * return {
69 * query: true,
70 * prefix: {
71 * required: true,
72 * parts: [
73 * '񀀁',
74 * ['񀀁', '񆆑'],
75 * '񆇡'
76 * ]
77 * },
78 * signbox: [
79 * { symbol: '񆀁' },
80 * {
81 * range: ['񀀁', '񀇱'],
82 * coord: [500, 500]
83 * }
84 * ],
85 * variance: 5,
86 * style: true
87 * }
88 */
89const parse = (swuQueryString) => {
90 const query = (typeof swuQueryString === 'string') ? swuQueryString.match(new RegExp(`^${re.full}`)) : undefined;
91 return {
92 'query': query ? true : undefined,
93 'prefix': query && query[1] ? parsePrefix(query[1]) : undefined,
94 'signbox': query && query[2] ? parseSignbox(query[2]) : undefined,
95 'variance': query && query[3] ? parseInt(query[3].slice(1)) : undefined,
96 'style': query && query[4] ? true : undefined
97 };
98}
99
100export { parse }