maplair
Version:
JavaScript library for mobile-friendly interactive maps
156 lines (155 loc) • 5.21 kB
JavaScript
import { __exportAll } from "../_virtual/_rolldown/runtime.js";
// src/core/Util.js
var Util_exports = /* @__PURE__ */ __exportAll({
falseFn: () => falseFn,
formatNum: () => formatNum,
lastId: () => lastId,
setOptions: () => setOptions,
splitWords: () => splitWords,
stamp: () => stamp,
template: () => template,
throttle: () => throttle,
toNumber: () => toNumber,
wrapNum: () => wrapNum
});
/**
* Last unique ID used by [`stamp()`](#util-stamp).
* @type {number}
*/
let lastId = 0;
/**
* Returns the unique ID of an object, assigning it one if it doesn't have it.
* @param {object} obj
* @returns {number}
*/
function stamp(obj) {
if (!("_maplair_id" in obj)) obj["_maplair_id"] = ++lastId;
return obj._maplair_id;
}
/**
* Returns a function which executes function `fn` with the given scope `context`
* (so that the `this` keyword refers to `context` inside `fn`'s code). The function
* `fn` will be called no more than one time per given amount of `time`. The arguments
* received by the bound function will be any arguments passed when binding the
* function, followed by any arguments passed when invoking the bound function.
* @param {(...args: any[]) => void} fn
* @param {number} time In milliseconds.
* @param {object} [context]
* @returns {(...args: any[]) => void}
*/
function throttle(fn, time, context) {
let lock, queuedArgs;
function later() {
lock = false;
if (queuedArgs) {
wrapperFn.apply(context, queuedArgs);
queuedArgs = false;
}
}
function wrapperFn(...args) {
if (lock) queuedArgs = args;
else {
fn.apply(context, args);
setTimeout(later, time);
lock = true;
}
}
return wrapperFn;
}
/**
* Returns the number `x` modulo `range` in such a way so it lies within
* `range[0]` and `range[1]`. The returned value will always be smaller than
* `range[1]` unless `includeMax` is set to `true`.
* @param {number} x
* @param {[number, number]} range
* @param {boolean} [includeMax]
* @returns {number}
*/
function wrapNum(x, range, includeMax) {
const max = range[1], min = range[0], d = max - min;
return x === max && includeMax ? x : ((x - min) % d + d) % d + min;
}
/**
* A function which always returns `false`.
* @returns {false}
*/
function falseFn() {
return false;
}
/**
* Returns the number `num` rounded with specified `precision`.
* The default `precision` value is 6 decimal places.
* `false` can be passed to skip any processing (can be useful to avoid round-off errors).
* @param {number} num
* @param {number|false} [precision]
* @returns {number}
*/
function formatNum(num, precision = 6) {
if (precision === false) return num;
const pow = 10 ** precision;
return Math.round(num * pow) / pow;
}
/**
* Returns `value` if it's a number (including `Infinity`), converts it if it's a
* numeric string, and returns `NaN` for anything else, unlike `Number()`, which turns
* `''`, `null` and booleans into `0` or `1`.
* @param {unknown} value
* @returns {number}
*/
function toNumber(value) {
return typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? +value : NaN;
}
const WHITESPACE_RE = /\s+/;
/**
* Trims and splits the string on whitespace and returns the array of parts.
* @param {string} str
* @returns {string[]}
*/
function splitWords(str) {
const trimmed = str.trim();
return WHITESPACE_RE.test(trimmed) ? trimmed.split(WHITESPACE_RE) : [trimmed];
}
/**
* Merges the given properties to the `options` of the `obj` object, returning the
* resulting options. See `Class options`.
* @param {object} obj
* @param {object} [options]
* @returns {object}
*/
function setOptions(obj, options) {
if (!Object.hasOwn(obj, "options")) {
const defaults = getDefaultOptions(obj.constructor) ?? obj.options;
obj.options = defaults ? Object.create(defaults) : {};
}
for (const i in options) if (Object.hasOwn(options, i)) obj.options[i] = options[i];
return obj.options;
}
const chainedDefaults = /* @__PURE__ */ new WeakMap();
function getDefaultOptions(cls) {
const defaults = cls?.defaultOptions;
if (defaults && chainedDefaults.get(cls) !== defaults) {
for (let c = cls; c.defaultOptions; c = Object.getPrototypeOf(c)) if (Object.hasOwn(c, "defaultOptions")) Object.setPrototypeOf(c.defaultOptions, Object.getPrototypeOf(c).defaultOptions ?? Object.prototype);
chainedDefaults.set(cls, defaults);
}
return defaults;
}
const templateRe = /\{ *([\w_ -]+?) *\}/g;
/**
* Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`
* and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string
* `('Hello foo, bar')`. You can also specify functions instead of strings for
* data values — they will be evaluated passing `data` as an argument.
* @param {string} str
* @param {Record<string, any>} data
* @returns {string}
*/
function template(str, data) {
return str.replace(templateRe, (str, key) => {
let value = data[key];
if (value === void 0) throw new Error(`No value provided for variable ${str}`);
else if (typeof value === "function") value = value(data);
return value;
});
}
export { Util_exports, falseFn, formatNum, lastId, setOptions, splitWords, stamp, template, throttle, toNumber, wrapNum };
//# sourceMappingURL=Util.js.map