koala-moon

Category: coding

  • Vue.js – Azure Pipelines

    I had a requirement to automate the CI/CD pipeline of an existing Vue.js project.

    What was asked…

    1. On any merge into the branch “releases/dev
    2. Run all unit tests
    3. Build for the development/staging environment
    4. Copy the files to Azure Blob storage so they can be used as a SPA

    The project repo was already in Azure Dev Ops

    trigger:
      - releases/dev
    
    pool:
      vmImage: "ubuntu-latest"
    
    steps:
      - task: NodeTool@0
        inputs:
          versionSpec: "12.x"
        displayName: "Install Node.js"
    
    - script: |
        npm install
        npm run test:unit
      displayName: "npm install"
    
    - script: |
        npm run test:unit
      displayName: "npm run test:unit"
    
    - script: |
        npm run build:dev
      displayName: "npm run build:dev"
    
    - task: AzureCLI@2
      displayName: "Copy files to blob storage"
      inputs:
        azureSubscription: 'Faux-Development-ltd'
        scriptType: 'bash'
        scriptLocation: 'inlineScript'
        inlineScript: 'az storage blob upload-batch -d \$web --account-   name "blobStoreName" -s "dist" --connection-string "DefaultEndpointsProtocol=https;AccountName=xxxxxx;AccountKey=123456789123456789/qwerty/qwertybangbang==;EndpointSuffix=core.windows.net"'

    The only sticking points where.

    The blob store container is called $web which look like a variable in the shell script so I had to use \$web

  • JS does a string/number exist within a nested array collection?

    I have the following and need to test if a user id is present anywhere in the collection.

    const meetingCollection = [
      { id: "2", userIds: [12, 34, 55, 6, 7, 43543, 45345, 545] },
      { id: "21", userIds: [3, 425, 5, 33, 7, 68, 76, 99, 66, 99] },
      { id: "22", userIds: [767, 5654756, 5658, 86, 45, 23456, 666] },
      { id: "23", userIds: [6, 43562, 5645747, 4654, 2577, 4345, 45777] },
      { id: "24", userIds: [45645, 124, 4, 435, 6, 7755, 7, 8] },
      { id: "25", userIds: [1, 2, 455, 647, 753] },
    ]
    const queryString = 7755;
    
    meetingCollection.some(m => m.userIds.some(userId => userId === queryString))
    

    Array.prototype.some() tests the method against each “row” of the collection and returns true on the first hit and then stops. If you have a 1000 elements and the method returns true on the 10th iteration .some() stops looping over the collection and returns true.

    If a method fails to return true then false is returned.

    The above example I’ve nested .some()

    Try this in the console….

    const meetingCollection = [
      { id: "2", userIds: [12, 34, 55, 6, 7, 43543, 45345, 545] },
      { id: "21", userIds: [3, 425, 5, 33, 7, 68, 76, 99, 66, 99] },
      { id: "22", userIds: [767, 5654756, 5658, 86, 45, 23456, 666] },
      { id: "23", userIds: [6, 43562, 5645747, 4654, 2577, 4345, 45777] },
      { id: "24", userIds: [45645, 124, 4, 435, 6, 7755, 7, 8] },
      { id: "25", userIds: [1, 2, 455, 647, 753] },
    ]
    
    const findId = (queryString) => {
      return meetingCollection.some(m => m.userIds.some(userId => userId === queryString))
    }
    
    console.log(findId(2577)); // true
    console.log(findId(257)); // false
  • JS rounding numbers

    I have a requirement to be able to round numbers to either a whole number or to a specified number of decimal places….

    Every now and then i find myself looking over my current solution to a problem when applying it in a new project. In this case it was very simple statistics and mean values.

    For example:

    const dec = [2, 678, 65.67467, 10.5452453453, 1, 0];
    // Required outcome to 3 decimal places
    // 2, 678, 65.675, 10.545, 1, 0
    
    // Or to 2 decimal places
    // 2, 678, 65.67, 10.55, 1, 0

    My solution:

    const round = (n, decimal = 2) => {
        return Math.round(n * Math.pow(10, decimal)) / Math.pow(10, decimal);
    };
    // Quick test
    dec.forEach(n => {
    console.log(round(n, 3));
    });
    
    dec.forEach(n => {
    console.log(round(n));
    });

    As an aside: I need to have a set of numbers rounded and set with 2 fixed decimal places. So the same data set would be:

    const dec = [2, 678, 65.67467, 10.5452453453, 1, 0];
    
    // Required response would be
    // 2.00, 678.00, 65.67, 10.55, 1.00, 0.00

    There is the Number.toFixed() method

    dec.forEach(n => console.log(n.toFixed(2)));
  • Finding, replacing, deleting and adding to a nested collection

    Problem: I have an object that has a field call modules that is and array of activities. Activities is itself a complex and many nested object. I need to hunt for activities by their IDs and replace, delete or insert between existing objects

    // Replace object in collection
    Object.keys(data.modules).forEach(modKey => {
      Object.keys(data.modules[modKey].activities).forEach(activityKey => {
        if (data.modules[modKey].activities[activityKey].id === newActivity.id) {
          data.modules[modKey].activities.splice(activityKey, 1, newActivity);
        }
      });
    });
    // Remove object in collection
    Object.keys(data.modules).forEach(modKey => {
      Object.keys(data.modules[modKey].activities).forEach(activityKey => {
        if (
          data.modules[modKey].activities[activityKey] &&
          data.modules[modKey].activities[activityKey].id === newActivity.id
        ) {
          data.modules[modKey].activities.splice(activityKey, 1);
        }
      });
    });
    // Insert object at index
    const moudleIndex = 0;
    const activityIndex = 2;
    
    Object.keys(data.modules).forEach(modKey => {
      if (modKey == moudleIndex) {
        Object.keys(data.modules[modKey].activities).forEach(activityKey => {
          if (activityKey == activityIndex) {
            data.modules[modKey].activities.splice(activityKey, 0, newActivity);
          }
        });
      }
    });

  • REGEX Examples with explanations

    A string 24 characters in length and only with hexadecimal letters and numbers

    Example use: In MongoDb the unique id’s (ObjectId)

    The string must be 24 characters long. ^ Starts of string or start of line, $ end of string or line; both dependent on the “multi-line mode”

    /^{24}$/

    Hexadecimal uses only the letters “a to f” and the number “0 to 9”

    /^[a-f0-9]{24}$/

  • Javascript – distinct values from an array

    The problem: How to get the unique values from this array?

    const userIds = [12, 14, 44, 12, 56, 30, 12, 14]

    ES6 solution

    const unique = [...new Set(usersIds)]; 

    Returns

    [12, 14, 44, 56, 30]

  • REGEX 2

    Okay in the previous post we had found the “find” tool and realised we can do so much more with it using regular expressions (regEx).

    To recap a regEx is

    “a sequence of symbols and characters expressing a string or pattern to be searched for within a longer piece of text.”

    \d = a character 0 to 9

    \w = any character a to Z and 0 to 9

    \s =  whitespace

    Example:

    \d\d\d will (using the find tool in your text editor) will highlight groups of 3 numbers in a string

    \w\w\w\w\w will highlight groups of 5 characters

    Notice how \w\w\w included numbers and letters

    \s\s will highlight double spaces

    Lets look for words that have only 4 characters.

    A 4 letter word can be described as,

    “a space followed by any 4 characters, followed by a space”

    \s\w\w\w\w\s

    Which can be rewritten as

    \s\w{4}\s

    But that will also include numbers. To ignore numbers

    \s\w{4}[a-z]\s

    Not quite there, if you are playing along you will notice that we are highlighting 4 letter words and the space before and after. What we need is to set boundaries.

    \b\w{4}[a-z]\b

    \b is a boundary, there are a few but for now lets stay with ‘spaces’. So with that you can find all four letter words

  • REGEX 1

    Part 1 of understanding regular expressions (regEx).

    RegEx is not just useful when writing code ( across different languages they are broadly similar) but I have found knowing a bit allows me to quickly become a “power user” when using the find replace functions in text editors like VSCode and PHPStorm.

    If you are using VSCode bring up the “find” box and have a look for the icon .*

    So instead of just searching for a text string you can quickly scan more accurately.

  • PHP7 The Null Coalesce Operator

    This is a simple and quick to describe, it will even save you a bunch of typing.

    Before PHP 7

    $name = isset($_POST['name']) ? $_POST['name']  : 'Default name';

    Now with PHP 7

    $name = $_POST['name'] ?? 'Default name';

    Soooo much better

  • What they never tell you about GitHub

    GitHub is brilliant…. There are loads of tutorials, video and articles out there, recently I’ve spent time filling gaps in my Git version control knowledge and something struck me as odd. Every tutorial should make it clear right from the start and reminders throughout their presentations that you

    DO NOT STORE PASSWORDS, KEYS, USERNAMES, CREDENTIALS, ETC. ON GIT HUB

    Why?

    Because there are bastards out there who are scanning git repositories for anything that could help access secured areas or consume resources they should not.

    Git does scan your repo’s and will warn you but its not in real time so be warned. Still not convinced? The image is of a free Amazon Web Service account that was set up as a learning exercise the keys where saved in a Git Repo and over the course of 3 days a free account had racked up nearly $10,000US .

    What can you do, if you accidentally commit a password, key, etc? Delete the branch? Roll back?

    No!

    The best advice and this is also given by Git themselves is to consider your data compromised and your accounts that use the data hacked. Once again, rolling back and deleting does not work.

    So reset your passwords/key etc and don’t just add a 1 at the end or swap out vowels for 12345.

    How do you manage password and environment values?

    Have a Google for git .gitignore or visit dotIgnore on GitHub