An interesting article about how you write code to display the correct “one like” or “two comments”, and how that quickly gets more complicated than just “add an -s”, especially when dealing with multiple languages.

Before And After in JavaScript

My last posts have been quite long, so I thought I would try something simpler. Sometimes a function should only be called a number of times. Usually that logic is managed outside of a function, but it is actually very easy to encapsulate that in a wrapper function. For example, to restict the total number of times something can be called for a click event:

var before = function(times, callback) {
    var called = 0;
    return function() {
        if (called < times) {
            return callback.apply(this, arguments);
        }

        called += 1;
    };
}

var simulateClicksOn = function(callback, times) {
    setTimeout(function() {
        callback();

        if (times > 0) {
            simulateClicksOn(callback, times - 1);
        }
    }, 100);
};

simulateClicksOn(before(4, function() {
    console.log('running click event');
}), 10);

To add a function that calls a function only after a number of calls just involves generalizing the before by a simple wrapper:

var clickNum = function(isAfter) {
    return function(times, callback) {
        var called = isAfter ? -1 : 0;
        return function() {
            called += 1;
            if ((called > times) === isAfter) {
                return callback.apply(this, arguments);
            }
        };
    };
};

var before = clickNum(false),
    after = clickNum(true);

These functions are also available in lodash: before after

Code Art Tutorial: Head

We will draw this with JavaScript in a web browser.

1. HTML page

Open a text editor. Start a new file. Type code for a blank HTML page:

<html>
<head>
  <title>empty page</title>
</head>

<body>
</body>
</html>

Save as a plain text file, with a name like head.html. Test in a browser.

2. Add Canvas and Script tags

Between the body tags, add tags for the canvas element and the JavaScript script.

<html>
<head>
  <title>empty page, canvas, and script tags</title>
</head>

<body>
  <canvas></canvas>
<script>
</script>
  
</body>
</html>

Test again. It’s still a blank page.

3. Get Canvas Context

Between the script tags, add code to get the Canvas context. And let’s set the canvas size to 500 by 500.

<html>
<head>
  <title>blank canvas</title>
</head>

<body>
  <canvas></canvas>
<script>
  // get context
  var canvas = document.getElementsByTagName("canvas")[0];
  var c = canvas.getContext("2d");
  // set size
  var maxx = c.canvas.width = 500;
  var maxy = c.canvas.height = 500;
</script>
  
</body>
</html>

Test again. It’s still a blank page, but it’s ready for drawing!

4. Background Color

Let’s start drawing with a background, a yellow rectangle.

<html>
<head>
  <title>background color</title>
</head>

<body>
  <canvas></canvas>
<script>
  // get context
  var canvas = document.getElementsByTagName("canvas")[0];
  var c = canvas.getContext("2d");
  // set size
  var maxx = c.canvas.width = 500;
  var maxy = c.canvas.height = 500;
  
  // background
  c.fillStyle="#ff8";
  c.beginPath();
  c.fillRect(0,0,maxx,maxy);
</script>
  
</body>
</html>

5. Head Circle

Add a circle for the head…

<html>
<head>
  <title>background color, head circle</title>
</head>

<body>
  <canvas></canvas>
<script>
  // get context
  var canvas = document.getElementsByTagName("canvas")[0];
  var c = canvas.getContext("2d");
  // set size
  var maxx = c.canvas.width = 500;
  var maxy = c.canvas.height = 500;
  
  // background
  c.fillStyle="#ff8";
  c.beginPath();
  c.fillRect(0,0,maxx,maxy);

  // head circle
  c.beginPath();
  c.arc(maxx/2,maxy/2, maxy*.45, 0,2*Math.PI,true);
  c.fillStyle = "#88f";
  c.fill();
  c.lineWidth = 9;
  c.stroke();
</script>
  
</body>
</html>

It should look like this:

6. Face

And eyes and a mouth.

<html>
<head>
  <title>background color, head circle</title>
</head>

<body>
  <canvas></canvas>
<script>
  // get context
  var canvas = document.getElementsByTagName("canvas")[0];
  var c = canvas.getContext("2d");
  // set size
  var maxx = c.canvas.width = 500;
  var maxy = c.canvas.height = 500;
  
  // background
  c.fillStyle="#ff8";
  c.beginPath();
  c.fillRect(0,0,maxx,maxy);

  // head circle
  c.beginPath();
  c.arc(maxx/2,maxy/2, maxy*.45, 0,2*Math.PI,true);
  c.fillStyle = "#88f";
  c.fill();
  c.lineWidth = 9;
  c.stroke();
  
  // eyes
  c.beginPath();
  c.arc(maxx/2 *.67,maxy*.33, maxy/8,0, 2*Math.PI,true);
  c.moveTo(maxx/2 *1.33+maxy/8, maxy*.33);
  c.arc(maxx/2 *1.33,maxy*.33, maxy/8,0, 2*Math.PI,true);
  c.fillStyle = "#fff";
  c.fill();
  c.stroke();
  
  // mouth
  c.beginPath();
  c.arc(maxx/2,maxy/2, maxy*.33, 1*Math.PI, 2*Math.PI,true);
  c.stroke();
</script>
  
</body>
</html>

7. Export a PNG

You can add a button and a function to export the canvas to a PNG image.

<html>
<head>
  <title>background color, head circle</title>
</head>

<body>
  <canvas></canvas>
  <input id="createImageData" value="-> PNG" type="button" />
  
<script>
  // get context
  var canvas = document.getElementsByTagName("canvas")[0];
  var c = canvas.getContext("2d");
  // set size
  var maxx = c.canvas.width = 500;
  var maxy = c.canvas.height = 500;
  
  // background
  c.fillStyle="#ff8";
  c.beginPath();
  c.fillRect(0,0,maxx,maxy);

  // head circle
  c.beginPath();
  c.arc(maxx/2,maxy/2, maxy*.45, 0,2*Math.PI,true);
  c.fillStyle = "#88f";
  c.fill();
  c.lineWidth = 9;
  c.stroke();
  
  // eyes
  c.beginPath();
  c.arc(maxx/2 *.67,maxy*.33, maxy/8,0, 2*Math.PI,true);
  c.moveTo(maxx/2 *1.33+maxy/8, maxy*.33);
  c.arc(maxx/2 *1.33,maxy*.33, maxy/8,0, 2*Math.PI,true);
  c.fillStyle = "#fff";
  c.fill();
  c.stroke();
  
  // mouth
  c.beginPath();
  c.arc(maxx/2,maxy/2, maxy*.33, 1*Math.PI, 2*Math.PI,true);
  c.stroke();
  
  // export
  var createImageDataPressed=function(e){
	window.open(canvas.toDataURL(),"canvasImage",
	"left=0,top=0,width="+canvas.width+
	",height="+canvas.height+",toolbar=0,resizeable=0");
	}
  document.getElementById("createImageData").onclick=
  createImageDataPressed;
</script>
  
</body>
</html>

The end result:

anonymous asked:

i've never coded or programmed a single thing, where should i start? :S

Thanks for the question, Anon!

First off:

You’re killing me, Smalls! You’ve gotta be a little more precise with these questions! ;P

I’m assuming that you’re asking about game development stuff since this is a gamedev blog, and I’m assuming you want to learn to code since you didn’t ask “how can I make a game without learning to code?”.

If you’re in school or have the option of taking courses, take a programming course. It’s not super important which language, because you can probably make a game in it. (Yes, even COBOL (probably)) Just google “Make games in [language name]”

Actually, that’s probably a pretty good place to start. I could, conceivably, tell you to google it and learn that way. That’s a pretty legit way to learn things, these days. There are tons of good (and bad) resources out there on the internet.

But I’m not a fan of people just replying “RTFM” or “Google it, noob!” when asked a question in good faith.

So, that being said, here’s your very first programming tutorial:

Open your browser’s Javascript console. In Chrome, it’s CTRL+SHIFT+J or F12. (It’s different in other browsers, here’s a rundown.) You might see a bunch of messages from whatever website you’re on, but ignore them. You should see a place to type. In chrome, it’s a cursor that looks like an angle-bracket: >

Type the following, then hit enter: console.log(’Hello, world!’);

See how it spit out Hello, World! on the next line? Congrats! You’ve just written your first computer program!

You’ve joined the great tradition of learning programming languages with a simple program known as “Hello, World!”

There may be better languages to start learning than javascript, but you asked me and I’m going to say that js is a good enough starting point. Once you learn your first programming language, you’ll probably find that learning others comes easily. (Since I do most of my programming in js these days, I don’t have the resources bookmarked for other languages. If you want resources about learning some other language, I’m afraid you’ll have to ask someone else.)

I’m going to post a few links that I think will help you get started learning javascript as a language, then I’m going to encourage you to continue your learning on your own. It’s like that whole “giving someone a fish” versus “teaching someone to fish” thing (not the same as the “RTFM” thing above).

I highly recommend following a lot of gamedev blogs on tumblr and reading about other peoples’ dev styles and techniques. You can also follow gamedevs on twitter, but some (like me) use twitter more for personal banter than dev stuff, so be careful about letting your stream get clogged up with stuff you aren’t actually interested in.

Anyhow, hope this helps, Anon. :)

youtube
Undefined In JavaScript

Undefined is a confusing type in JavaScript, but first I will start with the obvious cases. Like the null type can only be null, the undefined type can only be undefined. Firstly there is a global undefined variable with the value of undefined:

console.log(typeof undefined);// "undefined"

When a variable is not defined, it is undefined:

var x;
console.log(x);// undefined

When it doesn’t exist, using it will cause an error. Instead its type can be checked for undefined:

console.log(typeof notStated === 'undefined');

All functions with no explicit returns return undefined:

var function1 = function() {};
console.log(function1());// undefined

var function2 = function() {
    return
};
console.log(function2());// undefined

Unlike null, undefined is supposed to represent when something has not been assigned a value. What makes it confusing is that just like null, variables and properties can be given an undefined value. Meaning there could be variables and properties with an undefined value that have been defined. So there is no way to differentiate between a declared but unassigned variable and a non existent one without catching an error:

var x;
console.log(typeof x);// undefined
console.log(typeof y);// undefined
x = undefined;
console.log(typeof x);// undefined

try {
    notStated;
} catch (e) {
    if ((e + '').indexOf('ReferenceError') > -1) {
        console.log(e.message);// notStated is not defined: 
    }
}

Object properties when not assigned are undefined:

var obj = {};
console.log(obj.property1);// undefined

// Remember that array positions are properties too
var arr = [1, 2, 3];

console.log(arr[3]);// undefined
console.log(arr['3']);// undefined

Since properties can also be given the undefined value a different type of check needs to be made:

console.log(obj.hasOwnProperty('property1'));// false
// For checking inherited properties
console.log('property1' in obj);// false
console.log('toString' in obj);// true

Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2015/undefined.js

THOMSOON - Free Responsive HTML Portfolio Theme

Free responsive modern and clean HTML5, CSS3 and Jquery.
Multipurpose Page minimalist website with content about us, portfolio and contact.

Full screen portfolio view and home page with Parallax sidebar. Navigation is sticky to top - header. Ideal for your portfolio and photography showcase.

Keep reading

Variable Chaining And Globals In JavaScript

In many scripting languages assigning variables by chaining multiple equals are allowed. But in JavaScript this can create global variables. For example:

var a, b, c;

(function() {
    var a = b = c = 1;
})();

console.log(a, b, c);// undefined 1 1

It creates globals because it is equivalent to this:

(function() {
    var a = (b = (c = 2));
})();

console.log(a, b, c);// undefined 2 2

As you can see no var is included before, meaning they will become globals. JS will look up each parent scope until it can find a var reference. If it reaches the global scope before finding one, the variable becomes a global. One simple way to avoid this is to declare each variable first:

(function() {
    var a, b, c;
    a = b = c = 3;
})();

Alternatively, to do it in one line, the transivity can be managed in a comma seperator:

(function() {
    var a = 3, b = a, c = b;
})();

Which is equivalent to:

(function() {
    var a = 3;
    var b = a; 
    var c = b;
})();

Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2015/variableChaining.js

JSFuck

JSFuck (created by Martin Kleppe) is not a framework, nor is it an esolang exactly, but an esoteric coding style for JavaScript. While Perl has an entry on esolangs (with particularly choice example code), JS is similarly abusable, even if you have to dig a bit deeper to see its syntactic weirdness and eccentricities. Luckily, we have JSFuck to show us the way. Everything written in JSFuck is valid JavaScript, and works in the browser with no additional framework or plugin. It uses just six characters and resembles brainfuck in appearance.

Here is the letter “a” in JSFuck:

(![]+[])[+!![]]

To explain how this works, we first need to understand that JavaScript is an untyped language (for those who consider it weakly typed, this discussion explains it well). What this means is you don’t specify the kind of data a variable will hold when declaring it; it’s left to the interpreter to determine. When we mix types we often invoke implicit conversions. Let’s say we’re working with a boolean value (true or false). The ! operator converts such a value to its opposite: true to false and vice versa – it’s called the “not” operator (the action of using it is to negate). Take this command:

![]

We are attempting to negate an empty array, forcing JS to treat the empty array as a bool. Since it is not a “falsey value” like null or 0 or undefined, JS determines it’s true, and the negation then makes it false. What valid reason exists to negate an empty array, I have no idea, but this is what the language lets us do. 

So, let’s say we want true, we simply negate false, like so: 

!![] 

JSFuck gets a lot of mileage out of this. From true and false, we get 1 and 0 by converting them to integers with the unary + symbol. This is not the + operator for adding two things, its actual intended usage is to convert something to a number (why???). Applying it to the empty array like so: 

+[] 

gives us zero. To get the number one, we do the same thing to true: 

+!![] 

Or simply take the zero we already have, negate it, and then turn it back into a number: 

+!+[]

With zero and one, we now have a model for how to produce the other numbers. But things get more interesting when we want to produce letters. How do we write the letter “a”? JSFuck has a clever pattern for this. It will produce the word “false” (by converting boolean false to a string) and then grab the second letter. Here is how it’s explained on the esolangs.org site:

  • "a": from string "false", second character (index 1 counting from 0)…
  • "false"[1]: "false" can be made from false+[], i.e. the boolean constant false plus an empty array…
  • (false+[])[1]: we write false as ![] (negation applied to an empty array)…
  • (![]+[])[1]: 1 is a number, we can write it as +true
  • (![]+[])[+true]: since false is ![], true is !![]
  • (![]+[])[+!![]] <<< that’s it!

A JSFuck converter can be found on github. There, we can see how to get the other letters and symbols. Most use the same strategy, grabbing letters from keywords (we get the letter “n” from the string “undefined”, “y” from “Infinity”, “O” from “Object”, etc). You can find them in the jsfuck.js file. 

At JSFuck.com you can try the converter directly.


h/t Rich of prostheticknowledge

4 Line Node.js HTTP Test Server

I don’t usually use libraries in my blog posts, but with just 4 lines of code it is possible to create a simple server HTTP server:

var connect = require('connect'),
    serveStatic = require('serve-static');

connect().use(serveStatic(__dirname)).listen(process.argv[2]);
console.log('Now listening on port', process.argv[2]);

Which is run like:

node server.js 8080

With 8080 being the port number. This will create an HTTP server that can server all the static assets in the directory that server.js is placed. Which is really useful for quickly testing pages in any location on your hard drive when you don’t want to setup a server. Keep in mind that, just opening up the file in the browser can lead to a bunch of issues when accessing external resources on the page.

connect.js is a framework to build servers. While serve-static.js just creates middleware that servers static files at a given location. __dirname is a Node.js constant which gives the current location that a file is in. And finally, process.argv is just the array of all arguments passed to the file (including node).

The libraries can be installed with npm which comes with modern Node.js versions:

npm install connect serve-static

Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2015/server.js