javascript-site

A Difference Between JavaScript Arrays and Associative Arrays

I’ve been crunching a large government dataset for a project I’m working on. I had to key an array with the ids of some of the data. However, I noticed when I tried to stringify my array, it produced a ton of null values. It took me a second to realize this:

// an associative array in javascript is really just an object
var assoc = {};
// a numerical array is an object with an array constructor
var keyed = [];

// generate some random items for an array
for(var i = 0; i < 1000; i++) {
  var rand = Math.floor(Math.random() * 10000 + 1);
  assoc[rand] = rand;
  keyed[rand] = rand;
}

// count the number of items in the assoc array
var count = 0;
for(var name in assoc) {
  count++;
}

// log them out so we can see the difference
console.log("assoc length = " + count);
console.log("keyed.length = " + keyed.length);

See the Pen eNBNpz by Mike Newell (@newshorts) on CodePen.

 

 

You can see from the above you cannot key a javascript array with random values without the array constructor putting in the missing keys as null. Basically, this makes sense if you look at how arrays are stored in memory, it would be mayhem if you tried to store random keys. So in some cases, you’re better off using a javascript object in literal fashion and key it like you would the array. This way you only need to parse the items stored and not the missing keys.

javascript-site

Javascript Inheritance: Prototype not Available in Instances

Just for reference. You may be dealing with Javascript inheritance and wondering how the hell you can look things up? For instance, lets say I have a Javascript class for animal, then another for cat and finally one for a tabby cat. Let’s say I’ve defined some things in each and I want to know what methods I can call? Well, if you just log out the instance of the tabby named chester, you’ll see you done have a wonderful birds eye view of the tabby cat name chester. In fact, the only thing you’ll see is that you have public instance methods and properties. Where is the “meow” function? Where is the “walk” function?

function Animal(name, legs, species) {
	this.name = name;
  this.legs = legs;
  this.species = species;
  
	var walk = function() {
    console.log("pitter patter");
  }
  
  this.walk = walk;
  
}

function Dog(name) {
	this.name = name;
  this.legs = 4;
  this.species = "Canis lupus familiaris";
  
  this.bark = function() {
		console.log("woof woof");
  }
}

function Cat(name) {
  this.name = name;
  this.legs = 4;
  this.species = "Felis catus";
  
  this.meow = function() {
    console.log("meow!");
  }
}

Dog.prototype = new Animal();
Cat.prototype = new Animal();

function Tabby(name) {
	this.name = name;
  this.legs = 4;
  
  this.lookOutWindow = function() {
    console.log("sitting by the window staring at bugs");
  }
}

Tabby.prototype = new Cat();

var chester = new Tabby("Chester");
console.log(chester);

So how can we programmatically check to see if a method or property is available for us to use? Let’s say we have a cat with two legs (that can happen), now the method “walk” should be unavailable to us. You might try and use “hasOwnProperty”, but that would return false:

// does not have a species
console.log("chester.hasOwnProperty(\"species\") = "+chester.hasOwnProperty("species"))
// but obviously its working here:
console.log(chester.species)

So what do we do? Well, there are a couple options…

If you inspect an object in chrome, you will see there’s no property name prototype. That’s because prototype is used by javascript to construct the object, once its complete it’s not available as an object itself, however, you can still call “hasOwnProperty” on “hasOwnProperty” of a prototype (that’s confusing). There is a property of the object called “__proto__” but if you try to traverse it, you might find that property confusing (more here: http://stackoverflow.com/questions/9959727/proto-vs-prototype-in-javascript).

So let’s construct our methods a different way. Let’s say any time we call “new [Object]” we will also define a constructor and a parent. Then at the very least, we have something to reference inside our instances:

Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
Cat.prototype.parent = Animal.prototype;

Tabby.prototype = new Cat();
Tabby.prototype.constructor = Tabby;
Tabby.prototype.parent = Cat.prototype;

Now when we log out our instance of chester, we can see it’s fairly easy to call our parent. Now it’s fairly easy to tell how to access methods if you simple print out the object. Let’s put it all together:

function Animal(name, legs, species) {
	this.name = name;
  this.legs = legs;
  this.species = species;
  
	var walk = function() {
    console.log("pitter patter");
  }
  
  this.walk = walk;
  
}

function Dog(name) {
	this.name = name;
  this.legs = 4;
  this.species = "Canis lupus familiaris";
  
  this.bark = function() {
		console.log("woof woof");
  }
}

function Cat(name) {
  this.name = name;
  this.legs = 4;
  this.species = "Felis catus";
  
  this.meow = function() {
    console.log("meow!");
  }
}

Dog.prototype = new Animal();
Cat.prototype = new Animal();

function Tabby(name) {
	this.name = name;
  this.legs = 4;
  
  this.lookOutWindow = function() {
    console.log("sitting by the window staring at bugs");
  }
}

Tabby.prototype = new Cat();

var chester = new Tabby("Chester");
console.log(chester);


// does not have a species
console.log("chester.hasOwnProperty(\"species\") = "+chester.hasOwnProperty("species"))
// but obviously its working here:
console.log(chester.species)

// now lets check the prototype
console.log(chester.__proto__)
console.log("chester.__proto__.hasOwnProperty(\"species\") = " + chester.__proto__.hasOwnProperty("species"));
console.log(chester.__proto__.species)

// instance method
chester.lookOutWindow();

// now for the inherited methods:
// defined in cat
chester.meow();
// defined in animal
var walk = chester.walk;
walk();

See the Pen OVbLmY by Mike Newell (@newshorts) on CodePen.

Anyway, hope that clears things up a bit.

featured-site

Blow Up Doll High Five with Arduino and a Relay

We wanted to make a “high five” bot at work, because…

This was my first test, basically, an arduino runs a sonar range finder, when it detects an object within a certain distance, it activates a relay which allows current to flow into an air pump resulting in the blow up arm extending for a high five!

Here’s the code:

const int pump = 11;
const int pingPin = 7;

long in;

void setup() {
  Serial.begin(9600);
  pinMode(pump, OUTPUT);
}

void loop() {
  in = ping();
  
  if(in < 7) {
    digitalWrite(pump, HIGH);
    // fill the arm
    delay(2000);
  }
 
  digitalWrite(pump, LOW);
  delay(100);

}

long ping() {
  long duration, inches, cm;
  
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);
  
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);
  
  inches = microsecondsToInches(duration);
//  cm = microsecondsToCentimeters(duration);
  
  Serial.print(inches);
  Serial.print("in, ");
//  Serial.print(cm);
//  Serial.print("cm");
  Serial.println();
  
//  delay(100);
  
  return inches;
}

long microsecondsToInches(long microseconds)
{
  // According to Parallax's datasheet for the PING))), there are
  // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
  // second).  This gives the distance travelled by the ping, outbound
  // and return, so we divide by 2 to get the distance of the obstacle.
  // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}

If you don’t know how to wire a relay, refer here: http://iwearshorts.com/blog/how-to-wirecontrol-a-relay-with-arduino-or-raspberry-pi/

I used:

  • a JZC-11F relay (5V vcc and 120V rating up to 5 Amps)
  • air pump from amazon
  • ping sonar finder
  • arduino
  • diode
  • leds (for effect)
javascript-site

Easily Embed Javascript into a Gif Header

ok, first off, don’t do this…

Let’s say you find a website where you can add “script” tags to a page. Well usually, you can’t do anything with it since browsers won’t let you execute a file from another site. To work around that, we can load a gif in the source:

<script src="something.gif"></script>

Well, your browser will think that’s fine, but it will also to to interpret the encoding of the image as javascript. So now all we need to do is insert some ascii chars…

mn has a good tutorial on how to finish this up over here: http://jklmnn.de/imagejs/

Here are some more resources:

Have fun!

relay-site

How to Wire/Control a Relay with Arduino or Raspberry Pi

Let’s say you want to control a light/air pump/device from a microcontroller or raspberry pi…

We’re assuming the device in question is one that can easily be controlled simply by turning the power on and off.

You can use a relay. Basically these things are physical switches mounted inside a block with a small inductive coil next to it. When you push 5V through the coil, it creates a large enough magnetic field to pull the switch from one state to the other (on to off and vice versa). You just need to make sure the relay you’re using is rated for the voltage/current you’ll be pushing.

In my case, I wanted to push 120V at no more than 5 Amps through the relay to an air pump that would switch on and off depending on my arduino. I bought a JZC-11F relay and went to work, below is a wiring diagram:

relay

You can see above, I’ve got pin 11 wired to one side of the coil on the relay and ground on the other. When pin 11 is “HIGH” it causes the relay switch to flip and allows current to flow through. On the other side I have a simple LED wired to the output of the relay switch and ground. When the switch turns on, current flows through the relay and turns the LED on. I’ve also included a diode across the coil to prevent voltage backflow into the arduino. Sometimes when a current is high enough, the coil can build up a voltage, when pin 11 goes to “LOW” that voltage needs someplace to go, without a diode, the voltage could flow back into the arduino, damaging it. The diode prevents flow in this direction.

Here’s a quick video explaining the actual test:

And here’s the code:

// Pin 11 has an LED connected on most Arduino boards.
// give it a name:
int led = 11;

// the setup routine runs once when you press reset:
void setup() {                
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);     
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}

That’s it, next I’ll post something about what I did with this circuit!

bash

Recursive Function to Capitalize Words in an Array

Every once in a while, someone writes something bullet proof in as little as a couple lines. Here’s something I got off code academy that I thought might be useful to people:

// Our array of messy words
var capitals = ["berlin", "parIs", "MaDRiD"];

// Capitalize function
function capitalize(word) {
  return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
}

// Our recursive function
function fixLetterCase(array, i) {    
  // Base case
  if (i === array.length) {
    return;
  } 
  // Action
  array[i] = capitalize(array[i]);
  $('p').append(array[i] + '<br />');
  
  // Recursive case
  return fixLetterCase(array, i + 1);
}

// Here is our function call
fixLetterCase(capitals, 0);

See the Pen oXLydm by Mike Newell (@newshorts) on CodePen.

There are two things going on here, the “capitalize” function, which takes any string and capitalizes the first letter, then lower cases the rest of the string by slicing it at “1”. The other function is a recursive function that iterates through all the elements in the initial array and runs the capitalize function on every single one.

The bullet proof part is the “capitalize” function, it will work on almost any situation where a string is passed to the function without counting letters, character by character. It let’s JavaScripts native string functions do all the work. Very well written.

wordpress

Custom Linked Images in WordPress Page Gallery

Let’s say you spent all weekend building your girlfriends portfolio site and you want an easy way to output linked images on a page. You might think “easy enough, I’ll just put in a gallery on the page. She can manage her images from there!” But then you hand your site to your gf and she says “can I link those images to other sites?”…

We’ll, yeah. Here’s how.

She will manage images on the page through the wordpress gallery. For every image she wants to link out some place, you will have her put the link in the “alt text” input field on the backend:

alt_textThen you will pick this alt text out of the post meta and read it into your template. Here’s an example:

<?php
    $gallery = get_post_gallery( get_the_ID(), false );
    $idsArr = explode(',', $gallery['ids']);
    $template = '';
    
    if($idsArr) {
        foreach($idsArr as $key => $id) {
            
            $url = wp_get_attachment_url( $id );
            $alt = '#';
            $alt = get_post_meta($id, _wp_attachment_image_alt, true);
            
            $template .=    '<a href="' . $alt . '"><img src="'.$url.'" /></a>';
            $template .=    '<br />';
            
        }
    }
    
    echo $template;
?>

This code lives in “content-page.php” of my theme file, but you may have reason to put in into your “page.php” file directly.

 

bash

Slow Recursion

Let’s say you want to do something in a for loop, but you can’t seem to make it run with a delay in between loop iterations (let’s assume you’re working in something like JavaScript where the “setTimeout” function is non-blocking and will execute immediately).

Not to worry, the standard approach would be to write a recursive algorithm and do “setTimeout” before you call the next iteration of the recursion.

My solution is usually to embed a recursive algo in a closure, or self executing function. This way everything stays tight and you can define it in another higher level function so as not to make your code messy. See below:

var delay = 1000;              
var count = 100;
(function loop(i) {
    setTimeout(function() {
        // do something here
        if(--i) {
            loop(i);
        }
    }, delay);
})(count);

What’s nice about this is the fact that it negates the need for globals dedicated to the recursion. It’s also embeddable, see this example below where I output messages every 2 seconds:

 

function logMessages(msgs) {
    (function loop(i) {
        setTimeout(function() {
            var idx = i - 1;
            console.log(msgs[idx]);
             
            // if i != 0 loop again
            if(--i) {
                loop(i);
            }
        }, 2000);
    })(msgs.length);
}

logMessages(["things", "stuff", "awesome"]);

See the Pen waGBNa by Mike Newell (@newshorts) on CodePen.

microphone

Web Speech API

Made a quick library (https://github.com/newshorts/WebSpeechJS) last week that’s working alright for me. Thinking of making it an actual project on github. Just wanted to post a little blurb about it here, before I add documentation and make it a real thing.

It’s called WebSpeechJS. Basically, it just makes it easy to loop the web speech API return (primitive and final) text and call it into a callback.

Use it like this:

<!-- include the js file -->
<script src="path/to/js/webspeech.js"></script>
<script>
    // when the window loads call the script
    var options = {
        startButton: $('.start'),
        stopButton: $('.stop'),
        tmpOutput: $('.tmp'),
        finalOutput: $('.final'),
        onResult: handleWebSpeechResult
    };
    var ws = new WebSpeech($, options);

    // start the processes
    ws.init();
</script>

<!-- then in your page template, include necessary the elements -->
<p class="tmp"></p>
<p class="final"></p>
<button class="start">Start</button>
<button class="stop">Stop</button>

That’s it for now, easy peasy.

DEMO