This repository has been archived by the owner on Sep 24, 2024. It is now read-only.
forked from ezwelty/opentrees-harvester
-
Notifications
You must be signed in to change notification settings - Fork 1
/
names.js
830 lines (781 loc) · 21.1 KB
/
names.js
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
/**
* Parse scientific names.
*
* @module
*/
const helpers = require('./helpers')
// ---- Components ----
/**
* Generic epithet.
*
* Minimum two letters.
* Dash can be within three letters of end (e.g. 'Uva-ursi', 'Filix-mas').
*/
const GENERIC = `(?:[A-Z][a-z]+|[A-z][a-z]{2,}-[a-z]{3,})`
/**
* Specifc epithet.
*
* Minimum two letters.
* Dashes can be within one letter of end (e.g. 's-stylata', 'laurel-y').
*/
const SPECIFIC = `[a-z]+[a-z-]*[a-z]+`
/**
* Subgenus rank.
*
* subg: subg(.) | subgen(.) | subgenus
*/
const SUBG = `(?:subg(?:en)?\\.?|subgenus)`
/**
* Species rank.
*
* sp: sp(.), spp(.), species
*/
const SP = `(?:spp?\\.?|species)`
/**
* Infraspecific ranks.
*
* subsp: subsp(.) | subspp(.) | ssp(.) | sspp(.) | subspecies
* var: var(.) | variety | varietas
* subvar: subvar(.), subvariety, subvarietas
* f: f(.) | form | forma
* subf: subf(.) | subform | subforma
*/
const RANKS = {
subsp: `subspp?\\.?|sspp?\\.?|subspecies`,
var: `var\\.?|variety|varietas`,
subvar: `subvar\\.?|subvariety|subvarietas`,
f: `f\\.?|forma?`,
subf: `subf\\.?|subforma?`
}
/**
* Any infraspecific rank.
*/
const RANK = Object.values(RANKS).join('|')
// ---- Named capture groups ----
/**
* Everything before the first (latin) letter or hybrid symbol.
*/
const HEAD = `^(?<head>[^A-z×]+)`
/**
* Uninomial.
*/
const UNINOMIAL = `(?<uninomial>${GENERIC})`
/**
* Genus.
*
* Identical to uninomial, but inferred to be a genus based on context.
*/
const GENUS = `(?<genus>${GENERIC})`
/**
* Secondary genus in hybrid formula.
*
* May be abbreviated down to a single letter.
*/
const HYBRID_GENUS = `(?<genus>[A-Z](?:${SPECIFIC})?)\\.?`
/**
* Subgenus.
*/
const SUBGENUS = `${SUBG} (?<subgenus>${GENERIC})`
/**
* Species.
*/
const SPECIES = `(?<species>${SPECIFIC})`
/**
* One or more infraspecific epithets, each preceded by an optional rank.
*/
const INFRASPECIES = `(?<infraspecies>(?:(?:(?:${RANK}) )?${SPECIFIC}(?=$| ) ?)+)`
/**
* Single infraspecific epithet preceded by an optional rank.
*/
const RANK_EPITHET = `(?:(?:(?<rank>${RANK}) )?(?<epithet>${SPECIFIC}))(?:$| )`
/**
* Cultivar.
*
* Must be wrapped in quotes and not include certain characters.
*/
const CULTIVAR = `(?:(?<cultivarQuote>['"]+) ?(?<cultivar>(?:[A-z0-9'-\\. ](?! [xX] ))+[^ ]) ?\\k<cultivarQuote>)`
// ---- Decision trees ----
/**
* Parse a scientific name (or the first name in a hybrid formula).
*
* Each key is a regular expression with named capture groups. Try each in
* order. As soon as a match is found, proceed to the children keys and repeat
* until `null` or no more children are found. Any `tags`, if encountered, are
* added to the result.
*/
const FIRST = {
[`(?:[xX] |× ?)${GENUS}`]: {
tags: { hybrid: true, hybridGenus: true },
[SP]: CULTIVAR,
[CULTIVAR]: null,
[SPECIES]: {
[CULTIVAR]: null,
[INFRASPECIES]: CULTIVAR
}
},
[`${GENUS} (?:[xX] |× ?)${SPECIES}`]: {
tags: { hybrid: true },
[CULTIVAR]: null,
[INFRASPECIES]: CULTIVAR
},
[`${GENUS} (?:[xX×]|hybrid)`]: {
tags: { hybrid: true },
[CULTIVAR]: null
},
[`${GENUS} ${SUBGENUS}`]: {
tags: { hybrid: false }
},
[`${GENUS} ${SP}`]: {
[CULTIVAR]: null
},
[`${GENUS} ${CULTIVAR}`]: {
},
[`${GENUS} ${SPECIES}`]: {
[CULTIVAR]: null,
[INFRASPECIES]: {
[CULTIVAR]: null
}
},
[UNINOMIAL]: {
tags: { hybrid: false }
}
}
/**
* Parse a secondary name in a hybrid formula.
*/
const HYBRID = {
[SPECIES]: {
[CULTIVAR]: null,
[INFRASPECIES]: {
[CULTIVAR]: null
}
},
[`${HYBRID_GENUS} ${CULTIVAR}`]: {
},
[`${HYBRID_GENUS} ${SPECIES}`]: {
[CULTIVAR]: null,
[INFRASPECIES]: {
[CULTIVAR]: null
}
}
}
// ---- Object definitions ----
/**
* Infraspecies.
*
* @typedef {object} Infraspecies
* @property {string} rank - Rank (`subsp.`, `var.`, `f.`, `subvar.`, `subf.`).
* @property {string} epithet - Epithet (lowercase: e.g. `pontica`).
*/
/**
* Hybrid.
*
* Represents a secondary scientific name in a hybrid formula.
*
* @property {string} genus - Genus (capitalized: e.g. `Malus`).
* @property {string} subgenus - Subgenus (capitalized: e.g. `Malus`).
* @property {string} species - Specific epithet (lowercase: e.g. `pumila`).
* @property {Infraspecies[]} infraspecies - Infraspecific epithets.
* @property {string} cultivar - Cultivar (title case: e.g. `Golden Delicious`).
*/
/**
* Scientific name.
*
* @typedef {object} ParsedScientificName
* @property {string} head - Unparsed head.
* @property {string} uninomial – Uninomial name (maybe `genus`).
* @property {string} genus - Genus (capitalized: e.g. `Malus`).
* @property {string} subgenus - Subgenus (capitalized: e.g. `Malus`).
* @property {string} species - Specific epithet (lowercase: e.g. `pumila`).
* @property {Infraspecies[]} infraspecies - Infraspecific epithets.
* @property {string} cultivar - Cultivar (title case: e.g. `Golden Delicious`).
* @property {boolean} hybrid - Whether this is a hybrid.
* @property {boolean} hybridGenus – Whether `genus` is a nothogenus (e.g. `× Sorbopyrus`).
* @property {Hybrid[]} hybrids – Secondary names in a hybrid formula.
* @property {string} tail - Unparsed tail.
*/
// ---- Helper functions ----
/**
* Clean name string.
*
* - Latinizes characters.
* - Replaces whitespace sequences with a single space.
* - Removes leading and trailing whitespace.
*
* @param {string} s
* @return {string}
* @example
* cleanName(' Acer platanoïdes ') // 'Acer platanoides'
*/
function cleanName(s) {
return helpers.latinize(s).replace(/\s+/g, ' ').trim()
}
/**
* Parse infraspecific ranks and epithets.
*
* @param {string} s
* @returns {Infraspecies[]}
* @example
* parseInfraspecies('foo f bar') // [{epithet: 'foo'}, {rank: 'f.', epithet: 'bar'}]
*/
function parseInfraspecies(s) {
const infraspecies = []
let subs = s
while (match = subs.match(RANK_EPITHET)) {
if (match.groups.rank) {
for (const key in RANKS) {
if (match.groups.rank.match(`^(${RANKS[key]})$`)) {
match.groups.rank = `${key}.`
break
}
}
} else {
delete match.groups.rank
}
infraspecies.push(match.groups)
subs = subs.slice(match.index + match[0].length)
}
return infraspecies
}
/**
* Print infraspecific ranks and epithets.
*
* @param {Infraspecies[]} infraspecies
* @param {object} options
* @param {object} [options.n=Infinity] – Number of infraspecies.
* @param {object} [options.rank=true] – Print infraspecies rank.
* @returns {string}
* @example
* printInfraspecies([ { rank: 'f.', epithet: 'mora' } ])
* // 'f. mora'
* printInfraspecies([ { rank: 'f.', epithet: 'mora' } ], { rank: false })
* // 'mora'
*/
function printInfraspecies(infraspecies, { n = Infinity, rank = true } = {}) {
const s = []
if (n && infraspecies) {
infraspecies.slice(0, n).forEach(i => {
if (i.epithet) {
if (rank && i.rank) {
s.push(`${i.rank} ${i.epithet}`)
} else {
s.push(i.epithet)
}
}
})
}
return s.join(' ')
}
// ---- Main functions ----
/**
* Print scientific name.
*
* @param {ParsedScientificName} name - Scientific name.
* @param {object} [options] - Printing options.
* @param {number} [options.infraspecies=Infinity] - Number of infraspecies.
* @param {boolean} [options.hybrid=true] - Print hybrid symbol and formulas.
* @param {boolean} [options.rank=true] - Print infraspecies rank.
* @param {boolean} [options.cultivar=true] - Print cultivar.
* @return {string}
* @example
* name = {
* genus: 'Genus',
* species: 'speciosa',
* infraspecies: [{ rank: 'f.', epithet: 'formosa' }],
* cultivar: 'Gala',
* hybrid: true,
* hybrids: [{ genus: 'Genus', species: 'pendula' }]
* }
* printScientificName(name)
* // "Genus speciosa f. formosa 'Gala' × Genus pendula'"
* printScientificName(name, {cultivar: false})
* // "Genus speciosa f. formosa × Genus pendula'"
* printScientificName(name, {infraspecies: 0, cultivar: false})
* // 'Genus speciosa × Genus pendula'
* printScientificName(name, {hybrid: false, infraspecies: 0, cultivar: false})
* // 'Genus speciosa'
*/
function printScientificName(
name, { infraspecies = Infinity, hybrid = true, rank = true, cultivar = true } = {}
) {
if (name.uninomial) {
return name.uninomial
}
const s = []
if (hybrid && name.hybridGenus) {
s.push(`×${name.genus}`)
} else {
s.push(name.genus)
}
if (name.subgenus) {
s.push(`subg. ${name.subgenus}`)
}
if (hybrid && name.hybrid && !name.hybridGenus && !name.hybrids) {
if (name.species) {
s.push(`×${name.species}`)
} else {
s.push('×')
}
} else if (name.species) {
s.push(name.species)
}
if (infraspecies && name.infraspecies) {
s.push(
printInfraspecies(name.infraspecies, { n: infraspecies, rank: rank })
)
}
if (cultivar && name.cultivar) {
s.push(`'${name.cultivar}'`)
}
if (hybrid && name.hybrids) {
name.hybrids.forEach(h => {
const printedHybrid = printScientificName(
h, { infraspecies: infraspecies, rank: rank, cultivar: cultivar }
)
s.push(`× ${printedHybrid}`)
})
}
return s.join(' ')
}
/**
* Format scientific name.
*
* @param {ParsedScientificName} name – Scientific name.
* @param {string|boolean} defaultGenus – Genus to assume if hybrid genus is
* blank or an abbreviation of `defaultGenus`. Defaults to `genus` if `null`, or
* skipped if `false`.
* @return {ParsedScientificName}
* @example
* name = {
* genus: ' GENUS',
* species: 'SPECIOSA ',
* infraspecies: [ { rank: 'VAR', epithet: 'FORMOSA' } ],
* cultivar: 'CULTI VAR',
* hybrids: [ {genus: 'G', species: 'spéciosa' } ],
* hybrid: true
* }
* formatScientificName(name)
* // {
* // genus: 'Genus',
* // species: 'speciosa',
* // infraspecies: [ { rank: 'var.', epithet: 'formosa' } ],
* // cultivar: 'Culti Var',
* // hybrids: [ { genus: 'Genus', species: 'speciosa' } ],
* // hybrid: true
* // }
*/
function formatScientificName(name, defaultGenus = null) {
const CASE = {
uninomial: helpers.toSentenceCase,
genus: helpers.toSentenceCase,
subgenus: helpers.toSentenceCase,
species: s => s.toLowerCase(),
cultivar: helpers.toTitleCase
}
// Deep copy
const result = JSON.parse(JSON.stringify(name))
// Top-level strings
for (const key in CASE) {
if (name[key]) {
let s = name[key]
if (s) {
s = CASE[key](cleanName(s))
}
if (s) {
result[key] = s
} else {
delete result[key]
}
}
}
// Default genus
if (typeof defaultGenus === 'string') {
if (
(!result.genus && !result.uninomial) ||
(result.genus && defaultGenus.match(`^${result.genus.replace(/\.$/, '')}`))
) {
result.genus = defaultGenus
}
}
// Infraspecies
if (name.infraspecies) {
const infraspecies = result.infraspecies.map(i => {
for (const key of ['rank', 'epithet']) {
if (key in i) {
let s = i[key]
if (s) {
s = cleanName(s).toLowerCase()
}
if (s) {
if (key === 'rank') {
// Normalize rank
for (const key in RANKS) {
if (s.match(`^(${RANKS[key]})$`)) {
s = `${key}.`
break
}
}
}
i[key] = s
} else {
delete i[key]
}
}
}
return i
}).filter(obj => Object.keys(obj).length > 0)
if (infraspecies.length > 0) {
result.infraspecies = infraspecies
} else {
delete result.infraspecies
}
}
// Hybrids
if (name.hybrids) {
if (defaultGenus === null && result.genus) {
defaultGenus = result.genus
}
const hybrids = (
result.hybrids
.map(h => formatScientificName(h, defaultGenus))
.filter(obj => Object.keys(obj).length > 0)
)
if (hybrids.length > 0) {
result.hybrids = hybrids
} else {
delete result.hybrids
}
}
// Remove empty optional properties
for (const key of ['hybrid', 'hybridGenus', 'head', 'tail']) {
if (!result[key]) {
delete result[key]
}
}
return result
}
/**
* Parse scientific name.
*
* @param {string} name - Name to parse as a scientific name.
* @return {ParsedScientificName}
* @example
* parseScientificName(`Genus`)
* // { uninomial: 'Genus' }
* parseScientificName(`Genus speciosa var. segunda 'Cultivar' x Genus hybrida`)
* // {
* // genus: 'Genus',
* // species: 'speciosa',
* // infraspecies: [ { rank: 'var.', epithet: 'segunda' } ],
* // cultivar: 'Cultivar',
* // hybrids: [ { genus: 'Genus', species: 'hybrida' } ],
* // hybrid: true
* // }
*/
function parseScientificName(s) {
// Ignore case if string all upper or lower case
let ignoreCase = false
if (s === s.toLowerCase() || s === s.toUpperCase()) {
ignoreCase = true
}
s = cleanName(s)
const parsed = {}
function recurse(node, results) {
for (const key in node) {
const value = node[key]
if (key === 'tags') {
Object.assign(results, value)
continue
}
let pattern = `^${key}(?:$| )`
if (ignoreCase) {
pattern = new RegExp(pattern, 'i')
}
if (parse(pattern, results)) {
if (typeof value === 'string') {
let pattern = `^${value}(?:$| )`
if (ignoreCase) {
pattern = new RegExp(pattern, 'i')
}
parse(pattern, results)
} else if (value) {
recurse(value, results)
}
break
}
}
}
function parse(pattern, results) {
match = s.match(pattern)
if (match) {
if (match.groups) {
Object.assign(results, match.groups)
}
s = s.slice(match.index + match[0].length)
return true
}
return false
}
// Unparsed head
parse(HEAD, parsed)
// Parse
// HACK: Modify string to not require space in case-sensitive scenarios
if (!ignoreCase) {
// xGenus
s = s.replace(/^x([A-Z])/, 'x $1')
// Xspecies
s = s.replace(new RegExp(`^${GENUS} X([a-z])`), '$<genus> X $2')
}
recurse(FIRST, parsed)
// Parse infraspecies
if ('infraspecies' in parsed) {
parsed.infraspecies = parseInfraspecies(parsed.infraspecies)
}
delete parsed['cultivarQuote']
if (Object.keys(parsed).length === 0) {
return { tail: s }
}
// Hybrid formulas
if (!('hybrid' in parsed)) {
const hybrids = []
while (parse(`^(?:[xX×])(?:$| )`, parsed)) {
const temp = {}
recurse(HYBRID, temp)
if ('infraspecies' in temp) {
temp['infraspecies'] = parseInfraspecies(temp['infraspecies'])
}
delete temp['cultivarQuote']
if (Object.keys(temp).length > 0) {
hybrids.push(temp)
}
}
if (hybrids.length > 0) {
parsed.hybrids = hybrids
parsed.hybrid = true
}
}
// Unparsed tail
if (s) {
parsed.tail = s
}
return formatScientificName(parsed)
}
// ---- Class definition ----
/**
* Class representing a scientific name.
*
* @param {ParsedScientificName} obj - Parsed scientific name.
*
* @property {ParsedScientificName} parsed - Parsed scientific name.
* @property {string|object} [input] - Input from which `parsed` was derived.
* @property {object[]} [matches] - Matches from a taxonomic database.
*/
class ScientificName {
constructor(obj) {
this.parsed = formatScientificName(obj)
}
/**
* Build scientific name from string.
*
* @param {string} str
* @return {ScientificName}
* @example
* ScientificName.fromString('Malus pumila')
* // ScientificName {
* // parsed: { genus: 'Malus', species: 'pumila' },
* // input: 'Malus pumila'
* // }
*/
static fromString(str) {
const parsed = parseScientificName(str)
const sciname = new ScientificName(parsed)
sciname.input = str
return sciname
}
/**
* Scientific name fields.
* @private
*/
static _allFields = ['scientific', 'genus', 'species', 'cultivar', 'infraspecies']
/**
* Scientific name fields secondary to `scientific`.
* @private
*/
static _secondaryFields = ['genus', 'species', 'cultivar']
/**
* Build scientific name from feature fields.
*
* @param {object} fields
* @return {ScientificName}
* @example
* ScientificName.fromFields({ scientific: 'Malus pumila', other: 'Bloop' })
* // ScientificName {
* // parsed: { genus: 'Malus', species: 'pumila' },
* // input: { scientific: 'Malus pumila' }
* // }
* ScientificName.fromFields({ genus: 'malus', species: 'PLATANOÏDES' })
* // ScientificName {
* // parsed: { genus: 'Malus', species: 'platanoides' },
* // input: { genus: 'malus', species: 'PLATANOÏDES'}
* // }
*/
static fromFields(obj) {
const inputs = {}
ScientificName._allFields.forEach(key => {
if (obj[key]) {
inputs[key] = obj[key]
}
})
let parsed = { ...inputs }
if (parsed.scientific) {
Object.assign(parsed, parseScientificName(parsed.scientific))
delete parsed.scientific
}
const sciname = new ScientificName(parsed)
sciname.input = inputs
if (sciname.parsed.species && sciname.parsed.species.match(/^([xX×]|hybrid)$/)) {
sciname.parsed.hybrid = true
delete sciname.parsed.species
}
return sciname
}
/**
* Print scientific name to string.
*
* @param {object} options - Print options (see {@link printScientificName}).
* @return {string}
* @example
* ScientificName.fromString(`Malus pumila var. asiatica 'Gala'`).toString()
* // "Malus pumila var. asiatica 'Gala'"
*/
toString(options) {
return printScientificName(this.parsed, options)
}
/**
* Generate compare function for sorting by string representation.
*
* @param {object} options - Print options (see {@link printScientificName}).
* @return {function} Compare function (a, b).
* @example
* l = [new ScientificName({genus: 'Prunus'}), new ScientificName({genus: 'Malus'})]
* l.sort(ScientificName.compareStrings())
* // [
* // ScientificName { parsed: { genus: 'Malus' } },
* // ScientificName { parsed: { genus: 'Prunus' } }
* // ]
*/
static compareStrings(options) {
return function (a, b) {
const s = [a.toString(options), b.toString(options)]
if (s[0] < s[1]) return -1
if (s[0] > s[1]) return 1
return 0
}
}
/**
* Get warnings.
*
* @return {string[]}
* @example
* ScientificName.fromString('... Malus x pumila ...').warnings()
* // [ 'Unparsed head', 'Unparsed tail', 'Hybrid' ]
* ScientificName.fromFields({genus: 'Malus', species: 'pumila', scientific: 'Pyrus communis'}).warnings()
* // [ 'Inconsistent secondary fields: genus, species' ]
*/
warnings() {
const warnings = []
if (this.parsed.head) {
warnings.push('Unparsed head')
}
if (this.parsed.tail) {
warnings.push('Unparsed tail')
}
if (this.parsed.hybrid) {
if (this.parsed.hybridGenus) {
warnings.push('Hybrid genus')
} else if (this.parsed.hybrids) {
warnings.push('Hybrid formula')
} else {
warnings.push('Hybrid')
}
}
if (typeof this.input === 'object' && this.input.scientific) {
const bad = []
ScientificName._secondaryFields.forEach(key => {
if (this.parsed[key] && this.input[key] && this.parsed[key] !== this.input[key]) {
bad.push(key)
}
})
if (bad.length) {
warnings.push(`Inconsistent secondary fields: ${bad.join(', ')}`)
}
}
if (this.matches && this.matches[0]) {
if (this.matches[0].phonetic) {
warnings.push('Phonetic match')
}
if (this.matches[0].fuzzy) {
warnings.push('Fuzzy match')
}
}
return warnings.length ? warnings : undefined
}
/**
* Get errors.
*
* @return {string[]}
* @example
* (new ScientificName({species: 'pumila'})).errors()
* // [ 'Missing genus' ]
*/
errors() {
const errors = []
if (!this.parsed.genus) {
errors.push('Missing genus')
}
if (this.matches) {
if (!this.matches.length) {
errors.push('Missing matches')
} else {
if (this.matches[0].incomplete) {
errors.push('Incomplete match')
}
}
}
return errors.length ? errors : undefined
}
/**
* Get full report.
*
* @return {object}
* @example
* ScientificName.fromString('... Malus x pumila ...').report()
* // {
* // input: '... Malus x pumila ...',
* // parsed: {
* // head: '... ',
* // genus: 'Malus',
* // species: 'pumila',
* // hybrid: true,
* // tail: '...'
* // },
* // warnings: [ 'Unparsed head', 'Unparsed tail', 'Hybrid' ]
* // }
*/
report() {
const errors = this.errors()
const warnings = this.warnings()
return {
...this.input && { input: this.input },
parsed: this.parsed,
...this.matches && this.matches.length && { matches: this.matches },
...errors && { errors: errors },
...warnings && { warnings: warnings }
}
}
}
module.exports = {
parseScientificName,
printScientificName,
ScientificName
}