Friday, 23 November 2018

Finding the index of an array of objects by one of the object's properties

I've been doing a shed load of work with lodash of late and, seeing as I've not posted in an age, I thought I'd illustrate an issue I was working on today.

I needed to pass an element of an array to a Vue component but needed a specific one identified by another object. We use lodash so thought I'd make use of findIndex and isEqual and came up with this:

const obj = {
    id: 1,
    name: "fred"

const arr = [{
    a: "B",
    s: {
        id: 1,
        name: "fred"
}, {
    a: "A",
    s: {
        id: 2,
        name: "fred"

alert(arr[_.findIndex(arr, (a) => _.isEqual(a.s, obj))].a);

Heat eh?

Saturday, 14 July 2018

Getting Unstuck: Day 10

As a result of signing up for Scratch Getting Unstuck I got a little carried away building a binary clock like this one in Scratch, but got really, really annoyed about not being able to place the elements just where I wanted. I remembered reading something a little while ago about the sb2 file format being an archive so I unzipped it and clocked that sprites have a scratchX and scratchY coordinate within the project.json file. That and figuring out that it uses SVG as the Vector format (why wouldn't you?) meant that I could replace the dodgy path with a circle element. This is the result and I'm quite pleased with it. Now, if only I could automagically use dynamic variable names I wouldn't have to have so many functions. Ah well.

Wednesday, 11 July 2018

Getting IE11 to play nicely with grid-area

I've been playing with CSS Grid layout lately within a Vue Component and I'm needing to place specific blocks within a grid, they are of an arbitrary position width and height and that all worked a treat within FireFox and Chrome... just not in, you guessed it, IE11.

So after banging my head against the issue for a few hours and trying everything I could think of I went to StackOverflow and asked. It seems I was being too helpful and adding the browser prefix rather than letting Vue do it for me. So far so good and StackOverflow provided the answer (thanks zero298), but it only went so far.

After looking at the issue some more I came up with the following script:

getStyle: function(x, y, a, b, c, d){
    var style = [];
    style.push("grid-row: " + x + ";");
    style.push("grid-row-span: " + d + ";");
    style.push("grid-column: " + y + ";");
    style.push("grid-column-span: " + c + ";");
    style.push("grid-area: " + x + " / " + y + " / " + a + " / " + b + ";");
    style.push("border: 1px solid white;");
    return style.join(" ");

I know that I'm using CSS for the border on the elements but IE11 doesn't support the grid-gap property for some reason, and rather than use browser detection, I figured it would be better to just do it this way for all elements. It's an interesting way of doing things as some of the properties are incompatible, which is why the decent bits of grid-area are left to the end and the IE11 specific bits get added first. IE11 doesn't support grid-area anyway so we're golden.

A little bit of extra work but should you examine the result in the bound style of an element you only see the appropriate CSS for the appropriate browser, which is nice. As I replied added in my original question on SO I just needed to trust Vue!


I got to thinking about the variables I was passing to the function above and realised that the c and d variables could be derived from subtracting the width from the x coordinate and the depth of the block from the y coordinate. Not only does this meant that the number of variables I was passing was reduced (something of an issue as the functions I was calling this from were making the calculations on the fly) but it also makes it much clearer. This is the new function:

getStyle: function(x, y, width, depth){
     * X=Row , Y=Column
     * IE11 has issues with grid-area as well as the syntax of grid-row and grid-column.
     * As such we need a polyfill for that that uses "-span" to indicate the "length" of the element
     * @param {number} x The "line" where the element should start on the horizontal grid (column) from the top
     * @param {number} y The "line" where the element should start on the vertical grid (row) from the left
     * @param {number} width The "line" where the element should end on the horizontal grid (column) from the top
     * @param {number} depth The "line" where the element should end on the vertical grid (row) from the left
    var style = [];
    style.push("grid-row: " + x);
    style.push("grid-row-span: " + (width - x));
    style.push("grid-column: " + y);
    style.push("grid-column-span: " + (depth - y));
    style.push("grid-area: " + x + " / " + y + " / " + width + " / " + depth);
    return style.join("; ");

Thursday, 28 June 2018

Colour shading with JavaScript

Shading a colour can be an utter pain but when I came across this script from CSS-TRICKS I was happy as a pig in muck. At least I was until I had to change the colour received via a call to getComputedStyle. getComputedStyle returns the colour in this format rgb(RedDecimalNumber, GreenDecimalNumber, BlueDecimalNumber) (red is rgb(255,0,0)) rather than the #RedHexadecimalNumberGreenHexadecimalNumberBlueHexadecimalNumber (red is #ff0000). The original script I was using was the one linked above so I had to convert the colour from getComputedStyle to hexadecimal, alter its shade and return it back to the original element's style as hexadecimal again.

This method seemed overly complicated, and I clocked that I didn't need to return it to the element as hexadecimal but could use it just as an RGB string in the inline CSS. Then I got to looking at the original script and realised that as getComputedStyle returns an RGB string, I could rewrite the original function to use a regex function and return that to the inline CSS instead. The following is the function:


I always forget that replace can take a function as the second argument but in this instance, it's cool that it does. The following is a less ES6y version:

o.replace(/\d+/g, function(c){
  if((parseInt(c, 10) + s) >= 255){
    return 255
    if((parseInt(c, 10) + s) <= 0){
      return 0
      return parseInt(c, 10) + s

Fun eh?

Monday, 25 June 2018

Vue simple-webpack on c9

I've lost track of how many times I've had to re-research this issue so I thought I'd best document it here. When playing through tutorials on Vue I often use c9 but had problems figuring out how to get the simple-webpack versions running. This, then, is how to get it up and running with a the vue-cli.

Open webpack.config.js and turn off the host check by adding this to the devServer object:

devServer: {
    historyApiFallback: true,
    noInfo: true,
    overlay: true,
    disableHostCheck: true

Then open package.json and alter the dev scripts object so it looks like this:

"cross-env NODE_ENV=development webpack-dev-server --host $IP --port $PORT --open --hot"

Of course, this works for me but YMMV.

Sunday, 22 April 2018

A new outdoor venue for Witchford Archers

One of the things that always impresses me about Witchford Archers is just how well we work together! Last year when we had to move venue, we worked like crazy to move all of our kit. While it might seem that all we do is shoot, and drink afterwards, in the background, there's so much activity it makes me positive about humanity!
We prepared our new outdoor venue yesterday. Nick has moved heaven and earth to secure the playing fields at Sutton C of E (VC) Primary School as a lovely place to shoot when the sun's out. Yesterday we made significant progress with building a... shed doesn't do it justice, to be honest as it's a work of art!
Designed and architected by Alan and Chris loads of work went into sourcing and preparing materials as cheaply as possible.
Aided my Derek, Nick, Oliwia and Dominic it was erected in a lovely shady spot in the playing fields over the course of Saturday the 21st of April 2018. The following show just what was accomplished!

Wednesday, 4 April 2018

Detect IE11

I'm old enough to remember why we needed jQuery: IE6.

Now I'm less used to using it and prefer vanilla JS but still wish for its universal levelling of the playing field because now I have to deal with the peculiarities of IE11 on a near daily basis so, thanks to this answer on StackOverflow, you'll often see this peppering my code:

    // Do something peculiar...

Monday, 26 March 2018

Rock your lobster

I've moved jobs, and that's all well and good, but the best thing is meeting the new people. One of whom suggested I read 12 Rules for Life by Jordan Peterson (thanks, Gorka). It's an interesting read/listen, not least because his first rule is all to do with standing up straight... and something to do with lobsters...

The thing is, my back is borked with my vertebrae all on the way to being fused together (bloody AS). Thus I'm unable to even look behind me unless I turn around (got to love mirrors in cars).

And don't get me started on Yoga! I've tried it, and I thought it was a lovely idea (I even bought a mat on offer in Sainsbury's), but I lasted all of 5 and a half sessions until I knocked it on the head. The straw that broke the camels back was the instructor's insistence that we gradually curve our backs from sitting up until we were lying flat on our backs, at which point there was an almighty slap! There was no gradual curving involved; I just crashed back because I can't gradually curve my back as it's a solid lump. Unless that is, Maria's has expanded all of her strength pummeling it once a month, at that point it sort of moves freely for a little while (or it feels as if it does anyway, or I don't care because I'm too relaxed to notice).

So never put off a decent massage (thanks, Maria) and don't worry too much about standing up straight. He, Mr Peterson, does suggest other things. If you can't stand up straight, you can do other things like looking someone squarely in the face and putting your shoulders back... he even trots out the old adage about smiling making you feel better, even if you're not feeling all that chipper to start with (It's true as well).

Sunday, 11 March 2018

One line NHS Number checker

I didn't know this until recently, but the UK's NHS number is a rather smart device, and I ended up spending a few minutes looking at this page and then generating this checker:

const chechNhsNum = num => {
  let multiplier = 10;
  return num.split("").reduce((a, c) => {
    if(multiplier > 1){
      const semiTotal = ~~c * multiplier;
      return a + semiTotal;
      return 11 - a % 11 > 9 ? false : ~~c === 11 - a % 11
  }, 0);

Then I got to thinking how small I could make the checker and worked this up:

const validNHSnum=num=>num.split("").reduce((a,c)=>a.m>1?{a:a.a+~~c*a.m,m:a.m-1}:11-a.a%11>9?false:~~c===11-a.a%11,{a:0,m:10});

Which is sort of like the puzzles Mr Monks and I used to beat ourselves up with when we played Empire of Code. Running it through Babel produces this, which I guess is more readable:

var validNHSnum = function validNHSnum(num) {
  return num.split("").reduce(function (a, c) {
    return a.m > 1 ? { a: a.a + ~~c * a.m, m: a.m - 1 } : 11 - a.a % 11 > 9 ? false : ~~c === 11 - a.a % 11;
  }, { a: 0, m: 10 });

Thursday, 8 March 2018

Contagious nausea

A friend and I were discussing the most humorous bodily functions, and we got into a disagreement over whether farting of vomiting was the funniest.

I'm pretty sure that farting is the one most likely to make me guffaw, but she told a rather good story about sick that made me chortle.

The main reason why I think vomit is no laughing matter is that for me at least, it's contagious. I see someone being sick and I automatically get the gag reflex as well. And it doesn't even have to be a person.

Once-upon-a-time, when we lived afloat, I was quietly sitting working on my laptop in the galley when the cat went mental! Eddie was a bruiser of a cat with a face that only his mother, god rest her diseased soul, could love. He looked and acted like a thug, and I'm pretty sure he thought he was a dog.

He'd found a moth you see, and not just any old moth but one the size of Mothra. It was huge! He thought it was immense fun to chase around after the poor bugger dragging considerable tears in its wings. To such an extent that it was no longer able to keep itself aloft and fell to the floor, still waving it's enormous wings - though to no avail. It just lay there waving it's broken wings until, that is, Eddie pounced.

He batted it around a wee bit until he got bored and then chomp, down it went.

His table manners were as brutish as everything else about him, and he didn't bother to chew so down the poor moth went, still flapping.

The flapping must've tickled something in his withered innards as, not 10 seconds after he'd swallowed dear old Mothra, he threw it back up.

"Ah, bloody cat", says I and I gentle step over it to grab some kitchen roll to wipe up the mess. Crouching down after gently moving the cat out of the way (he was cleaning his claws and looking disinterested now that he's murdered his plaything) I bent to my task. But, looking down at the forlorn once-giant, I noticed that s/he was still vainly trying to escape and was gently waving those tattered wings while being slightly crushed and covered with Eddie's digestive juices and the odd semi-digested cat biscuit.

That was it! Thankfully I was close to the oven, so I grabbed the largest pan I could and threw up in it while, through streaming eyes, I cleaned up the mess before putting the whole sorry lot into the fire for a decent cremation.

Wednesday, 31 January 2018


I have an interesting relationship with pain. It's been a part of my life forever but not in the way that would make me seem like I'm feeling sorry for myself, or at least not too much.

I grew up with a significant other who had juvenile arthritis, developing into old-git arthritis when they reached their majority. They had one particularly severe bout of it when I was growing up that I can remember, and I'd never seen anyone suffering so much. The experience of watching them destroyed my illusions of what it was to be an adult as they spent what seemed like months getting over it, probably with the use of decent pharmaceuticals. They were undoubtedly hooked on something for years afterwards, and it took ages for them to get off of it (I think I would've stopped on it, TBH).

Then in adulthood, I spent a lot of time in pain clinics and thinking about pain in regards to another significant other. To say their pain affected me is, perhaps, an understatement.

I've had aches and pains since being a teenager. There was the bone chip stuck under my kneecap which stopped me playing sports except for table tennis at school (have you ever played table tennis against yourself for an hour straight: boring!). Then, when I worked nights, I'd often ask my colleagues to drag me along corridors by my legs to ease the pain in my hips. All these aches and pains meant that I was always taking painkillers of one sort or another - my favourite was co-proxamol, but the dodgy dossier put paid to that particular avenue, so it's been double up doses of Paracetamol and Ibuprofen for something like 15 years. And alcohol as well I guess, though that was partly down to needing a wee dram to get me off to sleep after a night shift.

I'd go and donate platelets and make sure I'd not taken any Ibuprofen for 48 hours or Paracetamol for 24. It wasn't always easy, and I had to cancel a couple of times because I'd forget (but only once or twice - nearly made it to 200 before the NSAID put paid to platelet donations). When asked if it were for something recurring I'd have to hold my hand up and say I'd been taking them since I was a teenager for various aches and pains. I had to wait a couple of times while the nurses at the donor centre liaised with medics to check. Check that someone who had near constant headaches, as well as aching fingers, wrists, elbows, shoulders, neck, back (upper and lower), hips, knees, ankles and toes, could donate platelets. They always asked about medical investigations, and I again said there was arthritis in the family and that so far nothing serious had been diagnosed. But I'd be given advice and told to see the GP, and off I went to donate. I always forgot to see the GP because multiple trips during my youth had revealed nothing - I wasn't being stoic, I just didn't want to waste time!

I guessed it was just something that was a little unusual about me... or perhaps everyone else felt like I did and I simply had a lower pain threshold than anyone else. Maybe everyone else ached, and it was merely that I was more sensitive to it, so I put it to the back of my mind and carried on. And I really did carry on! I went to the gym on a semi-regular basis on and off (definitely on at the minute, and it has been for over a year now). I cycled everywhere (easy to do in Cambridge TBH) and at one point had all three of my boys on the bike at once (#1 on a tag along, #2 in a bike seat between my legs and #3 on a bike seat behind me). Boy did we walk as well, whole days during the Summer holidays wandering around Cambridge, walking for miles, but my stride was getting shorter - I put this down to respecting the boys and not striding off and leaving them behind, but it was probably my crumbling hips.

Then, with the diagnosis of AS, I got prescribed a longer lasting and more powerful NSAID. But that was bloody odd! I was snappy as anything for about three days and a right miserable sod and quick to jump down the throats of anyone (sorry Katrina). Then that stopped, and I was right as rain - and was sleeping way past 05:00. Sometimes managing to sleep in, something I'd not managed to do in a long old time. No more staggering out of bed while it was still dark and trying to get myself moving with a cup of coffee, fag and the three S's.

I guess it's not easy trying to get the tone of this down right. I'm not looking for sympathy or anything, just trying to get my feelings down properly about my relationship with my failing body and it's near constant warnings to me (interesting euphemism for the pain that is). I'd been checked over about 18 months before my diagnosis and knew that I had an unhealthy relationship with carbohydrates, but that was solved by knocking bread, rice and potatoes out of my diet (and switching from bitter to lager). The type 2 diabetes is now classed as being in remission, so that worked a treat. My blood pressure is being treated with Statins and seems to be being slowly sorted. What I thought was angina was actually tennis elbow in my shoulder (though maybe it's AS as well?).

I ran out of the NSAIDs last month for three days and went back to Paracetamol and Ibuprofen until the prescription was filled. Not too much of a bother until I got them again, and again, I was a pain to live with for a day or three until I got used to them.

Then came an invitation to take part in a clinical trial. Coming off of them and having an MRI, going back on them and having another after they'd built up and having another MRI to check that they were of some therapeutic use rather than just stopping me feeling the pain. And I'm about a week in and aching again. I used to say that I knew I was alive because I ached, and that was the case, but I'm sort of getting used to living without constant pain. It's the transitions that cause the problem though.

So I'm a week into being NSAID free, and I ache, but I'm used to it now. Posture and exercise as well as eating a healthy diet are helping - as they did before - but I'm planning on what to do when I go back on them... as well as pondering not returning to them due to the serious grumps they seem to engender.

I'm not sure why that is the case though. I know that Paracetamol is linked to a reduction in empathy and there are suggestions that that reduction in empathy is down to a reduction in the pain subjects experience. Apparently feeling pain improves empathy... but that's an interesting thing, in that once my body is acclimatised to it I go back to being less grumpy... and I'm not 100% sure that my ill-temper is down to reduced empathy or just being a git generally.