## Convert Anything To A Number

There are many times in JavaScript when you need to scrub the input and give output of a specific type. Today, I will cover how you can convert anything into a number. The function to do so is as follows:

```// Converts any object into a number.
function parseNumber(obj) {
return parseFloat(obj)||+obj||0;
}
```

Now the question is, what happens under different circumstances. Look at (or even try out) the following to find out:

```// Convert any empty string into a number:
var a = "";
var b = parseNumber(a);  // 0

// Convert a string version of a number into a number:
var a = "9563.49";
var b = parseNumber(a);  // 9563.49

// Convert a string starting with space and then a number with extra decimal points into a number:
var a = "    9563.49.2";
var b = parseNumber(a);  // 9563.49

// Convert a sentence into a number:
var a = "I am 23.";
var b = parseNumber(a);  // 0

// Convert an array of numbers into a number:
var a = [129,84,7];
var b = parseNumber(a);  // 129

// Convert a date into a number:
var a = new Date();
var b = parseNumber(a);  // milliseconds since January 1, 1970

// Convert an object literal into a number:
var a = {};
var b = parseNumber(a);  // 0
```

The most interesting of the above test are probably the parsing of dates and arrays. For dates, the number will be the amount of milliseconds since January 1, 1970. For arrays, the number will be the numeric value of the number in the first position of the array.

## Private Variables In JavaScript

Often times, many people have made claims that it is not possible to make variables private in JavaScript. I am here to tell you that those people are wrong. There are many implementations from JavaScript guru’s such as Douglas Crockford explaining how to do this. Although these implementations will get the job done, I have noticed that these implementations do not use prototypal functions. On the contrary, the following shows how to give prototypal functions access to private members:

```// Immediately executed closure to define a person.
var Person = (function() {
// The parameter required to retrieve the private data of a person object.
var theKey = {};

function Person(firstName, lastName, isMale, birthDate) {
// If birth date is a string, convert it to a date.
if(typeof birthDate == "string")
birthDate = new Date(birthDate);
if(isNaN(birthDate.getTime()) || !(birthDate instanceof Date))
throw new Error("the passed birth date was invalid");
// Object literal to keep track of the private data.
var privateData = {
firstName : firstName + "",
lastName : lastName + "",
isMale : !!isMale,
birthDate : birthDate
};
// If theKey is passed as aKey, the private members of the object are
// returned.  Since aKey must be theKey in order to retrieve privateData and
// theKey is an empty object literal, you can be sure that private members
// will not be returned from the function to any code outside of the
// closure.  The only non-prototypal function.
this._ = function(aKey) {
if(aKey == theKey)
return privateData;
};
}

// Alias for the prototype of the Person object.
var p = Person.prototype;

// Get or set the first name for the person.
p.firstName = function(newName) {
// Get the private data members.
var pData = this._(theKey);
// If a parameter was passed, assign the new first name.
if(!arguments.length)
return pData.firstName;
// Set the first name.
pData.firstName = newName;
// Allow chainable calls.
return this;
};

// Get or set the last name for the person.
p.lastName = function(newName) {
// Get the private data members.
var pData = this._(theKey);
// If a parameter was passed, assign the new last name.
if(!arguments.length)
return pData.lastName;
// Set the last name.
pData.lastName = newName;
// Allow chainable calls.
return this;
};

// Gets how many years old the person is.
p.yearsOld = function() {
var now = new Date;  // current date
var birth = this._(theKey).birthDate;  // birth date
var years = now.getFullYear() - birth.getFullYear();  // difference in years
now = now.getMonth() * 100 + now.getDate();  // now as MMDD as number
birth = birth.getMonth() * 100 + birth.getDate();  // now as MMDD as number
return years - (now < birth);  // Return real years old.
};

// Gets the birth date.  Makes valueOf an alias so that people can be compared
// by age.
p.birthDate = p.valueOf = function() {
return this._(theKey).birthDate;
};

// Gets the full name.
p.fullName = function() {
var pData = this._(theKey);
return pData.firstName + " " + pData.lastName;
};

// Get the string representation of this person.
p.toString = function() {
var pData = this._(theKey);
return "I am a " + this.yearsOld() + " year old "
+ (pData.isMale ? "male" : "female") + " named " + pData.firstName + " "
+ pData.lastName + ".";
};

// Allow the person pseudo-class to exist outside of this closure.
return Person;
})();
```

The code above defines a person pseudo-class in JavaScript. There are four members that are private to each instantiated person object: `firstName`, `lastName`, `isMale`, and `birthDate`. The first name and last name can be retrieved and set by using the public getters/setters `firstName()` and `lastName()`. In addition, `fullName()` is another accessor method. The person’s birth date can only be retrieved by using either `birthDate()` or `valueOf()`. In addition, you can find out how many years old the person is by using `yearsOld()`. Finally, you can print the person object out as a string to find all of the person’s information.

Now it is time for the tests:

```var me = new Person("Chris", "West", true, "October 11, 1492");
var harry = new Person("Harry", "Finkelstien", true, "June 4, 1987");

// Show my full name.

// Change Jade's last name and then show it.

// Show how old harry is.

// Show everything about the three people.

// An attempt to retrieve the private members from the outside.
alert("Could " + (me._({}) == undefined ? "not " : "")
+ "access the private members from the outside.");
```

I think the comments explain most of the test code pretty well. One thing to note is that, just because you pass in an empty object literal doesn’t mean that it is the same one that is needed to retrieve the private members.

In conclusion, as is demonstrated in my definition of the Person pseudo-class, prototypal functions can retrieve private members.

## Power Set

As I was beefing up my past implementation of `cartesianProductOf()`, I decided to look into set theory a little bit more. After looking through some Wikipedia pages, I found another process that may be of interest to JavaScript programmers that have to deal with sets: a JavaScript implementation of finding a power set. Here is my code to do this:

```function powerSetOf(arrFull) {
var ret = [], fullLen = arrFull.length, last = fullLen - 1;
function get(arrPrefix, start, lenToFind) {
for(lenToFind--; start < fullLen; start++)
if(!lenToFind)
ret.push(arrPrefix.concat([arrFull[start]]));
else if(start < last)
get(arrPrefix.concat([arrFull[start]]), start + 1, lenToFind);
}
for(var lenToFind = fullLen; lenToFind > 0; lenToFind--)
get([], 0, lenToFind);
return ret.concat([[]]);
}
```

Although the above code works, I couldn’t help think that there was a simpler way of achieving the same goal. After fumbling around the idea in my head, I came up with the following, shorter solution:

```function powerSetOf(arr) {
var item, ret = [[]], max = arr.length - 1;
function fn(arrPrefix, start) {
for(; ret.push(item = arrPrefix.concat([arr[start]])) && start < max;)
fn(item, ++start);
}
if(max + 1)
fn([], 0);
return ret;
}
```

Unlike the first solution, the above one does not return the results ordered by size. On the other hand, this solution is shorter, an works faster.

You may have noticed that neither solution removes duplicates if they exist within the array. If you want to remove all duplicates from an array, you can make a build of jPaq that has the `Array.prototype.uniquify()` function and then use it as follows:

```// Your array of numbers or whatever.
var arr = [1,2,1,3,4,3,2];

// Get the power set for your array.
var arrPowerSet = powerSetOf(arr.uniquify());
```