Monday, 27 March 2017

react environment notes

Just a quick note to capture some of the difficulties I had yesterday getting a react project to sync between my two machines.

There’d been trouble getting the github repo sorted anyway - multiple deletions and re-creations, and two more yesterday - for reasons I can’t properly understand.

Had somehow gotten a filepath nested into a folder as a submodule (I barely know what this means) and none of the online suggestions I found fixed it.

I ended up deleting the whole remote repo, recreating it, deleting the .git directory locally and starting ‘from scratch’. Then I had to delete and clone the repo on my other machine. Ballache.

I did learn how to use .gitignore (I think).

$ touch .gitignore
$ echo node_modules >> .gitignore

Other than node I’m not sure what else I should be gitignoring.

Oh, and I got multiple compile errors with the project on my laptop because I hadn’t installed webpack, react, react-dom, webserver or plugins in the new repo I’d created locally. This shows my basic lack of comprehension of the mechanics of what’s going on, but hey-ho. I’m trying.

Acual react coding stuff, that’s a whole other subject. Separate post for that.

Wednesday, 22 March 2017

testing syntax highligting

    function testSyntaxHighlighting(content) {
        if (
            ```js
            content wrapped 
             ```){
                 content = syntaxHighlighted(content)
                 }
            }

Well what about this?!

Awesome!

What would be even better would be if if it appears properly formatted on Blogger because stackedit pushed the HTML (which it should…).

Let’s Go!

Tuesday, 21 March 2017

CodeWars - Is Ruby Coming?

Is Ruby Coming?

Not a lot to say about this one.

function isRubyComing(list) {  
  return list.filter(obj => obj.language === 'Ruby').length > 0;
}

I was trying to find a less hokey way of asserting the return boolean, but all my efforts at double-negating the function statement failed because an empty array is still a truthy value.

Only on completion did I see what I was looking for in other people’s solutions array.some()

function isRubyComing(list) {
  return list.some(obj => obj.language === 'Ruby');
}

Nice and declarative. I love it.

CodeWars - Greet Developers

Greet Developers

Another good one easy one from Piotr.

After the last exercise I went straight for the .forEach method. I was pretty sure I could just obj.greetdevelopers = [...] and so it was.

Initially I tried to use this.firstName and this.language but that didn’t work and it seems obvious to me now because at the time this is invoked it refers to the object in which the function greetDevelopers’s execution context is created. In this case the global object, I think.

So I replaced it with obj.

Here’s the code I ended up with:

function greetDevelopers(list) {
    list.forEach ((obj) => obj.greeting = "Hi " + obj.firstName + ", what do you like the most about " + obj.language +"?");    
    return list;
}

The function acts on each object in turn, changing it. The list object (and array) is not changed per se - it is identical at the start and end - but each object element within it has been amended.

I couldn’t get the => to work properly. Need to find out about that.

Done.

Other Solutions

Looking at the existing solutions on CodeWars, I notice the top differ slightly from mine:

    function greetDevelopers(list) {
      return list.map(x => Object.assign({}, x, {
        greeting: `Hi ${x.firstName}, what do you like the most about ${x.language}?`
      }))
    }

Object.assign({}, x, {...})) and the ${ } escapes (or whatever you want to call them)…

CodeWars

JavaScript developers from Europe

Made good progress with this quite quickly (once I identitfied that my undefined output was caused by me not calling the function - D’Oh!).

Basic Approach

Once I had the key callback logic down (list.[method](function(object) { ... })) I literally swapped in various methods to figure out the best approach: forEach, map, find etc.

I realised that since filter would only return objects for which the function statement was true, I didn’t need to do anything else except count the members of the resulting array with .length:

    function countDevelopers(list) {
        var responses = list.filter(function(object) {
            return object.continent === 'Europe';
            }
        ); 
        return responses.length; 
    }

Refactoring

I want to start using ES6 notation a bit more since it’s more concise and professional looking ;-)

Got the above code down to:

    const countDevelopers = list =>
      list.filter (obj => obj.continent === 'Europe').length;

Pretty pleased with myself!

Oh No!

Of course I hadn’t read the instructions properly. Wondering why the tests aren’t passing, I eventually realise that not all these devs from Europe are JavaScript devs! Doingggg!

Can I save this without a huge restructuring exercise?!

YES!

With the addition of && obj.language === 'JavaScript'.

Phew!

Monday, 20 March 2017

Monday

Log

Convert HTML Entities (FCC 273)

10:30

Initial test fails.
Error was treating str.replace() like an action. Needed

str = str.replace( x, y );
return str;

11:30

After watching this video I’m going to try writing a function into the replace command.

11:38

Done! defined the conditionals with switch, which feels like the right choice for readability if not brevity.

You don’t have to explicitly pass the regex match to the function call, or use parentheses (which seems syntactically “off”, but hey-ho:

    function convertHTML(str) {

      var match = /[&<>]/g;

      function condRep(match) {      
          switch (match) {
              case "&" :
                return "&amp;";
              case "<" :
                return "&lt;";
              case ">" :
                return "&rt;";
            }
        }

      str = str.replace(match, condRep);
      return str;
}   

convertHTML("Dolce & Gabbana < >");

Just realised in the course of adding that… I’ve not included " or '. D’Oh.
Fortunately the way I’ve written means it should be an easy fix.

11:58

Updated regex variable with ' and " and added 2 new cases. Time to test.

11:59

Failed, but I think because I made an incorrect assumtion that > was &rt; when in fact it should be &gt;

12:01

Done. Took much longer than it ought because of WhatsApp conversations with fellow coders about unrelated stuff.

Spinal Tap Case

More regex fun.

12:33

Overlooked conditions of the challenge again! Can’t just sub spaces for - since some of the test cases don’t delimit by space.

Need to

  • match words by any non-alphanumeric delimiter or caps
  • remove spaces
  • insert dashes
  • decapitalise

12:44

Backreferences weren’t working because I forgot to enclose them with parentheses within the regex / /s.

12:57

As my list of search-replace commands grows, it seems a function would be preferable.

14:23

Hmmm. Didn’t know how to deal with conditionals within the function when they’d been matched by subsets of the regex.

eg /([A-Z])|\s|\W/g/ will match any uppercase letter, whitespace characters and non-alphanumeric characters1, and within the replace statement I could use a backreference, but when the pattern is handed into a function how do I test for caps, symbol, space?

After trying a few things that didn’t work, the only likely method seemed to have a new array of letters via [ABCDEFGHIJKLMNOPQRSTUVWXYZ].split('') or somesuch and that was intolerably clunky to me.

So I’m not sure if my actual solution is any less clunky, as it relies on 4 successive str.replace() statements, one of which contains an anonymous function.

I think it was a pretty poor challenge in terms of being arbitrary test cases. It would have been more difficult but more consistent to have specified how any string may have needed conversion, eg “This%is£A_string+”

Well anyway. It’s done.

Fibonacci sequence

16:44

Finshed this. It was trickier than I thought!

I’ve never had much luck with while loops and this gave me trouble as well.

The main challenge here was assembling the steps in the right order. I think I made pretty good use of the array.slice(-2) (which takes the last two items in the array), array.reduce(function(a,b){return a+b} (to add them) and the ternary conditional to increment the total if odd and leave as is if even.

The stopping condition became the main problem.

I spent ages figuring out where to put another condition that checked the last item in the list (not the total and not nextFib variable!).

Done.


1 - I found this wasn’t true; - was matched by \W but _ wasn’t.

Scheduling

Monday

New week, new opportunities for improvement.

I’ve not been consistent with my coding blog, but for the last week or so I’ve been getting back into freecodecamp.

I’ve done my quote machine (such as it is), and am working my way through the intermediate algorithm scripting without having also done the Weather App, Wikipedia Viewer or Twitch.tv projects.

Is that a bit of a cop-out?

Anyway, that’s where I’m at, but I should probably draw up a new schedule.

To do

Free Code Camp

  • intermediate algorithm scripting
  • advanced algorithm scripting
  • intermediate frontend development projects
    • show local weather
    • build a Wikipedia Viewer
    • use the Twitch.tv JSON API
  • advanced front end development projects
    • javascript calculator
    • pmodoro clock
    • tic tac toe game
    • simon game

Video courses/tutorials

  • Understanding Javascript the weird parts
  • Node.js udemy course
  • backlog of youtube videos

Eloquent JavaScript

  • re-read and complete exercises?

Personal Projects

  • Personal website
  • react experiments
    • input analysis
  • Mum’s website
  • jekyll blog on github?

Sunday, 19 March 2017

Statusline Arrows

I really want to use input mono as my main font for coding, but it seems to push out the alignment on my vim-airline and powerline-shell statuslines.

Rather than get into a whole thing patching fonts with super-tweaked arrow icons I just decided I could live with square separators.

Vim-Airline

Add this to .vimrc:

    let g:airline_left_sep = ''
    let g:airline_right_sep = ''

Add what you like between the quotes for separators.

Powerline-shell

Add --mode flat as a flag to the line that calls the python script in .bashrc.

The other thing I did with powerline-shell was edit powerline-shell.py to the ‘untracked’ character is not u2753, which is not available on any of the patched fonts. I used u26A0 which is a triangle with an exclaimation mark. Seems appropriate.

I also finally figured out that the colors in powerline-shell/themes/default.py are the ones shown here - cterm or something, I dunno.

Backup default.py change the colors as you like, then run ./install.py.

Wednesday, 1 March 2017

React Structure

Been working on react for a few weeks now. My project is the cards-face-down-memory-game. Feels Iike I’ve been making no progress for forever… but of course I have.

Today

I got some insight into what the container app’s state is all about. And Tom confirmed for me that my original concept - that each component of the app should only deal with the logic and state data it needs to - was correct.

This notion of functional and presenational containers must just not be particularly appropriate to my chosen project and level of complexity.

I used youtube to share a link to gomix. It was not good but I thought hey, I need to expose myself in public.

Next

It feels super-ugly to me to have a bunch of class functions that are chained togther just to produce the initial state. I think relegating them to helper functions is the way to go; cleaner code and it lets me get started with TDD.