)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Golfed Codepen – 3D Spiral Thing

  1. // sort of golfed version of https://www.instagram.com/p/C1uv6Kqv19T/
  2. // by @mewtru
  3. b = document.body
  4. a = Object.assign
  5. a(b.style, { background:'#000', color:'#fff'})
  6. w = 'snippet.zone snippet.zone'.toUpperCase().split``
  7. F = (n, O = 0, C, S, o, t) => { 
  8.   b.innerHTML += `<div id=${n} style='position:absolute;left:50%;top:50%;translate:-50% -50%;width:100% text-align:center;white-space:nowrap'></div>`
  9.   w.map(l => this[n].innerHTML += `<span style='display:inline-block;margin-right:5px;font-size:28px'>${l}</span>`)
  10.   t = O
  11.   setInterval(_ => {
  12.     t += .005
  13.     ;[...this[n].children].map((e, i) => { 
  14.       T = t + i / 2.7
  15.       a(e.style, {
  16.         translate: `0 ${Math.sin(T) * 100}px`,
  17.         scale: Math.cos(T) * .5 + .5})
  18.     }, 16)
  19.   })
  20. }
  21. F('Z') 
  22. F('X', 3)

“Very cool” pen by Lucas Fernando that comes from @mewtru
I decided to do a speed-coded semi-golfed version… can definitely be way more golfed 😀

Faster than save/restore HTML5 canvas

  1. const canvas = document.createElement('canvas')
  2. const c = canvas.getContext('2d')
  3.  
  4. canvas.width = innerWidth
  5. canvas.height = innerHeight
  6.  
  7. document.body.append(canvas)
  8.  
  9. c.fillStyle = 'black'
  10. c.fillRect(0, 0, canvas.width, canvas.height)
  11.  
  12. class Shooter {
  13.   constructor() {
  14.     this.x = innerWidth / 2
  15.     this.y = innerHeight / 2
  16.     this.vx = Math.random() * 10 - 5
  17.     this.vy = Math.random() * 10 - 5
  18.     this.color = 'rgba(255, 0, 0, 0.5)'
  19.     this.size = 10
  20.     this.halfSize = this.size / 2
  21.   }
  22.   draw() {
  23.     this.x += this.vx
  24.     this.y += this.vy
  25.  
  26.     if (this.x < 0) {
  27.       this.x = innerWidth
  28.     } else if (this.x > innerWidth) {
  29.       this.x = 0
  30.     }
  31.  
  32.     if (this.y < 0) {
  33.       this.y = innerHeight
  34.     } else if (this.y > innerHeight) {
  35.       this.y = 0
  36.     }
  37.  
  38.     c.fillStyle = this.color
  39.     c.translate(this.x, this.y)
  40.     c.fillRect(-this.halfSize, -this.halfSize, this.size, this.size)
  41.  
  42.     c.setTransform(1, 0, 0, 1, 0, 0)
  43.   }
  44. }
  45.  
  46. const NUM = 1000
  47. const shooters = []
  48. for (let i = 0; i < NUM; i++) {
  49.   shooters.push(new Shooter())
  50. }
  51.  
  52. function loop() {
  53.   c.fillStyle = 'rgba(0, 0, 0, 0.1)'
  54.   c.fillRect(0, 0, innerWidth, innerHeight)
  55.  
  56.   for (let i = 0; i < NUM; i++) {
  57.     shooters[i].draw()
  58.   }
  59.   requestAnimationFrame(loop)
  60. }
  61. loop()

Using setTransform(1, 0, 0, 1, 0, 0) is faster than using save and restore. If you don’t need to save context info like fills, line styles etc… consider this method.

Prevent Class Method From Being Overwritten

  1. class A {
  2.   method() {
  3.     console.log('original')
  4.   }
  5. }
  6. Object.freeze(A.prototype)
  7.  
  8. let a = new A()
  9. a.method = function() { console.log('overwritten') }
  10. a.method()
  11.  
  12. class B {
  13.   method() {
  14.     console.log('original')
  15.   }
  16. }
  17.  
  18. let b = new B()
  19. b.method = function() { console.log('overwritten') }
  20. b.method()
I’m surprised I never tried/needed this before.

Em3w parensordot

  1. const vals = {
  2.   E: 0, M: 90, '3': 180, W: 270
  3. }
  4.  
  5. // const byDeg = {
  6. //   0: 'E', 90: 'M', 180: '3', 270: 'W'
  7. // }
  8. const byDeg = Object.keys(vals).reduce((acc, key) => { 
  9.   acc[vals[key]] = key;
  10.   return acc;
  11. }, {});
  12.  
  13.  
  14. const ops = {
  15.   ')': 90, '(' : -90, '|': 180
  16. }
  17.  
  18. function rotToSym(v) {
  19.   if (v < 0) v += 360;
  20.   const deg = Math.abs(v % 360);
  21.   return byDeg[deg]
  22. }
  23.  
  24. function op(char, op) {
  25.   if (char === 'M' && op === '|') return 'M'
  26.   if (char === 'W' && op === '|') return 'W'
  27.   let v = vals[char]
  28.   v += ops[op]
  29.   return rotToSym(v)
  30. }
  31.  
  32.  
  33. function emw(prog) {
  34.   prog = [...prog]
  35.  
  36.   let chars = []
  37.   let res = []
  38.   for (let i = 0; i < prog.length; i++) {
  39.     let char = prog[i]
  40.     if (vals[char] != null) {
  41.       chars.push(char)
  42.     } else if (ops[char]) {
  43.       chars = chars.map(v => op(v, char))
  44.     } else if (char === '.' && chars.length > 0) {
  45.       const num = chars.map(v => vals[v])
  46.         .reduce((a, b) => a + b, 0);
  47.       chars = [rotToSym(num)]
  48.     }
  49.   }
  50.   return chars.join``
  51. }
  52.  
  53. function expr(prog) {
  54.   const orig = prog;
  55.   prog = prog.split(/\s/)
  56.   return orig + ' = ' + prog.map(emw).join` `
  57. }
  58.  
  59. document.body.appendChild(
  60.   Object.assign(
  61.     document.createElement`pre`, {
  62.       innerHTML: 
  63. `
  64. Em3w parensordot 
  65.  
  66. // rotate 90 clockwise
  67. ${expr('EEE)')}
  68.  
  69. // rotate -90 clockwise
  70. ${expr('W(')}
  71. ${expr('W((')}
  72.  
  73. // mirror
  74. ${expr('E|')}
  75.  
  76. // mirror
  77. ${expr('EM|')}
  78.  
  79. ${expr('WW3) MM) EEEM).')}
  80.  
  81. // sum rotations
  82. ${expr('MMM.')}
  83.  
  84. ${expr(
  85. `E) E( E)) EEE))) E)))) MM33).`)}
  86. `}
  87.   )
  88. )

Fun thing I wanted to make for awhile… definitely going to do some doodles of this in my sketchbook…

Code description from GPT4 because I’m too lazy to write one…

This code is implementing a form of symbolic computation using a transformational language. This language has four primary symbols: “E”, “M”, “3”, and “W”. Each of these symbols is associated with a specific angle: 0, 90, 180, and 270 degrees, respectively.

There are also special symbols, which act as operators that perform certain transformations on the primary symbols:

  • “)”: Represents a rotation 90 degrees clockwise.
  • “(“: Represents a rotation 90 degrees counter-clockwise.
  • “|”: Represents a mirror operation, which reverses the direction. However, “M” and “W” are unaffected by this operation.
  • “.”: This operator sums up all previous primary symbols (by their respective degree values), resulting in a new symbol. The degree value of the new symbol is the sum of the previous degrees modulo 360.

The function emw(prog) interprets a string prog as a sequence of symbols and operations. It reads each character in the string and based on whether it’s a primary symbol, operator, or a “.”, it either adds the symbol to an array or performs an operation on the existing symbols in the array.

The expr(prog) function splits the input string prog into space-separated substrings. It interprets each substring as a sequence in the transformational language, using the emw function. It then joins the results together with a space and prepends the original input and an equals sign to give a string representation of the transformations.

The final section of the code generates a series of examples of expressions in this language, evaluates them using the expr function, and adds the results to the HTML body of a webpage in a formatted manner. This gives the user a way to see the transformations in action.

Concatenative JavaScript

  1. const vars = {}
  2.  
  3. const as = s => v => vars[s] = v
  4.  
  5. const def = s => v => {
  6.   vars[s] = v
  7. }
  8.  
  9. const set = (last, prop, val) => {
  10.   last[prop] = val
  11. }
  12.  
  13. const put = (last, prop, val) => {
  14.   last[prop] = val
  15.   return last
  16. }
  17.  
  18. const of = k => run.last[k]
  19. const $ = k => () => vars[k]
  20.  
  21. const run = (prog, log) => {
  22.   run.stack = []
  23.   let curr
  24.   for (let i = 0; i < prog.length; i++) {
  25.     let val = prog[i]
  26.     if (val != null && val === $) { 
  27.       run.stack.push(val())
  28.     } else if (typeof val === 'function') {
  29.       let ctx = null
  30.       if (document.body[val.name]) { 
  31.         ctx = document.body 
  32.         val = val.bind(ctx)
  33.       } else if (document[val.name]) { 
  34.         ctx = document
  35.         val = val.bind(ctx)
  36.       } 
  37.  
  38.       if (log) console.log('exec', 
  39.         val.name == 'bound ' ? '\u03BB' : val.name, run.stack)
  40.  
  41.       curr = val.apply(ctx, run.stack)
  42.       if (curr != run.stack) { 
  43.         run.stack = curr != null ? [curr] : []
  44.         if (typeof curr === 'object') {
  45.           run.last = curr
  46.         }
  47.       }
  48.     } else {
  49.       if (val != null) run.stack.push(val)
  50.     }
  51.   }
  52. }
  53.  
  54. const showStack = () => {
  55.   console.log('- stack:', run.stack)
  56.   console.log('  -> last object', run.last)
  57.   return run.stack
  58. }
  59.  
  60. const _ = new Proxy({}, { 
  61.   get: (o, key) => (() => (...a) => 
  62.     run.last[key].apply(run.last, a)
  63.   )()
  64. })
  65.  
  66. // try it out
  67.  
  68. run( 
  69.   [ 'div', 
  70.     document.createElement, 
  71.     document.body.appendChild, 
  72.     as`myDiv`,
  73.     'innerHTML', 'mini <b>concatenative</b>', set,
  74.     'style', of, 'color', 'green', set,
  75.  
  76.     'just logging the element', $`myDiv`, console.log, 
  77.  
  78.     'canvas', document.createElement, 
  79.     document.body.appendChild, 
  80.     'width', 500, put,
  81.     'height', 500, put,
  82.     def`myCanvas`,
  83.  
  84.     '2d',
  85.     _.getContext,
  86.     'fillStyle', 'red', set,
  87.     100, 30, _.translate,
  88.     0, 0, 10, 100, _.fillRect,
  89.     20, 0, 10, 100, _.fillRect,
  90.     .2, _.rotate,
  91.     -30, 25, 100, 10, _.fillRect,
  92.     -20, 55, 100, 10, _.fillRect,
  93.  
  94.     {}, 
  95.     'name', 'zevan', put,
  96.     'age', 82, put,
  97.     JSON.stringify,
  98.     as`person`,
  99.  
  100.     showStack
  101.   ]
  102. )
  103. console.log(vars);

I recently spent some time reading about and playing with the FORTH language. I keep finding myself creating weird vaguely FORTH inspired snippets now… This one processes an array that’s in a concatenative format like this:

[ 'hello world', Date.now(), console.log ]

Arguments are collected on a stack and passed to a function when a function is hit in the array. There are some odd helper functions for setting properties, setting nested properties, running functions with a specific context etc…


Here is GPT4’s mostly correct explanation of what it does

This is a rather unusual piece of JavaScript code that creates a simple “programming language” based on the concept of a stack machine, and runs a “program” in this language. It resembles some sort of DSL (domain-specific language) or script-like construct.

Here are what the main components do:

  1. vars: This is a dictionary that stores variables defined in the program.
  2. as: This is a function that takes a string s and returns a function that takes a value v, storing v in vars under the key s.
  3. def: Similar to as, it defines a variable in vars.
  4. set: This function is used to set the property of an object. It takes the object last, the property name prop, and the value val, and assigns val to the property prop of the object last.
  5. put: Similar to set, it sets the property of an object and returns the updated object.
  6. of: This function gets the property with name k of the last object returned by the program.
  7. $: This function is a getter for variables in vars.
  8. run: This is the main function that runs the program. The program is an array of actions, where an action can be a function, an object with a name of ‘get’ (which pushes the result of calling the function onto the stack), or a value (which is pushed onto the stack).
  9. showStack: This function logs the current state of the stack and the last object returned.
  10. _: This creates a new Proxy object that allows arbitrary methods to be called on the last object returned by the program.

The run function is then called with a list of actions to perform. The actions include creating a div and canvas element, appending them to the body of the document, setting their properties, and drawing on the canvas. It also creates an object with a name and age, converts it to JSON, and stores it in a variable. Finally, it shows the state of the stack and logs all the variables.

snippet.zone ~ 2021-24 /// {s/z}