Keep the case of a noun when making it singular

This commit is contained in:
dualfroz committed 2026-09-23 12:36:14 +02:00
1 parent 064b048c83
commit a29ba6095c
2 files changed
+34 -1

No files matched your search

+20 -1
View File
@@ -1,5 +1,16 @@
const keep = { tags: true } const keep = { tags: true }
// give 'dane' the case of the word it replaced: 'Danes' -> 'Dane', 'DANES' -> 'DANE'
const matchCase = function (original, str) {
if (original.length > 1 && original === original.toUpperCase() && original !== original.toLowerCase()) {
return str.toUpperCase()
}
if (/^\p{Lu}/u.test(original)) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
return str
}
const nounToSingular = function (m, parsed) { const nounToSingular = function (m, parsed) {
// already singular? // already singular?
if (parsed.isPlural === false) { if (parsed.isPlural === false) {
@@ -10,7 +21,15 @@ const nounToSingular = function (m, parsed) {
// inflect the root noun // inflect the root noun
const str = parsed.root.text('normal') const str = parsed.root.text('normal')
const single = toSingular(str, model) const single = toSingular(str, model)
m.replace(parsed.root, single, keep).tag('Singular', 'toPlural') const before = (parsed.root.docs[0] || []).map(term => term.text)
const after = m.replace(parsed.root, single, keep).tag('Singular', 'toPlural')
// the conversion works on the normalized text, so put the original case back
const terms = after.docs[0] || []
if (terms.length === before.length) {
terms.forEach((term, i) => {
term.text = matchCase(before[i], term.text)
})
}
// should we change the determiner/article? // should we change the determiner/article?
// m.debug() // m.debug()
return m return m
+14
View File
@@ -257,3 +257,17 @@ test('toSingular - longer:', function (t) {
}) })
t.end() t.end()
}) })
test('toSingular - keeps case:', function (t) {
const arr = [
[`Those are Great Danes`, `Those are Great Dane`],
[`The Children played`, `The Child played`],
[`I saw Mice`, `I saw Mouse`],
[`I saw MICE`, `I saw MOUSE`],
]
arr.forEach(function (a) {
const doc = nlp(a[0])
doc.nouns().toSingular()
t.equal(doc.text(), a[1], here + '[case] ' + a[0])
})
t.end()
})