[gnome-maps/wip/mlundblad/wikidata: 2/3] wikipedia: Add function to validate a Wikidata reference




commit 3c5dbd930ab0ee3a4736ea10002bdf2d1010996e
Author: Marcus Lundblad <ml dfupdate se>
Date:   Fri Oct 7 23:21:37 2022 +0200

    wikipedia: Add function to validate a Wikidata reference

 src/wikipedia.js       | 12 ++++++++++++
 tests/wikipediaTest.js | 10 ++++++++++
 2 files changed, 22 insertions(+)
---
diff --git a/src/wikipedia.js b/src/wikipedia.js
index 38a7c0c4..245f04c7 100644
--- a/src/wikipedia.js
+++ b/src/wikipedia.js
@@ -32,6 +32,11 @@ import * as Utils from './utils.js';
  */
 const WP_REGEX = /^[a-z][a-z][a-z]?(\-[a-z]+)?$|^simple$/;
 
+/**
+ * Regex matching Wikidata tags
+ */
+const WIKIDATA_REGEX = /Q\d+/;
+
 let _soupSession = null;
 function _getSoupSession() {
     if (_soupSession === null) {
@@ -74,6 +79,13 @@ export function isValidWikipedia(wiki) {
     return wpCode.match(WP_REGEX) !== null;
 }
 
+/**
+ * Determine if a Wikidata reference tag is valid (of the form Qnnn)
+ */
+export function isValidWikidata(wikidata) {
+    return wikidata.match(WIKIDATA_REGEX) !== null;
+}
+
 /*
  * Fetch various metadata about a Wikipedia article, given the wiki language
  * and article title.
diff --git a/tests/wikipediaTest.js b/tests/wikipediaTest.js
index 29e6086a..09212f23 100644
--- a/tests/wikipediaTest.js
+++ b/tests/wikipediaTest.js
@@ -38,3 +38,13 @@ JsUnit.assertTrue(Wikipedia.isValidWikipedia('zh-yue:粵文維基百科'));
 // invalid references
 JsUnit.assertFalse(Wikipedia.isValidWikipedia('https://en.wikipedia.org/wiki/Article'));
 JsUnit.assertFalse(Wikipedia.isValidWikipedia('Article with no edition'));
+
+// valid wikidata references
+JsUnit.assertTrue(Wikipedia.isValidWikidata('Q1234'));
+JsUnit.assertTrue(Wikipedia.isValidWikidata('Q1'));
+JsUnit.assertTrue(Wikipedia.isValidWikidata('Q100000000'));
+
+// invalid wikidata references
+JsUnit.assertFalse(Wikipedia.isValidWikidata('1234'));
+JsUnit.assertFalse(Wikipedia.isValidWikidata('AAAA'));
+JsUnit.assertFalse(Wikipedia.isValidWikidata('en:Article'));


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]