New syntax proposal: Constructor Cascade (returns the cascadee) · Issue #172 · satyr/coco (original) (raw)
I've got a fair amount of code that looks like this:
head = document.createElement \head
style = document.createElement \style
&id = \html5chan-style
&textContent =
'''
%hakase.css%
'''
head.appendChild style
title = document.createElement \title
&textContent = board.title
head.appendChild title
html.appendChild head
or more purely, like this:
thing = new Thing
&foo = 'bar'
&baz = quux 'stuff'
something-with thing
where some of the code initializes and mutates an object just to pass it into another function (or return it). When available, I usually use a full constructor:
something-with new Thing foo: \bar baz: quux \stuff
But some constructors, e.g. DOM Image
, have stupid arguments (no src
), so an extra line of initialization is necessary.
I know I can use new
with a block to create the new function() {...}
form, but that doesn't work with Image
, and it introduces overhead. Thus, my straw man is:
Constructor Cascade
Similar to cascade, but expression returns the original reference (after execution of the block) instead of the result of the last expression in the block.
fn = -> construct new Image
&src = 'image.jpg'
document.body.appendChild do
construct document.createElement \div
&id = \stuff
&classList.add \things
&style
&display = \block
&textContent = 'are you a wizard'
=>
var img, x,x,x,y; img = function() { var $y = new Image $y.src = 'image.jpg' return $y }
$x = document.createElement('div') $x.id = 'stuff' $x.classList.add('things') y=y = y=x.style $y.display = 'block' $x.textContent = 'are you a wizard' document.body.appendChild($x)
Advantages
- Avoids needing an extra reference to a variable used only as an argument
- Cuts down on the verbosity of creating DOM trees, without any function calling overhead
- Avoids an extra
return this
at the end of a function, e.g. when usingwith new XMLHttpRequest
- Extends cascade to cover the other use of "fluent interface"-style chaining APIs, e.g:
$(body).append($('<p>').text('just look at all this overhead!'))
Problems
- Couldn't think of a better symbol/keyword than
construct
- Complicates the meaning of & even more
- Changes the order of code in the compiled js compared to the source