Skip to content

Instantly share code, notes, and snippets.

@Offirmo
Last active January 29, 2024 10:09
Show Gist options
  • Save Offirmo/8c9df82f897a35087dd36b6e0473723b to your computer and use it in GitHub Desktop.
Save Offirmo/8c9df82f897a35087dd36b6e0473723b to your computer and use it in GitHub Desktop.
[rare JavaScript stuff I forget all the time] #JavaScript
// null coalescings https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing
foo = foo ?? 42
foo ??= 42
// optional chaining https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
dog?.name
dog?.[name]
hello?.(target)
// https://devdocs.io/dom/structuredclone
structuredClone(value)
structuredClone(value, options)
//https://devdocs.io/javascript/global_objects/array/sort
export function compare(a, b): number {
return a.localeCompare(b)
return a - b
}
// - <0 => sort a to an index lower than b => i.e. a comes first
// - =0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behavior, thus, not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
// - >0, sort b to an index lower than a => i.e. b comes first
// - must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned, then the sort order is undefined.
///////
// https://devdocs.io/javascript/global_objects/encodeuricomponent
encodeURIComponent(location.hostname)
encodeURI(location.hostname)
///////
const ROOT_PROTOTYPE = Object.create(null)
const SEC = Object.create(ROOT_PROTOTYPE)
/////// loop controls
break
continue
// https://enmascript.com/articles/2019/09/20/two-exceptional-use-cases-for-the-spread-operator-you-may-not-know-of
const isDog = true;
const obj = {
key: 'value',
...(isDog && { woof: true }),
}
// https://dmitripavlutin.com/javascript-array-from-applications/
Array.from(arguments)
Array.from(arrayToClone);
Array.from({length: 12}, (item, index) => index) //
Array.from(new Set(array)) // unique items
// dedupe array with sets
Array.from(new Set([...old_base.roles, ...new_base_n.roles]).sort()
s = new Set(['a', 'b'])
ss = new Set([ ...s, 'c'])
/////// enhanced object literals ///////
http://www.benmvp.com/learning-es6-enhanced-object-literals/
{
make, // same as make: make
// computed values now work with
// object literals
['make' + make]: true,
// Method definition shorthand syntax
// omits `function` keyword & colon
depreciate() {
this.value -= 2500;
}
}
/////// timestamp ///////
// https://stackoverflow.com/questions/221294/how-do-you-get-a-timestamp-in-javascript
+new Date() // <-- note the + operator!
(new Date()).toISOString()
/////// errors ///////
// https://github.com/Offirmo/extended-exceptions.js
Error (standard) <-- javascript root exception
+ EvalError <-- Vanilla javascript exceptions
+ RangeError <-- ...
+ ReferenceError <-- ...
+ SyntaxError <-- ...
+ TypeError <-- ...
+ URIError <-- ...
/////// chars ///////
str.charCodeAt(index)
str.codePointAt(pos)
String.fromCharCode(num1[, ...[, numN]])
String.fromCodePoint(num1[, ...[, numN]])
hexString = yourNumber.toString(16)
yourNumber = parseInt(hexString, 16)
// https://stackoverflow.com/questions/1877475/repeat-character-n-times
Array(11).join("a") // create string with 10 as "aaaaaaaaaa"
Array(10).fill('a').join('')
/////// break ///////
outer_block: {
inner_block: {
console.log('1');
break outer_block; // breaks out of both inner_block and outer_block
console.log(':-('); // skipped
}
console.log('2'); // skipped
}
resolution: {
if (!_.isString(message)) {
problems.push('invalid message')
break resolution
}
let message_format: IntlMessageFormat<any>
try {
message_format = new IntlMessageFormat(message, locale, custom_formats)
}
catch (err) {
problems.push('unable to parse message format (*)')
underlying_error = err
break resolution
}
// eventually
try {
formatted_msg = message_format.format(values)
}
catch (err) {
problems.push('unable to compile message (*)')
underlying_error = err
break resolution
}
}
if (underlying_error) ...
/////// SETS ///////
const seen_nodes = new Set()
let node = head
while(node) {
if (seen_nodes.has(node))
return true
seen_nodes.add(node)
node = node.next
}
return false
/////// REDUCE ///////
res = .reduce((acc, val) => {
return acc + val
}, 0)
err = decorators.reduce((err, decorator) => {
return decorator(err)
}, err)
/////// CUSTOM JS ERROR ///////
/**
* See:
* https://github.com/Offirmo/extended-exceptions.js/blob/master/extended_exceptions.js
*
* http://stackoverflow.com/questions/33870684/why-doesnt-instanceof-work-on-instances-of-error-subclasses-under-babel-node
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
*
Objet très spécial
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types
http://stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript
http://www.ecma-international.org/ecma-262/5.1/#sec-15.11.1
https://github.com/sindresorhus/aggregate-error
*/
function CustomException(message) {
this.name = 'CustomException';
this.message = message || 'XYZ will not run.';
this.stack = (new Error()).stack;
}
CustomException.prototype = Object.create(Error.prototype);
CustomException.prototype.constructor = CustomException;
/////// ACCESS //////
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment