User:Inductiveload/Useful functions

Load wikitext from a page
Use in an async function and "await" the result.

function extract_wikitext(revisions_json) { if (!revisions_json.query.pages["-1"]) { var content = revisions_json.query.pages[0].revisions[0].content; return content; }   return null; }

function load_wikitext(title) { // load donor wikitext var rq_promise = $.ajax({     type: "GET",      url: mw.util.wikiScript('api'),      data: {        'action': 'query',        'prop': 'revisions',        'rvprop': 'content',        'titles': title,        'formatversion': 2,        'format': 'json'      },      dataType: 'json'    });

return new Promise(function(resolve, reject) {     rq_promise.then(function(jsondata) { const content = extract_wikitext(jsondata); if (content) { resolve(content); } else { reject(content); }     });    });  }

Find first block of matching braces in string
var find_matching_brace = function(str) { var depth = 0; var first = -1;

for (var i = 0; i < str.length; i++) { var c = str[i];

if (c === '{') { if (first == -1) { first = i;       } depth += 1; } else if (c === '}') { depth -= 1; }

if (first !== -1 && depth === 0) { return [first, i]; }   }

// no match return null; };

Steal an accesskey from the current owner
function stealAccessKey(accessKey) { var previousTarget = $('[accesskey="' + accessKey.replace('"', '\\"') + '"]');   if (previousTarget.length) { console.log("overwrote access key [" + accessKey +       '] previously assigned to "' + previousTarget.text + '".'); previousTarget.removeAttr("accesskey"); } };