I've got some constructors and a factory class that I would like to use in an Angular project. I would like to know how I can convert these to usable Angular services for my project.
Process Constructor
/**
* A constructor for Process objects
*
* @param {Object} options An object with an integer processId and an array of roles containing
* roles
*
* @return {Process} A new Process object
*/
function Process (options) {
if ( typeof options.processId !== 'number' ) {
throw 'Process ID is not a number';
}
if ( typeof options.roles !== 'object' || typeof options.roles.length === 'undefined' ) {
throw 'Roles is not an array';
}
if ( options.roles.length === 0 ) {
throw 'No roles passed';
}
this.processId = options.processId;
this.roles = options.roles;
return this;
}
This is pretty straight forward. A bit of input checking then return the object.
Role Constructor
/**
* A constructor for Role objects
*
* @param {Integer} processId An integer representing this role's parent process ID
* @param {Integer} number What number to assign the roleName attribute
*
* @return {Object Role} A brand new Role object
*/
function Role (processId, number) {
// typecast
processId = +processId;
number = +number;
if ( !!isNaN(processId) || !!isNaN(number) ) {
throw 'Both processId and number need to be numbers';
}
this.roleName = 'role' + number;
this.startDate = rand(0, new Date().getTime());
this.endDate = rand(this.startDate, new Date().getTime());
this.href = '/v1/transactions/' + processId + '/roles/' + this.roleName;
return this;
}
Again, pretty straightforward. Some input validation, and then throw some data in and return the object.
Factory to create Process and Role objects
/**
* A factory class to make some randomly generated processes
* Based on http://addyosmani.com/resources/essentialjsdesignpatterns/book/#factorypatternjavascript
*
* @return {Object Process} A new Process object with random data
*/
function processFactory () {}
/**
* Returns a random 12 digit integer
* @return {Integer} 12 digit integer
*/
processFactory.prototype.makeId = function () {
return Math.round(Math.random() * Math.pow(10, 12));
};
/**
* Makes a new process with random info
*
* @param {Integer} numberOfRoles The amount of roles to put into the process
*
* @return {Object Process} A new Process object
*/
processFactory.prototype.makeProcess = function(numberOfRoles) {
var i = 1;
if ( typeof numberOfRoles === 'undefined' ) {
numberOfRoles = Math.round(Math.random() * 10);
}
this.processId = processFactory.makeId();
this.roles = [];
while ( numberOfRoles-- ) {
i++;
this.roles.push(new Role(this.processId, i));
}
return new Process(this);
};
var processFactory = new processFactory();
And here's the factory to build me some Processes and Roles for them. I'm not even sure if this is the best way to make a factory in Vanilla JS!
I want to be able to instantiate multiple processes and controllers.
processFactory
could be in an Angular service. – Martin May 1 '14 at 20:29