Retrieving a SharePoint app URL using JSOM

At occasions, I need to call apps directly from other scripts. I then need the actual app web URL and cannot launch a dialog to find this.
There are APIs out there to get this but the entire URL must be constructed.
I know the app domain and redirect URL, but need to fetch the app web, i.e. the masquerade URL. To do this, I can use the following snippet:
The key here is to send the app redirect URL together with a part of the app URL to check for. For example, if my app generates a subweb named MyCustomApp and I am hosting the backend in Azure then I would call the method as:
loadAppUrl("", "MyCustomApp");
This method could set a top level parameter, call another method or why not just return a promise with the value. You will then have the full app URL in the following format:
https://[app domain]/[app redirect url]?SPLanguage=[lang]
&SPClientTag=[num]&SPProductNumber=[version]&SPHostUrl=[current URL]
&SPAppWebUrl=[app web]