• I am at peak Portland right now.

  • This package esm seems handy.

    It monkey patches in ES6 style import statements and modules into Node without using the latest bleeding edge features and naming your modules with the .mjs extension.

    You can run your node app with node -r esm index.js to enable globally for your process.

  • JAMStack

    Modern web development architecture based on client-side JavaScript, reusable APIs, and prebuilt Markup.

    That’s a pretty fancy name for a static web-site.

  • Metalsmith continued

    After mucking about for a bit I landed on the following configuration for Metalsmith.

    Metalsmith(__dirname)
        .metadata({})
        .source('./src')
        .destination('./build')
        .clean(true)
        .use(less())
        .use(slug())
        .use(collections({
            works: {
                pattern: 'works/*.md',
                sortBy: 'date',
                reverse: true,
                refer: false
            }
        }))
        .use(markdown())
        .use(jquery('**/*.html', function($) {
            let img = $('img');
            img.addClass('b-lazy');
            img.each((i, el) => {
                let src = $(el).attr('src');
                let lowsrc = src.replace('/images', '/images/thumbs');
                $(el).attr('src', lowsrc);
                $(el).attr('data-src', src);
            });
        }))
        .use(permalinks({
            relative: false,
            pattern: 'works/:date/:title'
        }))
        .use(layouts())
        .build(err => {
            if (err) {
                console.log(err);
                throw err;
            }
        });
    

    This starts with a direct lift from their documentation, to which I added Less compilation, a URL slugger, and a little “jQuery” post processing.

    The “jQuery” plugin is actually a wrapper around Cheerio - which is a small implementation of the jQuery API for Node. I’m using this plugin to grab all the images in the resulting markdown-converted HTML and set them up for use with a lazy-loader. This way the markdown document can remain simple and clear of HTML.

    I still think Metalsmith could use some better documentation and error handling. Debugging plugins exist but they’re not included in the examples. Overall, though, it’s a very good static site builder. I’m using Serve as a development server locally and Watch to rebuild files as I work. All together it’s a nice little web-site building toolkit.

  • I’ve run into this a few times - where renaming a file in VS Code can cause an explosion of borked imports.

    https://github.com/Microsoft/vscode/issues/52675

  • I’m re-evaluating Metalsmith as a static site generator.

    The last time I looked this over, it was still pretty new and didn’t have a lot of community support - but the plugin library has grown a lot.

  • I ran across a fun Webpack bug…at least I think it’s a bug.

    I have an isomorphic app - much of it is written in ES6 syntax (ReactJS). A small slice of the app runs only on the server-side to power a local API. There is a small amount of shared code between these two sections of the app - these are written as CommonJS modules to work directly in NodeJS without transpiling. Webpack imports this just fine along side ES6 style modules and imports.

    However…I found a fun issue. I had a small module which had a default export of an asynchronous function. Let’s pretend it was something like this:

    const async function doAsync() {
    	let result;
    	try {
    		result = await Promise.resolve(true);
    	} catch(e) {
    		result = false;
    	}
    	return result;
    }
    
    module.exports = doAsync;
    

    Now over in ES6 Webpack land - this completely fails to import - with strange errors about defaults and export not being defined.

    I need to create a test project demonstrating this. I have yet to find any explicit documentation about this particular issue…but boy is it definitely an edge case.

  • “WTF is JSX” is a good primer on what JSX is, even. I recall the first time I saw JSX I was a bit confused and it gave me the heebie-jeebies. “What’s that template doing in my jobblescript?” I moaned. But once I understood it I came to appreciate that it really serves to modularize and un-obfuscate UX code.

    Besides, all templating languages suck.

  • Here is something that should have been obvious - but was new to me. I was playing around with emoji strings the other day and got unexpected results. My favorite monkey-wrench for JavaScript Lodash handles emojis just fine.

  • And and not not

    Since I’ve been working in and around ReactJS for several months, I’ve come to know (and love) the JavaScript idiom of using logical operators && and || as simple control-flow statements.

    Since JavaScript types are loosey-goosey, logical operators mustn’t be too particular about the values they compare.

    A statement like true && “troof” will ultimately return troof because it’s not falsey. We can use this to our advantage to make a tiny equivalent of an if conditional statement.

    let isIt = "nope",
        itIs = ['it', 'is'];
    
    Array.isArray(isIt) && isIt.push('yep');
    Array.isArray(itIs) && itIs.push('indeed');
    
    console.log('Is this an array?', isIt);
    console.log('Is this an array?', itIs);
    
  • ASCII ain't Roman

    I thought a little more about the classic roman numeral interview problem. The challenge is to deal with the “subtractive” syntax. For example where the numeral for four iv is made of two characters and their order implies a different value…so if you’re mapping each character in a roman numeral to a number you can’t just blindly add them all up. The i before the v must be subtracted.

    This all very ASCII thinking though - a string of symbols like xxiv looks like four characters to an English speaking person - but to an ancient Roman - this is three characters. And this iii is one character.

    Unicode includes some roman numerals and you can see that “ⅳ” (U+2173) is only one character - made of two glyphs.

    With this in mind, you can think about the problem as a task of “correcting” the troublesome “two letter” glyphs and replacing them with a single symbol - then just doing some dumb arithmetic to get your integer value.

    This works because Roman numerals are a finite set, unlike the Arabic number system. We can use this to our advantage and write a dumber function.

    function toDecimal(numeral) {
      const troublesomeGlyphs = {
        "iv": "ⅳ", // 4
        "ix": "ⅸ", // 9
        "xl": "f", // 40
        "xc": "n", // 90
        "cd": "F", // 400
        "cm": "N", // 900
      };
    
      const sym = {
        "i": 1,
        "ⅳ": 4,
        "v": 5,
        "ⅸ": 9,
        "x": 10,
        "l": 50,
        "f": 40,
        "n": 90,
        "c": 100,
        "F": 400,
        "d": 500,
        "N": 900,
        "m": 1000,
      };
      numeral = numeral.toLowerCase();
      (Object.keys(troublesomeGlyphs)).forEach(k => {
        numeral = numeral.replace(k, troublesomeGlyphs[k]);
      });
      return numeral
        .split('')
        .map(n => sym[n])
        .reduce((total, current) => total + current, 0);
    }
    
  • Classical classics

    We’re doing lots of interviews at my work and two of my team are doing white-board exercises with applicants. They’re doing the classic “convert a roman numeral to a decimal” problem.

    In all my years, ironically, I have never been asked such a thing. So this morning on the train I decided to have a crack at it myself.

    const MDCCLXXVI = 'MDCCLXXVI'; // 1776
    const MCMLIV = 'MCMLIV'; // 1954
    const MCMXC = 'MCMXC'; // 1990
    
    function toDecimal(numeral) {
      const sym = {
        i: 1,
        v: 5,
        x: 10,
        l: 50,
        c: 100,
        d: 500,
        m: 1000
      };
      return (numeral.toString().toLowerCase().split(''))
        .map(j => sym[j])
        .reverse()
        .reduce((total, current, i, arr) => {
          return (i === 0 || current >= arr[i-1])
            ? total + current 
            : total - current;
        }, 0);
    }
    
  • !!coffee

    Bang! Bang! Coffee! This is a new Micro.blog about JavaScript.

    I’ve been (micro) blogging @abouthalf on Micro.Blog for a while now - and I lurve it. I miss having a place to blarg about the technology I work with most of the time - but I don’t want to mix arty things on abouthalf with techy things. So here we are!

    I will use this as a dumping ground for links, short thoughts, and discoveries on everyone’s favorite least favorite programming language.

subscribe via RSS