Skip to content

Instantly share code, notes, and snippets.

View rvighne's full-sized avatar

Rohit Vighne rvighne

View GitHub Profile
@rvighne
rvighne / enum.js
Last active September 10, 2016 19:12
Bringing enums to JavaScript! Creates a read-only enum-like object.
function Enum(...names) {
const target = new.target ? this : names.shift();
const desc = {
writable: false,
configurable: false,
value: null,
enumerable: true
};
@rvighne
rvighne / periodicSpeller.js
Created August 26, 2016 18:22
A generator that yields all possible spellings of a given word using element abbreviations from the periodic table (or any other source). Requires ES2015 support.
// List of strings that will be chained to spell words.
const atoms = new Set(["ac", "al", "am", "sb", "ar", "as", "at", "ba", "bk", "be", "bi", "bh", "b", "br", "cd", "ca", "cf", "c", "ce", "cs", "cl", "cr", "co", "cu", "cm", "ds", "db", "dy", "es", "er", "eu", "fm", "f", "fr", "gd", "ga", "ge", "au", "hf", "hs", "he", "ho", "h", "in", "i", "ir", "fe", "kr", "la", "lr", "pb", "li", "lu", "mg", "mn", "mt", "md", "hg", "mo", "nd", "ne", "np", "ni", "nb", "n", "no", "os", "o", "pd", "p", "pt", "pu", "po", "k", "pr", "pm", "pa", "ra", "rn", "re", "rh", "rg", "rb", "ru", "rf", "sm", "sc", "sg", "se", "si", "ag", "na", "sr", "s", "ta", "tc", "te", "tb", "tl", "th", "tm", "sn", "ti", "w", "uub", "uuh", "uuo", "uup", "uuq", "uus", "uut", "uuu", "u", "v", "xe", "yb", "y", "zn", "zr"]);
// An optimization. Should be equal to the length of the longest string in the `atoms` set above. Not strictly necessary
const maxAtomSize = 3;
/*
USAGE:
createMolecule(String targetWord) -> Iterator -> Array<String>
@rvighne
rvighne / loadScript.js
Last active August 25, 2016 23:52
Synchronously loads an external script. Not necessarily recommended for performance (due to use of eval) nor user experience (due to synchronous loading and execution). But this may be acceptable depending on your use case.
function loadScript(url) {
var request = new XMLHttpRequest;
request.open('GET', url, false);
request.send();
eval(request.responseText);
}
@rvighne
rvighne / multiKey.js
Last active July 6, 2021 21:53
Create an object that has multiple keys pointing to the same value. It uses getters and setters to work its magic, but acts perfectly like a regular object, including enumeration, membership testing, and deleting properties.
function multiKey(keyGroups) {
let obj = {};
let props = {};
for (let keyGroup of keyGroups) {
let masterKey = keyGroup[0];
let prop = {
configurable: true,
enumerable: false,
@rvighne
rvighne / lazyProp.js
Created August 11, 2016 17:42
Define properties on JavaScript objects to be evaluated on the first attempt to access them, rather than when defined, and then cached for all future accesses.
/*
SYNTAX:
object Object.prototype.lazyProp(string propName, function evaluator [, object propertyDescriptorDefaults]);
USAGE:
let obj = {};
obj.lazyProp('sqrtPI', () => Math.sqrt(Math.PI))
.lazyProp('e4', () => Math.E ** 10);
// obj.sqrtPI and obj.e4 have not been calculated yet
@rvighne
rvighne / Object-assign.js
Last active August 8, 2016 22:50
Polyfill for the Object.assign method using only ES5 (broadly supported) features. Follows the spec exactly (http://www.ecma-international.org/ecma-262/7.0/#sec-object.assign)
// Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
// Public domain
if (typeof Object.assign !== 'function') {
Object.defineProperty(Object, 'assign', {
configurable: true,
enumerable: false,
writable: true,
// Second argument forces the `length` property to be 2, as per the spec
@rvighne
rvighne / removeFormatting.js
Created July 22, 2016 17:01
Easy-to-use and robust function that removes all HTML formatting from an element by replacing its contents with a single Text node. This does not remove any CSS styling applied to the parent element.
/*
USAGE:
void removeFormatting(Element)
RESULT:
The provided element now contains a single Text node, whose value is
the concatenation of all the Text nodes in the original element's hierarchy
*/
// Used internally. Empties the element and returns the concatenated text as a String
@rvighne
rvighne / treeIterator.js
Created July 21, 2016 21:46
Wraps the TreeWalker interface into a generator function, for simpler and more idiomatic usage.
/*
SYNTAX:
Generator treeIterator(Node root, int whatToShow, bool function filter(Node))
- root: The parent node. It is not returned.
- whatToShow: Bitmask of the NodeFilter.SHOW_* static constants. Represents the types of nodes included.
- filter: Predicate returning whether the node given as the first argument should be included in the iteration.
Instead of a boolean, it may return a NodeFilter.FILTER_* static constant.
A return value of `true` is implicitly converted to `NodeFilter.FILTER_ACCEPT`,
and `false` becomes `NodeFilter.FILTER_REJECT`
@rvighne
rvighne / RightTriangles.hpp
Created June 17, 2016 22:01
Given a perimeter, this function returns a vector of all the integer-sided right triangles that can be formed that have that perimeter. Inspired by https://projecteuler.net/problem=75
#pragma once
#include <cmath>
#include <vector>
struct Triangle {
int a, b, c;
};
inline int gcd(int a, int b)
@rvighne
rvighne / miller-rabin.js
Created November 12, 2014 00:41
Miller-Rabin probabillistic primality test. You can trade off speed for more accuracy by raising the k argument.
function probablyPrime(n, k) {
// Always prime
if (n === 2 || n === 3)
return true;
// Never prime
if (n % 2 === 0 || n < 2)
return false;
// Write (n - 1) as 2^s * d