Skip to content

Instantly share code, notes, and snippets.

@evinism
Created October 17, 2021 22:32
Show Gist options
  • Save evinism/435f6ee76d07a3fdfb88f158e098e9cb to your computer and use it in GitHub Desktop.
Save evinism/435f6ee76d07a3fdfb88f158e098e9cb to your computer and use it in GitHub Desktop.
Chaotic JS Patterns files
const bareStrings = new Proxy({}, {
has(_, prop){
return window[prop] === undefined;
},
get(_, prop){
return prop.toString();
}
});
with(bareStrings){
console.log(Hello); // Logs "Hello"!
}
function only(definedItems){
return new Proxy({}, {
has(_, prop){
return !definedItems.includes(prop);
},
get(_, prop){
throw new Error("Referenced variable " + prop.toString() + " out of scope!");
},
set(_, prop){
throw new Error("Referenced variable " + prop.toString() + " out of scope!");
}
});
}
const a = 'available';
const b = 'unavailable';
with (only['a']) {
console.log(a); // "available"
console.log(b); // Throws!!
}
class Animal {}
const cat = new Animal();
const dog = new Animal();
const talk = {
[cat]: 'meow',
[dog]: 'woof'
};
console.log(talk[dog]); // "woof"
console.log(talk[cat]); // "woof", oh no!!!!
function uncomment(fn){
const body = fn.toString().replace(/\/\//, '');
return new Function(`return (${body})(...arguments)`);
}
function fn(a){
// return a + 1;
return a
}
fn(1) // returns 1
uncomment(fn)(1) // returns 2!
class Indexable {
constructor(){
this._indexer = Symbol();
}
[Symbol.toPrimitive](){ return this._indexer }
}
class Animal extends Indexable {}
const cat = new Animal();
const dog = new Animal();
const talk = {
[cat]: 'meow',
[dog]: 'woof'
};
console.log(talk[cat]); // "meow", hooray!!!
console.log(talk[dog]); // "woof"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment