Convert Dialogfow duration system entity from minutes to seconds in JavaScript

前端 未结 1 1828
失恋的感觉
失恋的感觉 2021-01-28 04:13

I am looking for ways to convert a Duration (@sys.duration) system entity from Dialogflow in JavaScript code from minutes to seconds.

I ask the user for a certain durati

相关标签:
1条回答
  • 2021-01-28 04:21

    The @sys.duration system entity will send you an Object with two attributes, "amount" which contains an integer, and "unit" which contains a string.

    So in Javascript, this would be represented something like:

    {
      "amount": 20,
      "unit": "min"
    }
    

    To convert this to seconds, you would lookup how many seconds are in the "unit" provided and multiply it by the amount.

    A good way to do this lookup would be to create an object that has, as attributes, the possible unit names and as values the number of seconds. This works well for most units up to a week. When you hit a month or a year (or longer), however, you run into trouble since the number of seconds for these periods can be variable. To represent these, I'll mark these as a negative number, so you can check if the conversion failed. (I'm ignoring issues with clock changes such as due to Daylight Saving Time / Summer Time.)

    I haven't fully tested this code, but it appears to be correct. This function lets you pass the object sent in the the_duration parameter and will return the number of seconds:

    function durationToSeconds( duration ){
      const mult = {
        "s":      1,
        "min":    60,
        "h":      60*60,
        "day":    60*60*24,
        "wk":     60*60*24*7,
        "mo":     -1,
        "yr":     -1,
        "decade": -1
      };
      return duration.amount * mult[duration.unit];
    }
    

    Extracting the number from the string is certainly possible, and you can adapt this function to work that way, but since Dialogflow already gives it to you as an object with normalized strings, it would be significantly more difficult.

    0 讨论(0)
提交回复
热议问题