Faster Drafts scripting and less debugging – use `map` for simpler code


Imagine we have split some part of draft.content into a list of lines, and now we want indented versions of them.

In other words, we want to get from:



  "    alpha",
  "    beta",
  "    gamma",
  "    delta",
  "    epsilon",
  "    zeta",
  "    eta",
  "    theta",
  "    iota",
  "    kappa",
  "    lambda",
  "    mu"

There’s a complicated route, and a simple one.

The complex path (with many moving parts – all of which can fail and cost puzzlement and debugging time):

const indent = xs => {
    let out = [];
    for (let i = 0, lng = xs.length; i < lng; i++) {
        out.push('    ' + xs[i])
    return out;

and the simple path

const indent = xs => => '    ' + x);

So, if you want a transformed version of a list, without changing its length, less can go wrong if you just use map

// indent :: [String] -> [String]
const indent = xs => => '    ' + x);

const xs = [
    "alpha", "beta", "gamma", "delta", "epsilon",
    "zeta", "eta", "theta", "iota", "kappa", "lambda", "mu"

const result = indent(xs);

Using map will save you from having to:

  • Declare three variables,
  • set up a test,
  • set up an auto-mutating increment
  • remember to delimit the parts with semi-colons instead of commas
  • reference each item of the list by zero-based index
  • push into an array
  • remember to return the value of the array

(Traditionally minded programmers often tell me that doing all this is “much simpler” than using map. Perhaps they mean that after many years of habit, all those fiddly and accident-prone mechanics just feel like familiar old friends to them. In any case, I always agree :slight_smile: )

Recipes :: Working with a subset of lines in a draft

Maybe you could update the title of this post to indicate it refers to use of map?

I was looking for it as a reference and had to poke around a bit.