Get & Remove Random Sentence from List [Example] Macro (v9.0.2)

MACRO:   Get & Remove Random Sentence from List [Example]

~~~ VER: 1.0    2019-09-17 ~~~
Requires: KM 9.0.2+   macOS 10.11 (El Capitan)+
(Macro was written & tested using KM 9.0+ on macOS 10.14.5 (Mojave))

DOWNLOAD Macro File:

Get & Remove Random Sentence from List [Example].kmmacros
Note: This Macro was uploaded in a DISABLED state. You must enable before it can be triggered.


Example Output

image


Implementation Note

I wanted to use all native non-script KM Actions, but there was just no easy way (that I know of) to remove a selected line from a list of lines. Yes, I know I could have used a For Each, but that seems too clumsy and verbose to me, when JXA can easily randomly select the line and remove it.

I welcome all suggestions for improvements to this macro.


ReleaseNotes

Author.@JMichaelTX

PURPOSE:

  • Get & Remove a Random Line from List of Questions

HOW TO USE

  1. First, make sure you have followed instructions in the Macro Setup below.
  2. Trigger this macro.

MACRO SETUP

  • Carefully review the Release Notes and the Macro Actions
    • Make sure you understand what the Macro will do.
    • You are responsible for running the Macro, not me. ??
      .
      Make These Changes to this Macro
  1. Assign a Trigger to this macro.
  2. Move this macro to a Macro Group that is only Active when you need this Macro.
  3. ENABLE this Macro, and the Macro Group it is in.
    .
  • REVIEW/CHANGE THE FOLLOWING MACRO ACTIONS:
    (all shown in the magenta color)

Actions are provided to EITHER

  • enter the Question in the Set Variable Action,
    OR,
  • Read the Questions from a File.

Enable/Disable the Below Actions accordingly.

  • Replace with Your Master List of Questions.
  • REPLACE File Path with Path to Your Master List of Questions

REQUIRES:

  1. KM 9.0+
  2. macOS 10.11.6 (El Capitan)+

TAGS: @Random @Lists @JXA @JavaScript

USER SETTINGS:

  • Any Action in magenta color is designed to be changed by end-user

ACTION COLOR CODES

  • To facilitate the reading, customizing, and maintenance of this macro,
    key Actions are colored as follows:
  • GREEN -- Key Comments designed to highlight main sections of macro
  • MAGENTA -- Actions designed to be customized by user
  • YELLOW -- Primary Actions (usually the main purpose of the macro)
  • ORANGE -- Actions that permanently destroy Variables or Clipboards,
    OR IF/THEN and PAUSE Actions

USE AT YOUR OWN RISK

  • While I have given this a modest amount of testing, and to the best of my knowledge will do no harm, I cannot guarantee it.
  • If you have any doubts or questions:
    • Ask first
    • Turn on the KM Debugger from the KM Status Menu, and step through the macro, making sure you understand what it is doing with each Action.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

JXA Script

'use strict';  // See http://www.w3schools.com/js/js_strict.asp
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

(function myMain() {    // ~~~ automatically executed when this script is executed ~~~
  
var ptyScriptName   = "Get & Remove Random Line from String List"
var ptyScriptVer     = "1.0"
var ptyScriptDate   = "2019-09-17"
var ptyScriptAuthor = "JMichaelTX"
/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PURPOSE:  Get & Remove a Random Line from a String List (KM Variable)

RETURNS:  One of these, as text:
  • Actual Results of script if all goes well
    • The line that was removed.
    
  • "[USER_CANCELED]" at start of results if the user canceled something
  • "[ERROR]" at start of results if a script error occurred.
  
KM VARIABALES REQUIRED:
  • Local__CurrentList
  
KM VARIABLES SET:
  • Local__CurrentList
  
REF:
  • 
~~~~~~~~~~~~~~~~~~~ END HEADER COMMENTS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
var app = Application.currentApplication()
app.includeStandardAdditions = true

var scriptResults = "OK"  // Set your results to this var


try {  //~~~~~~~~~~~ START TRY ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  
  //  Use this to throw custom error:
  //  throw new Error("Your_Error_Message");
  

var kmInst = app.systemAttribute("KMINSTANCE");
var kmeApp = Application("Keyboard Maestro Engine")
 
var stringList = kmeApp.getvariable("Local__CurrentList",  {instance: kmInst});

//----- NOW, CONVERT String List to Array ---

var arrayList = stringList.split("\n");
var numItems  = arrayList.length;
var randomIndex = getRandomInt(1, numItems) - 1;
var randomItem = arrayList[randomIndex];

//--- Remove Item from List ---
arrayList.splice(randomIndex, 1);
var stringListRev   = arrayList.join('\n')

//~~~~ UPDATE KM VARIABLE With Selected Item Removed ~~~~
kmeApp.setvariable("Local__CurrentList", {instance: kmInst, to: stringListRev})

scriptResults =  randomItem

  
} //~~~~ END TRY ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

catch (oError) {
  
  //console.log(oError);
  
  if (oError.errorNumber === -128) {  // User Canceled
  
    scriptResults =  "[USER_CANCELED]\n\n"
      + "SCRIPT: " + ptyScriptName + "   Ver: " + ptyScriptVer
  }
  
  else {
    var errNum = oError.errorNumber || "Custom Error";
    scriptResults = "[ERROR]\n\n"
      + "SCRIPT: " + ptyScriptName + "   Ver: " + ptyScriptVer + "\n"
      + "Error Number: " + errNum + "\n"
      + oError.message
      
      var errMsg = oError.message;
      
      app.displayNotification(
        errMsg, 
        {
          withTitle: ptyScriptName,
          subtitle:  '[ERROR] Macro CANCELLED',
          soundName: "Glass"
        })
        
      throw new Error(errMsg);

      
  } // END if/else on ERROR Number
  
} //~~~~ END TRY/CATCH BLOCK ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


//--- RETURN ---
return scriptResults

//=============== END OF MAIN SCRIPT =======================================


function getRandomInt(min, max) {
  max += 1;
  return Math.floor(Math.random() * (max - min) ) + min;
}


})();  // ~~~ function myMain() is automatically executed when this script is executed ~~~


1 Like