Skip to content

Instantly share code, notes, and snippets.

@westc
westc / formatIntlDate.js
Last active April 20, 2024 03:48
A more intuitive version of a JS date formatter. This function leverages Intl.DateTimeFormat().
var formatIntlDate = (() => {
const codeToOpts = [...'Y=year M=month D=day H=hour h=hour m=minute s=second S:1 SS:2 SSS:3 MMM=month:short MMMM=month:long DDD=weekday:short DDDD=weekday:long A=hour:2D a=hour:2D Z:Offset ZZ:Offset ZZZ:Generic ZZZZ: J=year:numeric,month:2D,day:2D,hourCycle:h23,hour:2D,minute:2D,second:2D,fractionalSecondDigits:3,timeZoneName:longOffset'.replace(/(\w)=\w+(?= |$)/g, '$&:numeric $1$&:2D').replace(/hour/g, 'hourCycle:h23,$&').replace(/Z:/g, 'Z=timeZoneName:long').replace(/S:/g, 'S=fractionalSecondDigits:').replace(/2D/g, '2-digit').matchAll(/(\w+)=(\S+)/g)]
.reduce(
(codeToOpts, [_, code, strOpts]) => {
codeToOpts[code] = [...strOpts.matchAll(/(\w+):([^,]+)/g)].reduce(
(opts, [_, key, value]) => {
opts[key] = value;
return opts;
},
{}
@westc
westc / formatIntlDate.js
Last active April 19, 2024 04:41
Makes it possible to format a Date object while leveraging the Intl.DateTimeFormat formatter.
function formatIntlDate(date, format, options) {
return format.replace(
/<<|>>|<(\w)(?:\|([^>]+))?>/g,
(fullMatch, type, option) => {
if (!type) return fullMatch.charAt(0);
if (/^[YMDHhmsf]$/.test(type ?? '')) option ??= 'numeric';
const subOptions = {timeZone: options?.timeZone ?? undefined};
let partType;
@westc
westc / zip.cls
Last active March 28, 2024 22:14
Two implementations of zip() and zipKeys() in Apex (Salesforce).
/**
* Merges together the values of each of the arrays with the values at the
* corresponding position. Useful when you have separate data sources that are
* coordinated through matching array indexes.
*/
public static Object[][] zip(Object[][] listOfArrays) {
Object[][] rows = new List<Object[]>();
Integer itemsCount;
for (Object[] items : listOfArrays) {
Boolean isFirstPass = itemsCount == null;
@westc
westc / sendNewRecordsEmail.cls
Created February 16, 2024 02:25 — forked from cwest-consultch/sendNewRecordsEmail.cls
Apex - Function that sends an email of all of the new records of a given type created after a given datetime.
public static boolean sendNewRecordsEmail(String[] toAddresses, String sobjectName, DateTime createdAfter) {
String strCreatedAfter = createdAfter.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');
// Get the count of records after the createdAfter date/time.
String restSOQL = String.join(
new String[]{
'SELECT count(Id) record_count',
'FROM ' + sobjectName,
'WHERE CreatedDate > ' + strCreatedAfter
},
@westc
westc / getComments.js
Last active February 12, 2024 17:18
getComments(fn, opt_trim) returns an array of all the comments in the specified function.
(function(RGX_COMMENT, RGX_TRIM) {
getComments = function (fn, opt_trim) {
var comments = [];
(fn + '').replace(RGX_COMMENT, function(m, a, b, c) {
if (!c) {
m = a == undefined ? b : a;
comments.push(opt_trim ? m.replace(RGX_TRIM, '') : m);
}
});
return comments;
@westc
westc / lwc-console-override.js
Created February 12, 2024 16:16
Custom console object to allow for objects to be printed correctly in the console from within LWC by leveraging iframes.
/**
* Custom console object to allow for objects to be printed correctly in the
* console by leveraging iframes.
* @type {Console}
*/
const CONSOLE = ((realConsole) => {
let iframe;
try {
iframe = document.createElement('iframe');
iframe.style.display = 'none';
@westc
westc / loadScripts.js
Last active February 1, 2024 21:16
Loads a <script> tag if necessary and finishes once the `checker` returns a promised value that is not falsy.
/**
* Can load multiple scripts (javascript and css) and finishes once the
* `checker` returns a promised value that is not falsy.
* @param {string[]} urls
* Ordinarily a URL is determined to be for CSS or JS by the extension of the
* pathname but if it doesn't end in .js or .css this will not be possible and
* it will default to JS. If you want to force a URL to be recognized as a JS
* file you should prefix the URL with `"js:"` and if you want it to be
* recognized as a CSS file you should prefix it with `"css:"`.
* @param {null|undefined|{
@westc
westc / vue3-component-clickable-dragon-balls.html
Last active January 25, 2024 17:25
Vue3 Component - Clickable Dragon Balls
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset='UTF-8'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Clickable Dragon Balls</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.37/vue.global.prod.min.js"></script>
<script>
addEventListener('DOMContentLoaded', () => {
Vue.createApp({
@westc
westc / createCallableFrame.js
Last active January 24, 2024 17:58
createCallableFrame() - Creates an IFRAME which allows for easier 2-way communication (sending messages). When calling into the frame you actually specify a function name (or path) followed by the arguments you want to pass.
// NOTE: This solution was intentionally written without using newer JS
// features to make the minified version even smaller.
var createCallableFrame = (function () {
var IFRAME_SCRIPT_MESSAGE_CODE = parseFunction(function() {
// NOTE: Referencing with window to ensure that local namespace will not
// interfere.
window.addEventListener('message', function(e) {
if (e.data.funcName && e.data.args) {
var func = eval(e.data.funcName);
if ('function' === typeof func) func.apply(e, e.data.args || []);
@westc
westc / extract.js
Last active January 12, 2024 15:40
Extracts substrings from the given `string` by using `regexp`.
/**
* Extracts substrings from the given `string` by using `regexp`.
* @type {{
* (regexp: RegExp, string: string) => RegExpExecArray;
* <T>(regexp: RegExp, string: string, handler: (matches: RegExpExecArray) => T) => T;
* }}
*/
const extract = (regexp, string, handler) => {
const matches = regexp.exec(string) ?? [];
return handler ? handler(matches) : matches;