Просмотр исходного кода

implement command for modes switch based on string similarity

SaltyMonkey лет назад: 6
Родитель
Сommit
dff96a35d9

+ 2 - 1
.gitignore

@@ -3,4 +3,5 @@
 *.bak
 *.bak
 node_modules/*
 node_modules/*
 !node_modules/rfdc/
 !node_modules/rfdc/
-!node_modules/fast-deep-equal/
+!node_modules/fast-deep-equal/
+!node_modules/string-similarity/

+ 11 - 11
lib/unitCommands.js

@@ -10,7 +10,7 @@
  * @typedef {import("../fpsManager.js").deps} deps
  * @typedef {import("../fpsManager.js").deps} deps
 */
 */
 const rfdc = require("rfdc")({ "proto": true });
 const rfdc = require("rfdc")({ "proto": true });
-
+const stringSimilarity = require("string-similarity");
 class unitControl {
 class unitControl {
 	/**
 	/**
 	 *Creates an instance of Control.
 	 *Creates an instance of Control.
@@ -24,7 +24,7 @@ class unitControl {
 
 
 		const helpHandler = () => {
 		const helpHandler = () => {
 			deps.mod.command.message("FPS Manager help.");
 			deps.mod.command.message("FPS Manager help.");
-			
+
 		};
 		};
 
 
 		const autoSettingHandler = () => {
 		const autoSettingHandler = () => {
@@ -43,15 +43,15 @@ class unitControl {
 		};
 		};
 
 
 		const activeModeHandler = (str) => {
 		const activeModeHandler = (str) => {
-			if (deps.data.preset[str]) {
-				deps.data.prevMode = rfdc(deps.data.activeMode);
-				deps.data.activeMode = deps.data.preset[str];
-				deps.mod.command.message(`Mode was changed to "${str}".`);
-				deps.data._eventTrigger();
-			}
-			else {
-				deps.mod.command.message(`Mode "${str}" was not found.`);
-			}
+			let res = stringSimilarity.findBestMatch(str, Object.keys(deps.data.preset.modes));
+
+			// eslint-disable-next-line no-magic-numbers
+			if(res.bestMatch.rating < 0.2) { deps.mod.command.message("Mode was not found"); return; }
+
+			deps.data.prevMode = rfdc(deps.data.activeMode);
+			deps.data.activeMode = deps.data.preset[res.bestMatch.target];
+			deps.mod.command.message(`Mode was changed to "${res.bestMatch.target}".`);
+			deps.data._eventTrigger();
 		};
 		};
 
 
 		const commands = {
 		const commands = {

+ 21 - 0
node_modules/string-similarity/LICENSE

@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2018 Akash Kurdekar
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.

+ 154 - 0
node_modules/string-similarity/README.md

@@ -0,0 +1,154 @@
+string-similarity
+=================
+
+Finds degree of similarity between two strings, based on [Dice's Coefficient](http://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient), which is mostly better than [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance).
+
+## Table of Contents
+
+* [Usage](#usage)
+  + [For Node.js](#for-nodejs)
+  + [For browser apps](#for-browser-apps)
+* [API](#api)
+  + [compareTwoStrings(string1, string2)](#comparetwostringsstring1-string2)
+      * [Arguments](#arguments)
+      * [Returns](#returns)
+      * [Examples](#examples)
+  + [findBestMatch(mainString, targetStrings)](#findbestmatchmainstring-targetstrings)
+      * [Arguments](#arguments-1)
+      * [Returns](#returns-1)
+      * [Examples](#examples-1)
+* [Release Notes](#release-notes)
+  + [2.0.0](#200)
+  + [3.0.0](#300)
+  + [3.0.1](#301)
+  + [4.0.1](#401)
+
+
+## Usage
+
+#### For Node.js
+
+Install using:
+
+```shell
+npm install string-similarity --save
+```
+
+In your code:
+
+```javascript
+var stringSimilarity = require('string-similarity');
+
+var similarity = stringSimilarity.compareTwoStrings('healed', 'sealed'); 
+
+var matches = stringSimilarity.findBestMatch('healed', ['edward', 'sealed', 'theatre']);
+```
+
+#### For browser apps
+
+Include `<script src="//unpkg.com/string-similarity/umd/string-similarity.min.js"></script>` to get the latest version.
+
+Or `<script src="//unpkg.com/string-similarity@4.0.1/umd/string-similarity.min.js"></script>` to get a specific version (4.0.1) in this case.
+
+This exposes a global variable called `stringSimilarity` which you can start using.
+
+```
+<script>
+  stringSimilarity.compareTwoStrings('what!', 'who?');
+</script>
+```
+
+(The package is exposed as UMD, so you can consume it as such)
+
+## API
+
+The package contains two methods:
+
+### compareTwoStrings(string1, string2)
+
+Returns a fraction between 0 and 1, which indicates the degree of similarity between the two strings. 0 indicates completely different strings, 1 indicates identical strings. The comparison is case-sensitive.
+
+##### Arguments
+  
+1. string1 (string): The first string
+2. string2 (string): The second string
+  
+Order does not make a difference.
+  
+##### Returns
+  
+(number): A fraction from 0 to 1, both inclusive. Higher number indicates more similarity.
+
+##### Examples
+  
+```javascript
+stringSimilarity.compareTwoStrings('healed', 'sealed');
+// → 0.8
+
+stringSimilarity.compareTwoStrings('Olive-green table for sale, in extremely good condition.', 
+  'For sale: table in very good  condition, olive green in colour.');
+// → 0.6060606060606061
+
+stringSimilarity.compareTwoStrings('Olive-green table for sale, in extremely good condition.', 
+  'For sale: green Subaru Impreza, 210,000 miles');
+// → 0.2558139534883721
+
+stringSimilarity.compareTwoStrings('Olive-green table for sale, in extremely good condition.', 
+  'Wanted: mountain bike with at least 21 gears.');
+// → 0.1411764705882353
+```
+
+### findBestMatch(mainString, targetStrings)
+
+Compares `mainString` against each string in `targetStrings`.
+
+##### Arguments
+
+1. mainString (string): The string to match each target string against.
+2. targetStrings (Array): Each string in this array will be matched against the main string.
+
+##### Returns
+(Object): An object with a `ratings` property, which gives a similarity rating for each target string, a `bestMatch` property, which specifies which target string was most similar to the main string, and a `bestMatchIndex` property, which specifies the index of the bestMatch in the targetStrings array.
+
+##### Examples
+```javascript
+stringSimilarity.findBestMatch('Olive-green table for sale, in extremely good condition.', [
+  'For sale: green Subaru Impreza, 210,000 miles', 
+  'For sale: table in very good condition, olive green in colour.', 
+  'Wanted: mountain bike with at least 21 gears.'
+]);
+// → 
+{ ratings:
+   [ { target: 'For sale: green Subaru Impreza, 210,000 miles',
+       rating: 0.2558139534883721 },
+     { target: 'For sale: table in very good condition, olive green in colour.',
+       rating: 0.6060606060606061 },
+     { target: 'Wanted: mountain bike with at least 21 gears.',
+       rating: 0.1411764705882353 } ],
+  bestMatch:
+   { target: 'For sale: table in very good condition, olive green in colour.',
+     rating: 0.6060606060606061 },
+  bestMatchIndex: 1 
+}
+```
+
+## Release Notes
+
+### 2.0.0
+* Removed production dependencies
+* Updated to ES6 (this breaks backward-compatibility for pre-ES6 apps)
+
+### 3.0.0
+* Performance improvement for `compareTwoStrings(..)`: now O(n) instead of O(n^2)
+* The algorithm has been tweaked slightly to disregard spaces and word boundaries. This will change the rating values slightly but not enough to make a significant difference
+* Adding a `bestMatchIndex` to the results for `findBestMatch(..)` to point to the best match in the supplied `targetStrings` array
+
+### 3.0.1
+* Refactoring: removed unused functions; used `substring` instead of `substr`
+* Updated dependencies
+
+### 4.0.1
+* Distributing as an UMD build to be used in browsers.
+
+![Build status](https://codeship.com/projects/2aa453d0-0959-0134-8a76-4abcb29fe9b4/status?branch=master)
+[![Known Vulnerabilities](https://snyk.io/test/github/aceakash/string-similarity/badge.svg)](https://snyk.io/test/github/aceakash/string-similarity)

+ 43 - 0
node_modules/string-similarity/package.json

@@ -0,0 +1,43 @@
+{
+  "name": "string-similarity",
+  "version": "4.0.1",
+  "description": "Finds degree of similarity between strings, based on Dice's Coefficient, which is mostly better than Levenshtein distance.",
+  "main": "src/index.js",
+  "scripts": {
+    "test": "jasmine --config=src/spec/support/jasmine.json",
+    "build": "rm -rf umd && webpack-cli",
+    "prepublish": "npm test && npm run build"
+  },
+  "repository": {
+    "type": "git",
+    "url": "git://github.com/aceakash/string-similarity.git"
+  },
+  "keywords": [
+    "strings",
+    "similar",
+    "difference",
+    "similarity",
+    "compare",
+    "comparison",
+    "degree",
+    "match",
+    "matching",
+    "dice",
+    "levenshtein"
+  ],
+  "files": [
+    "src/index.js",
+    "umd/string-similarity.min.js"
+  ],
+  "author": "Akash Kurdekar <npm@kurdekar.com> (http://untilfalse.com/)",
+  "license": "ISC",
+  "devDependencies": {
+    "jasmine": "^3.4.0",
+    "webpack": "^4.41.5",
+    "webpack-cli": "^3.3.10"
+  }
+
+,"_resolved": "https://registry.npmjs.org/string-similarity/-/string-similarity-4.0.1.tgz"
+,"_integrity": "sha512-v36MJzloekKVvKAsYi6O/qpn2mIuvwEFIT9Gx3yg4spkNjXYsk7yxc37g4ZTyMVIBvt/9PZGxnqEtme8XHK+Mw=="
+,"_from": "string-similarity@4.0.1"
+}

+ 69 - 0
node_modules/string-similarity/src/index.js

@@ -0,0 +1,69 @@
+module.exports = {
+	compareTwoStrings,
+	findBestMatch
+};
+
+function compareTwoStrings(first, second) {
+	first = first.replace(/\s+/g, '')
+	second = second.replace(/\s+/g, '')
+
+	if (!first.length && !second.length) return 1;                   // if both are empty strings
+	if (!first.length || !second.length) return 0;                   // if only one is empty string
+	if (first === second) return 1;       							 // identical
+	if (first.length === 1 && second.length === 1) return 0;         // both are 1-letter strings
+	if (first.length < 2 || second.length < 2) return 0;			 // if either is a 1-letter string
+
+	let firstBigrams = new Map();
+	for (let i = 0; i < first.length - 1; i++) {
+		const bigram = first.substring(i, i + 2);
+		const count = firstBigrams.has(bigram)
+			? firstBigrams.get(bigram) + 1
+			: 1;
+
+		firstBigrams.set(bigram, count);
+	};
+
+	let intersectionSize = 0;
+	for (let i = 0; i < second.length - 1; i++) {
+		const bigram = second.substring(i, i + 2);
+		const count = firstBigrams.has(bigram)
+			? firstBigrams.get(bigram)
+			: 0;
+
+		if (count > 0) {
+			firstBigrams.set(bigram, count - 1);
+			intersectionSize++;
+		}
+	}
+
+	return (2.0 * intersectionSize) / (first.length + second.length - 2);
+}
+
+function findBestMatch(mainString, targetStrings) {
+	if (!areArgsValid(mainString, targetStrings)) throw new Error('Bad arguments: First argument should be a string, second should be an array of strings');
+	
+	const ratings = [];
+	let bestMatchIndex = 0;
+
+	for (let i = 0; i < targetStrings.length; i++) {
+		const currentTargetString = targetStrings[i];
+		const currentRating = compareTwoStrings(mainString, currentTargetString)
+		ratings.push({target: currentTargetString, rating: currentRating})
+		if (currentRating > ratings[bestMatchIndex].rating) {
+			bestMatchIndex = i
+		}
+	}
+	
+	
+	const bestMatch = ratings[bestMatchIndex]
+	
+	return { ratings, bestMatch, bestMatchIndex };
+}
+
+function areArgsValid(mainString, targetStrings) {
+	if (typeof mainString !== 'string') return false;
+	if (!Array.isArray(targetStrings)) return false;
+	if (!targetStrings.length) return false;
+	if (targetStrings.find(s => typeof s !== 'string')) return false;
+	return true;
+}

Разница между файлами не показана из-за своего большого размера
+ 0 - 0
node_modules/string-similarity/umd/string-similarity.min.js


+ 5 - 0
package-lock.json

@@ -1126,6 +1126,11 @@
       "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=",
       "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=",
       "dev": true
       "dev": true
     },
     },
+    "string-similarity": {
+      "version": "4.0.1",
+      "resolved": "https://registry.npmjs.org/string-similarity/-/string-similarity-4.0.1.tgz",
+      "integrity": "sha512-v36MJzloekKVvKAsYi6O/qpn2mIuvwEFIT9Gx3yg4spkNjXYsk7yxc37g4ZTyMVIBvt/9PZGxnqEtme8XHK+Mw=="
+    },
     "string-width": {
     "string-width": {
       "version": "4.2.0",
       "version": "4.2.0",
       "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz",
       "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz",

+ 2 - 1
package.json

@@ -21,6 +21,7 @@
   },
   },
   "dependencies": {
   "dependencies": {
     "fast-deep-equal": "^3.1.1",
     "fast-deep-equal": "^3.1.1",
-    "rfdc": "^1.1.4"
+    "rfdc": "^1.1.4",
+    "string-similarity": "^4.0.1"
   }
   }
 }
 }

Некоторые файлы не были показаны из-за большого количества измененных файлов