/**
* Various utilities.
*
* @author Alain Pitiot
* @version 3.0.0b13
* @copyright (c) 2018 Ilixa Ltd. ({@link http://ilixa.com})
* @license Distributed under the terms of the MIT License
*/
/**
* Syntactic sugar for Mixins
*
* [http://justinfagnani.com/2015/12/21/real-mixins-with-javascript-classes/]
*
* class BaseClass { ... }
* let Mixin1 = (superclass) => class extends superclass { ... }
* let Mixin2 = (superclass) => class extends superclass { ... }
* class NewClass extends mix(BaseClass).with(Mixin1, Mixin2) { ... }
*/
export let mix = (superclass) => new MixinBuilder(superclass);
class MixinBuilder {
constructor(superclass) {
this.superclass = superclass;
}
with(...mixins) {
return mixins.reduce((c, mixin) => mixin(c), this.superclass);
}
}
/**
*
* @param {promise} promise - the promise
*/
export function promiseToTupple(promise) {
return promise
.then(data => [null, data])
.catch(error => [error, null]);
}
/**
* Return a Universally Unique Identifier, following RFC4122 version 4
* https://www.ietf.org/rfc/rfc4122.txt
*/
export function makeUuid()
{
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
/**
* Returns the error stack of the calling, exception-throwing function
*
* @return the error stack
*/
export function getErrorStack()
{
try {
throw Error('');
} catch(error) {
// we need to remove the second line since it references getErrorStack:
var stack = error.stack.split("\n");
stack.splice(1, 1);
return JSON.stringify(stack.join('\n'));
}
}
/**
* Tests if x is an 'empty' value.
* @param x the value to test
* @return true if x one of the following: undefined, [], [undefined]
*/
export function isEmpty(x)
{
if (typeof x === 'undefined') return true;
if (!Array.isArray(x)) return false;
if (x.length == 0) return true;
if (x.length == 1 && typeof x[0] === 'undefined') return true;
return false;
}
/**
* Note: since user agent is easily spoofed, we use a more sophisticated approach, as described here:
* https://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
*/
export function detectBrowser()
{
// Opera 8.0+
const isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
if (isOpera) return 'Opera';
// Firefox 1.0+
const isFirefox = typeof InstallTrigger !== 'undefined';
if (isFirefox) return 'Firefox';
// Safari 3.0+ "[object HTMLElementConstructor]"
const isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification));
if (isSafari) return 'Safari';
// Internet Explorer 6-11
const isIE = /*@cc_on!@*/false || !!document.documentMode;
if (isIE) return 'IE';
// Edge 20+
const isEdge = !isIE && !!window.StyleMedia;
if (isEdge) return 'Edge';
// Chrome 1+
const isChrome = !!window.chrome && !!window.chrome.webstore;
if (isChrome) return 'Chrome';
// Blink engine detection
const isBlink = (isChrome || isOpera) && !!window.CSS;
if (isBlink) return 'Blink';
return 'unknown';
}
/**
* Convert obj to its numerical form
* number -> number, e.g. 2 -> 2
* [number] -> [number], e.g. [1,2,3] -> [1,2,3]
* numeral string -> number, e.g. "8" -> 8
* [number | numeral string] -> [number], e.g. [1, 2, "3"] -> [1,2,3]
* otherwise raise an exception
*/
export function toNumerical(obj)
{
let errorPrefix = '{ "origin" : "util.toNumerical", "context" : "when converting an object to its numerical form", "error" : ';
if (typeof obj === 'number')
return obj;
if (typeof obj === 'string')
obj = [obj];
if (Array.isArray(obj)) {
return obj.map( e => {
let n = Number.parseFloat(e);
if (Number.isNaN(n))
throw errorPrefix + '"unable to convert: ' + e + ' to a number."}';
return n;
});
}
}
/**
* Check whether a point lies within a polygon
* We are using the algorithm described here: https://wrf.ecse.rpi.edu//Research/Short_Notes/pnpoly.html
*/
export function IsPointInsidePolygon(point, vertices)
{
let x = point[0], y = point[1];
let isInside = false;
for (var i = 0, j = vertices.length - 1; i < vertices.length; j = i++)
{
const xi = vertices[i][0], yi = vertices[i][1];
const xj = vertices[j][0], yj = vertices[j][1];
const intersect = ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
if (intersect) isInside = !isInside;
}
return isInside;
}
/**
* Shuffle an array in place using the Fisher-Yastes's modern algorithm
* https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
*/
export function shuffle(array)
{
for (let i = array.length - 1; i > 0; i--)
{
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
/**
* Gets the position of the object in pixel unit
* [basevisual.py l. 530]
*/
export function getPositionFromObject(object, units)
{
let response = { origin: 'util.getPositionFromObject', context: 'when getting the position of an object' };
try {
if (typeof object === 'undefined')
throw 'cannot get the position of an undefined object';
let objectWin = undefined;
// object has a getPos function:
if (typeof object.getPos === 'function') {
units = object.units;
objectWin = object.win;
object = object.getPos();
}
// convert object to pixel units:
return to_px(object, units, objectWin);
}
catch (error) {
throw {...response, error };
}
}
/**
* [tools/monitorunittools.py l. 73]
*/
export function to_px(pos, posUnit, win)
{
let response = { origin: 'util.to_px', context: 'when converting a position to pixel units' };
if (posUnit === 'pix')
return pos;
else if (posUnit === 'norm')
return [pos[0] * win.size[0]/2.0, pos[1] * win.size[1]/2.0];
else if (posUnit === 'height') {
const minSize = Math.min(win.size[0], win.size[1]);
return [pos[0] * minSize, pos[1] * minSize];
}
else
throw { ...response, error: `unknown position units: ${posUnit}` };
}
export function to_norm(pos, posUnit, win)
{
let errorPrefix = '{ "origin" : "util.to_norm", "context" : "when converting a position to norm units", "error" : ';
if (posUnit === 'norm')
return pos;
if (posUnit === 'pix')
return [pos[0] / (win.size[0]/2.0), pos[1] / (win.size[1]/2.0)];
if (posUnit === 'height') {
const minSize = Math.min(win.size[0], win.size[1]);
return [pos[0] * minSize / (win.size[0]/2.0), pos[1] * minSize / (win.size[1]/2.0)];
}
throw errorPrefix + '"unknown pos units: ' + posUnit + '" }';
}
export function to_height(pos, posUnit, win)
{
let errorPrefix = '{ "origin" : "util.to_height", "context" : "when converting a position to height units", "error" : ';
if (posUnit === 'height')
return pos;
if (posUnit === 'pix') {
const minSize = Math.min(win.size[0], win.size[1]);
return [pos[0] / minSize, pos[1] / minSize];
}
if (posUnit === 'norm') {
const minSize = Math.min(win.size[0], win.size[1]);
return [pos[0] * win.size[0]/2.0 / minSize, pos[1] * win.size[1]/2.0 / minSize];
}
throw errorPrefix + '"unknown pos units: ' + posUnit + '" }';
}
export function to_win(pos, posUnit, win)
{
let errorPrefix = '{ "origin" : "util.to_win", "context" : "when converting a position to window units", "error" : ';
try {
if (win._units === 'pix')
return to_px(pos, posUnit, win);
if (win._units === 'norm')
return to_norm(pos, posUnit, win);
if (win._units === 'height')
return to_height(pos, posUnit, win);
throw errorPrefix + '"unknown window units: ' + win._units + '" }';
} catch (error) {
throw errorPrefix + error + '}';
}
}
export function to_unit(pos, posUnit, win, targetUnit)
{
let errorPrefix = '{ "origin" : "util.to_unit", "context" : "when converting a position to a different unit", "error" : ';
try {
if (targetUnit === 'pix')
return to_px(pos, posUnit, win);
if (targetUnit === 'norm')
return to_norm(pos, posUnit, win);
if (targetUnit === 'height')
return to_height(pos, posUnit, win);
throw errorPrefix + '"unknown target units: ' + targetUnit + '" }';
} catch (error) {
throw errorPrefix + error + '}';
}
}
/**
* Convert a position to a PIXI Point
*
* @param {*} pos
* @param {*} posUnit
* @param {*} win
*/
export function to_pixiPoint(pos, posUnit, win)
{
const pos_px = to_px(pos, posUnit, win);
return new PIXI.Point(pos_px[0], pos_px[1]);
}
/**
* Convert an object to its string representation
*/
export function toString(object)
{
if (typeof object === 'string')
return object;
try {
return JSON.stringify(object);
} catch (e)
{
return 'Object (circular)';
}
}
if (!String.prototype.format) {
String.prototype.format = function() {
var args = arguments;
return this
.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
})
.replace(/{([$_a-zA-Z][$_a-zA-Z0-9]*)}/g, function(match, name) {
//console.log("n=" + name + " args[0][name]=" + args[0][name]);
return args.length > 0 && args[0][name] !== undefined
? args[0][name]
: match
;
});
};
}
/**
* Return whether the value is an integer or a string representing an integer
* [https://stackoverflow.com/a/14794066]
*/
export function isInt(value) {
if (isNaN(value)) {
return false;
}
const x = parseFloat(value);
return (x | 0) === x;
}
/**
* Get the URL parameters
* returns an iteratable URLSearchParams
*
* example:
* const urlParameters = util.getUrlParameters();
* for (const [key, value] of urlParameters)
* console.log(key + ' = ' + value);
*
*/
export function getUrlParameters()
{
const urlQuery = window.location.search.slice(1);
return new URLSearchParams(urlQuery);
/*let urlMap = new Map();
for (const entry of urlParameters)
urlMap.set(entry[0], entry[1])
return urlMap;*/
}
/**
* Add info extracted from the URL to the given dictionary
*
* @param {*} info
*/
export function addInfoFromUrl(info)
{
const infoFromUrl = getUrlParameters();
for (const [key, value] of infoFromUrl)
info[key] = value;
return info;
}
function createHtml(htmlCode) {
var fragment = document.createDocumentFragment();
var element = document.createElement('div');
element.innerHTML = htmlCode;
while (element.firstChild) {
fragment.appendChild(element.firstChild);
}
return fragment;
}
/**
* Select values from an array.
*
* <p> 'selection' can be a single integer, an array of indices, or a string to be parsed, e.g.:
* 5
* [1,2,3,10]
* '1,5,10'
* '1:2:5'
* '5:'
* '-5:-2, 9, 11:5:22'
*
* @param {Array.<Object>} array - the input array
* @param {number | Array.<number> | string} selection - the selection
* @returns {Array.<Object>} the array of selected items
*/
export function selectFromArray(array, selection) {
// if selection is an integer, or a string representing an integer, we treat it as an index in the array
// and return that entry:
if (isInt(selection))
return [array[parseInt(selection)]];
// if selection is an array, we treat it as a list of indices
// and return an array with the entries corresponding to those indices:
else if (Array.isArray(selection))
return array.filter( (e,i) => (selection.includes(i)) );
// if selection is a string, we decode it:
else if (typeof selection === 'string') {
if (selection.indexOf(',') > -1)
return flattenArray( selection.split(',').map(a => selectFromArray(array, a)) );
else if (selection.indexOf(':') > -1) {
let sliceParams = selection.split(':').map(a => parseInt(a));
if (sliceParams.length === 3)
return sliceArray(array, sliceParams[0], sliceParams[2], sliceParams[1]);
else
return sliceArray(array, ...sliceParams);
}
}
else
throw { origin: 'selectFromArray', context: 'when selecting entries from an array', error: 'unknown selection type: ' + (typeof selection)};
}
/**
* Recursively flatten an array of arrays
*/
function flattenArray(array) {
return array.reduce( (flat, next) => flat.concat(Array.isArray(next) ? flattenArray(next) : next), [] );
}
/**
* Slice an array
*/
function sliceArray(array, from = NaN, to = NaN, step = NaN)
{
if (isNaN(from)) from = 0;
if (isNaN(to)) to = array.length;
let arraySlice = array.slice(from, to);
if (isNaN(step))
return arraySlice;
if (step < 0)
arraySlice.reverse();
step = Math.abs(step);
if (step == 1)
return arraySlice;
else
return arraySlice.filter( (e,i) => (i % step == 0) );
}
/**
* Uses ``time.strftime()``_ to generate a string of the form
* 2012_Apr_19_1531 for 19th April 3.31pm, 2012.
* This is often useful appended to data filenames to provide unique names.
* To include the year: getDateStr(format="%Y_%b_%d_%H%M") returns '2011_Mar_16_1307'
* depending on locale, can have unicode chars in month names, so utf_8_decode them
* For date in the format of the current localization, do:
* data.getDateStr(format=locale.nl_langinfo(locale.D_T_FMT))
*/
function getDateStr()
{
return new Date().toString();
}