Converting a JavaScript code using callbacks and RegEx method to equivalent code in C# -


i've below javascript code, returned function callback related user command, user command used in different ways, hence regex required:

(function (undefined) {   "use strict";    var root = this;   var commandslist = [];   var debugstyle = 'font-weight: bold; color: #00f;';    // command matching code modified version of backbone.router jeremy ashkenas, under mit license.   var optionalparam = /\s*\((.*?)\)\s*/g;   var optionalregex = /(\(\?:[^)]+\))\?/g;   var namedparam    = /(\(\?)?:\w+/g;   var splatparam    = /\*\w+/g;   var escaperegexp  = /[\-{}\[\]+?.,\\\^$|#]/g;   var commandtoregexp = function(command) {     command = command.replace(escaperegexp, '\\$&')                   .replace(optionalparam, '(?:$1)?')                   .replace(namedparam, function(match, optional) {                     return optional ? match : '([^\\s]+)';                   })                   .replace(splatparam, '(.*?)')                   .replace(optionalregex, '\\s*$1?\\s*');     return new regexp('^' + command + '$', 'i');   };    var registercommand = function(command, cb, phrase) {     commandslist.push({ command: command, callback: cb, originalphrase: phrase });       root.console.log('command loaded: %c'+phrase, debugstyle);   };  root.fonixlisten = {     addcommands: function(commands) {       var cb;       (var phrase in commands) {         if (commands.hasownproperty(phrase)) {           cb = root[commands[phrase]] || commands[phrase];           if (typeof cb === 'function') {             // convert command regex register command             registercommand(commandtoregexp(phrase), cb, phrase);           } else if (typeof cb === 'object' && cb.regexp instanceof regexp) {             // register command             registercommand(new regexp(cb.regexp.source, 'i'), cb.callback, phrase);           }         }       }     },     executecommand: function(commandtext) {       (var j = 0, l = commandslist.length; j < l; j++) {         var result = commandslist[j].command.exec(commandtext);         if (result) {           var parameters = result.slice(1);           // execute matched command           commandslist[j].callback.apply(this, parameters);           return true;         }       }     }   }; }).call(this) 

below commands:

  var commands = {     'hello :name *term': function(name) {       alert('hello '+name+'');  // i.e. consider *term optional input     },     'items identification': {          'regexp': /^(what is|what's|could please tell me|could please give me) meaning of (tf|ffs|sf|shf|ff|tube film|shrink film|stretch hood|stretch hood film|flat film)$/,          'callback': itemsidentification,    },     'ml soh': {          'regexp': /^(what is|what's|could please tell me|could please give me) (stock|inventory) of ml$/,          'callback': mlsoh,    },      'report stock on hand': {          'regexp': /^(what is|what's) (our|the) (stock|inventory|soh) of (tf|ffs|sf|shf|ff|tube film|shrink film|stretch hood|stretch hood film|flat film)$/,          'callback': soh,         },       'basic mathematical opertions': {                // ?\s? can used instead of space, use /i instead of $/,                 'regexp': /^(what is|what's|calculate|how is) ([\w.]+) (\+|and|plus|\-|less|minus|\*|\x|by|multiplied by|\/|over|divided by) ([\w.]+)$/,                 'callback': math,               },   }; 

at running app, addcommands command executed, , based on input command user, executecommand command executed.

the above works fine me, i'm moving c#, , new it, looking help, @ least guiding of functionalities , tools in c# can me write similar above.

update more details try do, i've form, user input command voice using htl5 voice api, api convert voice text, text submitted app, app work start looking text, trying find required command using reqex, execute programmed function/callback mapped input command.

i found solution using dictionary @ using system.collections.generic; , using regex @ using system.text.regularexpressions; along need of function called firstordefault availabe @ using system.linq;

i used action instead of function func callbacks in case not return anything, i.e. void functions, , because no input parameters provided, used action-delegate, , did not use action<string[]>.

the working code is:

using system; using system.collections.generic;  // dictionary using system.linq;  // firstordefault using system.text.regularexpressions;  // regex  namespace consoleapplication {     public class program     {         public static void main(string[] args)         {             console.writeline("hello world!");              var input = "what's meaning of stretch hood";                      var functions = new dictionary<regex, action>                     {                         {new regex("/^(what is|what's|could please tell me|could please give me) meaning of (tf|ffs|sf|shf|ff|tube film|shrink film|stretch hood|stretch hood film|flat film)$/"),                              itemsidentification},                         {new regex("/^(what is|what's|could please tell me|could please give me) (stock|inventory) of ml$/"),                              mlsoh},                         {new regex("/^(what is|what's) (our|the) (stock|inventory|soh) of (tf|ffs|sf|shf|ff|tube film|shrink film|stretch hood|stretch hood film|flat film)$/"),                              soh},                         {new regex("/^(what is|what's|calculate|how is) ([\w.]+) (\+|and|plus|\-|less|minus|\*|\x|by|multiplied by|\/|over|divided by) ([\w.]+)$/"),                              math},                     };             functions.firstordefault(f => f.key.ismatch(input)).value?.invoke();    // execute first action found wherever input matching regex, ?. means if not null ([null-conditional operators][1]) // or              action action;             action = functions.firstordefault(f => f.key.ismatch(input)).value;             if (action != null)             {                 action.invoke();             }             else             {                 // no function name             }         }          public static void itemsidentification()         {         console.writeline("fn 1");         }          public static void mlsoh()         {         console.writeline("fn 2");         }         public static void soh()         {          }         public static void math()         {          }     } } 

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -