Intro Javascript Data Structures & Commander.js 

v1.0

Narkoz's Rule for SysAdmins

"if something — anything — requires more than 90 seconds of my time, I write a script to automate it."

When late, sends a text message "late at work" to his wife and "automatically picks reasons" from a preset list of them

Results: 

If he wasn't at work and logged in to the servers by 8:45 AM, sends a text message "not feeling well, working from home" - He calls the script "hung over"

v1.0

Ric's Rule for Devs

"if you do something - anything more than 3 times, write a script to automate it"

But how?

with a node.js library called Commander

and some basic data structures

Use JavaScipt

v1.0

Tonight's Topics

 

  • We are going to code - help each other
  • Intro C9 Environment
  • Bash Baby Steps
  • JavaScript Scripts
  • CLI Apps with Commander
  • The List Data Structure
  • The Ordered List Data Structure
  • The Queue Data Structure

v1.0

Prepare Your C9 Workspace

Click on Create a new workspace

Workspace Name: data_struct_commander_s1

Login to C9

v1.0

Clone from Git or Mercurial URL:

https://github.com/ricmclaughlin/data_struct_commander_S1.git

Select: Blank Template

The C9 Workspace

Terminal or CommandLine

Project Navigator

Editor

Preview

v1.0

Did it work?

but first a tiny bit o' bash! 

# <- the hash make a comment in bash

# type this next line in and notice it does NOTHING

# type me in - I am a comment
# use pwd to show what directory are we in!

pwd

How do I make a comment?

What directory am I in?

v1.0

Did our setup work?

# use ls to see if npm install worked...

ls

# we should see a node_modules subdir
# what is in the node_modules subdir?

ls node_modules

What files and directories are there?

v1.0

# use npm install -> npm reads package.json and installs the needed packages

npm install

Install our dependencies with npm

# use ls to list files and subdirectories

ls

What files and directories are there?

Let's see some magic

# use node to run a JavaScript app

node ricname.js

Run an amazing CLI App!

v1.0

Editor

#!/usr/bin/env node

console.log('Ric!');

What do you see?

Let's create some magic

# use node to run your app

node myname.js

User Story: Output your name

v1.0

#!/usr/bin/env node

console.log('[YourName]');

Create a new file - 'myname.js'

Print an Argument(s)

# pass in your name as an argument like:

node myname2.js [myname]

User Story: Pass in your name as an argument and output it

v1.0

#!/usr/bin/env node

console.log(process.argv);

Create a new file - 'myname2.js'

What do you see???

Print Just One Argument

# copy myname2.js => justmyname.js using the cp command

cp myname2.js justmyname.js

User Story: Pass in your name as an argument and output it

v1.0

#!/usr/bin/env node

//your app should look like this!

console.log(process.argv[2]);

Change justmyname.js to use process.argv[2] element that represents your name argument

# pass in your name as an argument like:

node justmyname.js ric

Print Two Arguments

# copy justmyname.js => printmynameage.js using the cp command

cp justmyname.js printmynameage.js

User Story: Pass in your name and age as arguments and output them

v1.0

#!/usr/bin/env node

// your app should so this
console.log('My name is ' + process.argv[2]);
console.log('My age is ' + process.argv[3]);

Change printmynameage.js to use your name & age arguments and include "My Name is " and "My Age is "

# pass in your name and age as an argument like:

node printmynameage.js ric 34

Enter commander.js

  • A node.js option parsing library for command line apps
  • Named arguments
  • Optional arguments
  • Easy to coerce Args into arrays and other types

JavaScript Script Limitations

  • Args are order specific
  • Args are required
  • Args are simple, space-delimited, strings

v1.0

A Tour of Commander Options

# complete.js is a tour de force of commander.js excellency

node complete.js -s car,boat,bike -c bob -c larry -n 1,2,3 -i 5

node complete.js -f 1.3 -r 1..3 booger -s 1,2,3

v1.6

Open complete.js

Print Two Arguments (again)

# copy complete.js => printmynameage2.js using the cp command

cp complete.js printmynameage2.js

User Story: Pass in your name and age as arguments and output them

v1.0

Change printmynameage2.js to use your name & age arguments and include "My Name is " and "My Age is "

# pass in your name and age as an argument like:

node printmynameage2.js -n ric -a 34

# app returns a sorted list of fruit or something like:
My Name is ric
and My Age is 34

Use built in type coersion

# copy printmynameage2.js => iam5yearsyounger.js using the cp command

cp printmynameage2.js iam5yearsyounger.js

User Story: Pass in your name and age as arguments, then subtract 5 from your age and output them

v1.0

Change iam5yearsyounger.js to use your name & age arguments and include "My Name is " and "My age 5 years ago was "

# pass in your name and age as an argument like:

node printmynameage2.js -n ric -a 34

# app returns a sorted list of fruit or something like:
My Name is ric
My age 5 years ago was 29

What is a List?

3.2

'chicken'

['bob', 'bill']

true

myList

# Create an empty array called myList(NOT new Array())

var myList = [];

# add string

myList[0] = 'chicken';

# add a number

myList.push(3.2);

# add an array

myList.push(['bob', 'bill']);

# In one statement

var myList = ['chicken', 3.2, 'scotch', true, ['bob', 'bill']];

# add a boolean

myList.push(true);

v1.0

Common Arrays as Lists Methods

# how long is my list?
# length is a property NOT a method

var len = myList.length;

# does an element exist in the list?
# returns -1 if not found

var incChk = myList.indexOf('chicken');

# iterate through list.. and do something!

myList.forEach(logArrayElements);

function logArrayElements(element, index, array) {
  console.log('a[' + index + '] = ' + element);
}


v1.0

Sorting Numeric Arrays as Lists

# sorting of arrays is alphabetic
# notice the number sort problem!!

myList.push(10);
console.log(myArray.sort());

-> [ 10, 3.2, [ 'bob', 'bill' ], 'chicken', true ]

# pass the sort() method a sorting function for numbers
# this sorts increasing

console.log(myList.sort(sortNumber));

function sortNumber(a,b) {
    return a - b;
}

-> [ 3.2, 10, [ 'bob', 'bill' ], 'chicken', true ]

v1.0

Make an sorting list app

# copy complete.js => move.js using the cp command

cp complete.js listapp.js

User Story: Pass in a string list and output it sorted

v1.0

Edit listapp.js

# pass in some fruit

node listapp.js -f tangerine,orange,apple,pear


# app returns a sorted list of fruit
-> apple orange pear tangerine

Code snippets in the list.js file!!

What is an Ordered List?

'bake cake'

'heat oven'

'eat cake'

myOrderedList

# Create an ordered list which is simple an array

var myOrderedList = ['heat oven', 'bake cake', 'eat cake'];

v1.0

A list where the order is important!

[0]

[1]

[2]

Ordered List Methods

// access element by index
var el1 = myOrderedList[1];
console.log('Element 1 in myOrderedList is %j', el1);

var elLast = myOrderedList[myOrderedList.length - 1];
console.log('The last element in myOrderedList is %j', elLast);
// find the index of an element
var indexOfEatCake = myOrderedList.findIndex(eatCake);
function eatCake(element) {
  return element === 'eat cake';
}
console.log('"eat cake" is element %j in the myOrderedList', indexOfEatCake);
// use a for loop to access elements by index 
//(skip the last element in the ordered list)

for (var i = 0; i < myOrderedList.length -1; i++) {
  console.log(myOrderedList[i]);
}

v1.0

Make an ordered list app

# copy complete.js => move.js using the cp command

cp complete.js move.js

User Story: Pass in roll-over,sit,crawl,walk,run and output the developmental stages in order

v1.0

Edit move.js

// pass in the developmental stages

node move.js -m roll-over,sit,crawl,walk,run

// app returns this:
First, I roll-over,
then I sit,
then I crawl,
then I walk,
then I run.

Code snippets in the orderedlist.js file!!

What is a Queue?

'light fuse'

'find

dynamite'

myQueue

// Create a queue which is simply an array

var myQueue = ['find dynamite'];

v1.0

A list where elements are processed in order then removed in a First-in, First-out method

[0]

[1]

// Add an element

myQueue.push('light fuse');


// process an element
// remove it from the front of the queue

myQueue.shift(0);


'light fuse'

'light fuse'

myQueue

[0]

[1]

Make a Queue App

# copy complete.js => dyn-o-mite.js using the cp command

cp complete.js dyn-o-mite.js

v1.0

Edit dyn-o-mite.js

// pass in the developmental stages

node dyn-o-mite.js -q 'find dynamite','light fuse', 'RUN!!'

// app returns this:
find dynamite - next tasks: light fuse, RUN!!
light fuse - next tasks: RUN!!
RUN!! - next tasks: none

Code snippets in the queue.js file!!

The End

Intro Javascript Data Structures & Commander.js

By Ric McLaughlin

Intro Javascript Data Structures & Commander.js

  • 1,676