ems-web-app-utils
Version:
Utility methods that are intended for use in Angular.io [web applications developed by Educational Media Solutions](https://github.com/spencech/ems-web-app-template)
330 lines (323 loc) • 11.8 kB
JavaScript
import * as i0 from '@angular/core';
import { Injectable, Component, NgModule } from '@angular/core';
import { __awaiter } from 'tslib';
import * as _ from 'underscore';
class UtilsService {
constructor() { }
}
UtilsService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.2.7", ngImport: i0, type: UtilsService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
UtilsService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.2.7", ngImport: i0, type: UtilsService, providedIn: 'root' });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.2.7", ngImport: i0, type: UtilsService, decorators: [{
type: Injectable,
args: [{
providedIn: 'root'
}]
}], ctorParameters: function () { return []; } });
class UtilsComponent {
constructor() { }
ngOnInit() {
}
}
UtilsComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.2.7", ngImport: i0, type: UtilsComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
UtilsComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "13.2.7", type: UtilsComponent, selector: "lib-utils", ngImport: i0, template: `
<p>
utils works!
</p>
`, isInline: true });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.2.7", ngImport: i0, type: UtilsComponent, decorators: [{
type: Component,
args: [{
selector: 'lib-utils',
template: `
<p>
utils works!
</p>
`,
styles: []
}]
}], ctorParameters: function () { return []; } });
function alphabetize(...parameters) {
if (typeof parameters[0] === 'string') {
// if this method is supplied as a callback to Array.sort
const a = parameters[0];
const b = parameters[1];
if (a > b)
return 1;
if (a < b)
return -1;
return 0;
}
else {
// if we're sorting a list with a supplied key to alphabetize
const list = parameters[0];
const property = parameters[1];
list.sort((a, b) => {
if (a[property] > b[property])
return 1;
if (a[property] < b[property])
return -1;
return 0;
});
return list;
}
}
function clone(obj) {
if (obj === null || obj === undefined)
return obj;
return JSON.parse(JSON.stringify(obj));
}
function convertToEST(date) {
const gmtDate = new Date(date + " GMT");
const options = {
timeZone: 'America/New_York',
year: "numeric",
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: true
};
const formatter = new Intl.DateTimeFormat('en-US', options);
return formatter.format(gmtDate);
}
function dateStrings(date) {
date = date || new Date();
return {
year: date.getFullYear(),
month: (date.getMonth() + 1).toString().padStart(2, '0'),
date: date.getDate().toString().padStart(2, '0'),
time: `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`,
seconds: date.getSeconds().toString().padStart(2, '0'),
};
}
function delay(method, ms = 0) {
return window.setTimeout(method, ms);
}
function download(content, name, extension = 'csv') {
const blob = new Blob([content]);
name = kebab(name);
if (window.navigator.msSaveOrOpenBlob)
window.navigator.msSaveBlob(blob, `${name}.${extension}`);
else {
const a = window.document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = `${name}.${extension}`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
}
function empty(e) {
return falsy(e);
}
function enumKeys(obj) {
return Object.keys(obj).filter(k => Number.isNaN(+k));
}
function enumValues(obj) {
const output = [];
for (const value of enumKeys(obj)) {
output.push(obj[value]);
}
return output;
}
function falsy(e) {
if (typeof e === 'string' && trim(e).match(/^false$/i))
return true;
if (typeof e === 'string')
return _.isEmpty(e.replace(/\s+/gim, ''));
if (typeof e === 'boolean')
return e === false;
if (!isNaN(parseInt(e, 10)))
return e === 0;
return _.isEmpty(e);
}
function focus(selector) {
const element = document.querySelector(selector);
if (!element || !element.focus)
return 0;
return delay(() => element.focus());
}
function getLargestRemainder(values, desiredSum) {
let sum = 0;
let valueParts = values.map((value, index) => {
const integerValue = value || 0;
sum += integerValue;
return {
integer: integerValue,
decimal: value % 1,
originalIndex: index,
};
});
if (sum !== desiredSum && sum) {
valueParts = valueParts.sort((a, b) => b.decimal - a.decimal);
const diff = desiredSum - sum;
let i = 0;
while (i < diff) {
valueParts[i].integer++;
i++;
}
}
return valueParts.sort((a, b) => a.originalIndex - b.originalIndex).map((p) => p.integer);
}
function getparams(requestedProperty) {
const vars = {};
const parts = window.location.href.replace(/[?&#]+([^=&]+)=([^&]*)/gi, ((m, key, value) => {
vars[key] = value;
}));
for (const prop in vars) {
if (vars[prop].toLowerCase() === 'true')
vars[prop] = true;
else if (vars[prop].toLowerCase() === 'false')
vars[prop] = false;
else if (!isNaN(parseFloat(vars[prop])) && !vars[prop].match(/[^0-9]+/gim))
vars[prop] = parseFloat(vars[prop]);
}
if (requestedProperty)
return vars[requestedProperty];
return vars;
}
function isset(e) {
return truthy(e);
}
function kebab(e) {
if (_.isEmpty(e))
return e;
return e.toLowerCase().replace(/\s+/gim, '-').replace(/_/g, '-').replace(/-+/g, '-');
}
function paginate(method, offset, limit, key, output = [], callback, prevResolve) {
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
let response;
try {
response = yield method(offset, limit);
}
catch (e) {
reject(e);
}
output = output.concat(response[key]);
if (callback)
callback(output, response[key]);
if (response.nextPage) {
yield paginate(method, response.nextPage, limit, key, output, callback, prevResolve !== null && prevResolve !== void 0 ? prevResolve : resolve);
}
else {
(prevResolve !== null && prevResolve !== void 0 ? prevResolve : resolve)(output);
}
}));
}
function prepareSearchString(value) {
if (!value)
return "";
return value.toLowerCase().replace(/\s+/gim, "");
}
function replaceItem(array, item, key = 'id', position = 'current') {
const lookup = {};
lookup[key] = item[key];
const oldItem = _.findWhere(array, lookup);
if (!oldItem) {
array.unshift(item);
return item;
}
const index = array.indexOf(oldItem);
if (position === 'first') {
array.splice(index, 1);
array.unshift(item);
}
else {
array.splice(index, 1, item);
}
return item;
}
function sleep(duration = 0) {
return new Promise((resolve) => {
delay(() => resolve(duration), duration);
});
}
function snakecase(e) {
if (_.isEmpty(e))
return e;
return e.toLowerCase().replace(/\s+/gim, '_').replace(/-/g, '_').replace(/_+/g, '_');
}
function tick(returnValue) {
return new Promise((resolve, reject) => {
delay(() => resolve(returnValue));
});
}
function timestamp(date, includeTime = true) {
const info = dateStrings(date);
const time = ` ${info.time}:${info.seconds}`;
return `${info.year}-${info.month}-${info.date}${includeTime ? time : ''}`;
}
function trace(...parameters) {
if (!getparams().debug)
return;
for (let i = 0, count = parameters.length; i < count; i++) {
// tslint:disable-next-line
console.log(parameters[i]);
}
}
function trim(e) {
if (_.isEmpty(e))
return e;
return e.replace(/^\s+/, '').replace(/\s+$/, '');
}
function truthy(e) {
return !falsy(e);
}
function validateEmail(email) {
if (!email)
return null;
return String(email)
.toLowerCase()
.match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
}
function viewport(el, percentVisible = 100) {
const rect = el.getBoundingClientRect();
const windowHeight = window.innerHeight || document.documentElement.clientHeight;
return !(Math.floor(100 - ((rect.top >= 0 ? 0 : rect.top) / +-(rect.height / 1)) * 100) < percentVisible ||
Math.floor(100 - ((rect.bottom - windowHeight) / rect.height) * 100) < percentVisible);
}
function password(length) {
const upperCaseChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const lowerCaseChars = 'abcdefghijklmnopqrstuvwxyz';
const numbers = '0123456789';
const specialChars = '!@#$%^&*()-_=+[]|;:,.?';
length = length !== null && length !== void 0 ? length : 8;
// Ensure each type of character appears at least once
const password = [
upperCaseChars[Math.floor(Math.random() * upperCaseChars.length)],
lowerCaseChars[Math.floor(Math.random() * lowerCaseChars.length)],
numbers[Math.floor(Math.random() * numbers.length)],
specialChars[Math.floor(Math.random() * specialChars.length)], // One special char
];
// Pool of all allowed characters for remaining password characters
const allChars = upperCaseChars + lowerCaseChars + numbers + specialChars;
// Fill the rest of the password length (64 characters) with random characters
for (let i = password.length; i < length; i++) {
password.push(allChars[Math.floor(Math.random() * allChars.length)]);
}
// Shuffle the password array to ensure randomness, then join it into a string
const randomPassword = password.sort(() => Math.random() - 0.5).join('');
return randomPassword;
}
class UtilsModule {
}
UtilsModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.2.7", ngImport: i0, type: UtilsModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
UtilsModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "13.2.7", ngImport: i0, type: UtilsModule });
UtilsModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "13.2.7", ngImport: i0, type: UtilsModule, imports: [[]] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.2.7", ngImport: i0, type: UtilsModule, decorators: [{
type: NgModule,
args: [{
declarations: [],
imports: [],
exports: []
}]
}] });
/*
* Public API Surface of utils
*/
/**
* Generated bundle index. Do not edit.
*/
export { UtilsComponent, UtilsModule, UtilsService, alphabetize, clone, convertToEST, dateStrings, delay, download, empty, enumKeys, enumValues, falsy, focus, getLargestRemainder, getparams, isset, kebab, paginate, password, prepareSearchString, replaceItem, sleep, snakecase, tick, timestamp, trace, trim, truthy, validateEmail, viewport };
//# sourceMappingURL=ems-web-app-utils.mjs.map