Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Sunday, 15 April 2018

# Markdown all things

Whilst blogger.com provides a fairly good blogging platform for regular writing, I've found that it's rather painful for technical blogging. In particular, code blocks are a mission. In the past, I've wrapped code in <pre><code> ... </code></pre> and let [highlight.js](https://github.com/isagalaev/highlight.js/) do all the heavy lifting of making that actually look readable. HighlightJs has been fantastic at that, but it still hasn't been as smooth a process as I would have liked _overall_. I still tended to write the non-code parts in the WYSIWIG html editor, and had to switch the source view to work on code parts. 

When I blog, I literally want to get out the information as quickly as possible, in a readable format. I'm not here to fight with styling.

So I was quite happy to stumble across [showdown](https://github.com/showdownjs/showdown). A little Javascript in my template and suddenly I could write in possibly the simplest format ever: markdown. I had quick and easy access to simple styling elements (lists, headings, etc) as well as code blocks. All good, but not automagick out of the box. 

I thought to myself, _"I'm sure I can't be the only person who wants this"_, and _"It would be nice if that auto-bootstrapping of markdown+code could be done anywhere, not just from within my blogger template"_.

So, as is so common within the open-source world, I stand upon the very tall, very broad shoulders of [highlight.js](https://github.com/isagalaev/highlight.js/) and [showdown](https://github.com/showdownjs/showdown) to present [auto-markdown](https://github.com/fluffynuts/auto-markdown): a script you can include on any page to convert any element with the `markdown` class to be rendered as markdown. It can even be configured (script versions and code theme) via some global variables, so you don't have to fiddle with the code if you don't want to.

I trialed it with my last post and It's how I'm writing now -- I just add a shell `pre` tag with the `markdown` class and get on with the writing, without any more fighting with the html editor. As a bonus: even if the script fails for some reason (such as if the user has Javascript disabled or GitHub doesn't supply my script in time), the blog is still in a readable format: markdown.

If you're interested, follow the instructions in the [README.md](https://github.com/fluffynuts/auto-markdown). Feel free to open issues if you encounter some - for instance, I encountered some stickiness with generics in code blocks. Also, bear in mind that markdown requires html-escaping for chevrons (ie, embedding xml). 

Feel free to share it as much as you like. If you don't feel comfortable referencing my code directly, fork my repo and keep your own copy (:

Now, if only blogger's html editor had a vi mode...

Thursday, 9 July 2015

Callbacks suck

Problem: Javascript is essentially run on one thread and some things take time, blocking other requests.
Solution: make everything asynchronous and provide a callback mechanism.
Problem: I now have plenty of asynchronous calls which come back to a callback which does another async call and so on and so forth. Since I didn't really think this through to start with (!!), I now have something like:


This code is an unmaintainable mess and something has to be done about it.


There are a few ways to slay this beast:

#1 Refactor
You could refactor your code to pull out methods and reference those. Chances are you end up with something a little spaghetti-like: now you have all these neat little functions but actually determining the call order is an exercise in using your IDE's "go to definition" function, or at the very least, VIM's * and # commands. Not ideal, at least not from where I stand. Refactoring is a good process but I don't think it's the right tool to fix this.

#2 Node async module
You could alter your programming pattern and make use of the (rather cool) async node module. Off the top, it looks like it has some interesting solutions to some of the most common logic patterns, but I'm still not 100% sold. There's nothing intrinsically wrong with the module -- it just doesn't seem like the best fit (to me).

#3 Promises (to the rescue, again)
Promises have been around for a while and they're not going away. Indeed, ES6 brings promises right into the core language. If you aren't using them, it's at least time to start looking at them. And if you do, and you happen to stumble across one of the grandfathers of the promise library offering, Q, then you will be pleased to find that Q has support baked in to provide a promise-based wrapper around the typical NodeJS async callback: Q.nfbind, or, as I prefer, the alias: Q.denodeify.

You can just do something like:



var promiseBasedFunction = Q.denodeify(someAsyncFunction);
promiseBasedFunction('arg1.level0', 'arg2.level0').then(function(result) {
// first call succeeds, let's carry on
  return promiseBasedFunction('arg1.level1', 'arg2.level1');
}).then(function(result) {
// second call succeeds, let's forge on forward
  return promiseBasedFunction('arg1.level2', 'arg2.level2');
}).catch(function(error) {
// handle errors
  console.log('FAIL: ' + error);
}).done(function() {
// this is always run
  console.log('Exiting now...');
});
 
 

Some wins you get out of this:
  1. No deep nesting. There is a nice follow-on of functionality, something you can read top-down and which someone else could probably get into a little quicker. Code readability consistently ranks highly when programmers are asked to list aspects of quality code. Remember that the code you expertly write today will be visited by a complete stranger some time in the future. That stranger may even be you.
  2. No need to handle errors at every asynchronous turn. The first one that fails ends up in the catch area and you can deal with it there
  3. A defined end-point that is easy to deal with (the done handler)
But wait, there's more!
The async node module has some interesting techniques for dealing with simultaneous async calls (think: I need to get data from three web services and provide a consolidated answer -- I'd prefer to make those calls in parallel and consolidate once) -- but so does Q, with Q.all(). Q offers a lot, and one of the main benefits it offers is helping to wean you off of the callback tit. As I've shown in my promises tutorial, different promise libraries play together fairly well, so even if you decide to switch to another (or the ES6 built-in Promise), you have to freedom to do so.

Not that I suspect Q is going anywhere any time soon.


Footnote: this journey started when I had the brainfart that it would be great if there were a node module that provided functionality to wrap existing async calls in the promise lingo. I was about to embark on writing one when a friend suggested that I check out some of the functionality in Q that I wasn't already using. That's a reminder to check if a problem has already been solved before running off to write code -- though the process (like the process of writing my own promises implementation) would have probably been enlightening. It's also probably a reminder that it can be quite beneficial to skim over the full documentation for a library to discover useful gems.

Tuesday, 14 April 2015

RequireJS + AngularJS + A different spin

I keep on meaning to post this tutorial here -- it's been on github for a while and I somehow didn't manage to add it here...
Anyways, this was part of a discovery mission for using RequireJS and Angular to build a simple app. Angular because I like it as an MVC framework for Javascript and RequireJS because, really, who wants to maintain script tag spam in your SPA? Not me, not after I had a page with 20 inclusions and realised it was indicative of something horribly wrong.
The method I chose also makes this code easier (for me) to test: Angular has some great mocking and testing functionality, but in the face of Karma+Jasmine, it just seems like far too much effort to figure out another mocking framework -- not to mention that I find the concept of having to $apply to get Angular to run its magic a little counter-intuitive and a little out-of-place in a test (imo).
So I flipped this a little on it's head: the controller module in this project doesn't actually register a controller -- it returns the configuration which can be used to register a controller -- which is consumed by app.js so that routing can work with the configured controller. This frees me up to test the controller in a simpler way: test that the array has the correct dependencies, in the correct order (typically, just '$scope') and then test that the scope passed in is modified in the expected way (properties and methods added and the methods work as expected). I must point out the obvious here: that I'm not inclined to use Angular factories and services -- but who needs them if you have RequireJS and go the prototypical route?
But enough blah-blah. If nothing else, this tutorial can demonstrate one way to do it. I've also made JQuery private so that the only library in the global scope is Angular -- and this was mainly so that angular-route would load up correctly. There's probably a better way do to this too (I've read about AngularAMD and some others; just haven't play-tested them), but I was satisfied enough with the final result -- and it might prove at least a little interesting for some (:

Tuesday, 31 March 2015

Update to promises tutorial

For anyone who is interested, my promises tutorial has been updated to include info and examples about the native ES6 Promise prototype. You can get some goodness here: http://davydm.blogspot.com/2014/10/javascript-and-promises.html

Thursday, 30 October 2014

Javascript and promises

I wrote a little tutorial a small while back on using promises within Javascript as this seems to be a point of confusion for some, especially those new to promises. The tutorial is not meant to be ultimately comprehensive, but hopefully it should at least be useful -- and it made me polish up a promises library of my own for learning and display purposes. You can get all the code here: https://github.com/fluffynuts/js-promises-tutorial and indeed that repository is what I'm using for the iframe source below, using RawGit. Mainly because it relies on a bunch of Javascript and JSON files to work but also because I'm way too lazy to maintain multiple versions of this and this tutorial may be revisited for a little spit 'n polish on occasion. (EDIT: this entry was updated to include example usage of the ES6 native Promise prototype).

What's new in PeanutButter?

Retrieving the post... Please hold. If the post doesn't load properly, you can check it out here: https://github.com/fluffynuts/blog/...