How can javascript like varName.myFunction() - javascript

function CircleArea(Value) {
var Results = 3.14 * Value^2;
return Results;
}
So I want:
var Diameter = 30;
Diameter.CircleArea(); // Results 2826
Like:
var n = 30; n.toString() // Results 30
Syntax:
varName.myFunction();

You can but rarely should extend prototypes:
Number.prototype.circleArea = function() {
var value = this;
return Math.pow(value, 2) * Math.PI;
};
var num = 30;
console.log(num.circleArea()); // 2827.4333882308138

Your function accepts an argument .
So you will need to pass in Diameter like so :
CirclArea(Diameter)
Returns 2826

Related

How to send Javascript list to angular controller

What I am trying to achieve is send a list of zip codes from my JavaScript function that gets a range based on the distance and zip code that the user enters. Once I get my list of zip codes, send the list to my angular controller.
Originally, the scope below would grab the zip code that was entered by the user from the form (see below):
$scope.GetCurrentZip = function (){
try{
$http.get("../remote/ReturnZipCodes.cfm")
.then(function(response){
$scope.searchParam.Zip = response.data;
})
}
else{ console.log('No geolocation'); }
}
catch(err) { console.log(err.message); }
}
I would like to use the same scope that I have above. However, instead of grabbing the value that was entered by the user, I would like to grab the list that I obtain from the function instead.
The following is the JavaScript function that generates the list of zip codes:
var rad = function(x) {
return x * Math.PI / 180;
};
var getDistance = function(p1, p2) {
var R = 6378137; // Earth’s mean radius in meter
var dLat = rad(p2.lat - p1.lat);
var dLong = rad(p2.lon - p1.lon);
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(rad(p1.lat)) * Math.cos(rad(p2.lat)) * Math.sin(dLong / 2) * Math.sin(dLong / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d; // returns the distance in meter
};
function getZipCodes() {
var miles = document.getElementById("miles").options[document.getElementById("miles").selectedIndex].innerHTML;
var zip = document.getElementById("zip").value;
if (typeof zip === 'undefined' || typeof miles === 'undefined' || !zip.length || !miles.length) return false;
var zips = getZips();
var zip_list = "";
if (zips.length) {
// var list_item = "";
// for (i=0;i<zips.length;i++) {
// console.log(zips[i]);
// }
zip_list = zips.join();
}
return zip_list;
}
function getZips() {
var zipcode1 = getZipInfo(zip);
var res = [];
if (typeof zipcode1 === "undefined") return false;
for (i=0; i<zipinfo.length; i++) {
var zipcode2 = zipinfo[i];
var distance = getDistance(zipcode1, zipcode2);
//Convert meters into miles
distance = distance/1609.344;
if (distance <= miles) {
res.push(zipcode2.zip);
}
}
return res;
}
function getZipInfo(zip) {
for (i=0; i<zipinfo.length; i++) {
if (zipinfo[i].zip == zip) return zipinfo[i];
}
}
Any help would be appreciated.
Update: As stated by #charlietfl, I was not clear with what I was asking in my question and I do apologize for any confusion.
What I was asking is I would like to retrieve the list of zip codes that was generated in my JavaScript function GetZips().
As suggested by #charlietfl (thanks for your help once more), all I needed to do is the following:
$scope.GetCurrentZip = function (){
try{
$scope.Zip = getZips();
}
catch(err) {}
}
Update: #LSD pointed out that it will not pass do to the values passing in are not in a array. Is it possible to change the scope to accept the list? The list is a string.
Below code of angular will give you the hiden value
var hidenctl = angular.element(document.querySelector('#hidenid'));
var hidenvalue = hidenctl.val();

Javascript: Creating an array of arrays

I am trying to create an array of four arrays.
Each of this four arrays consists of three numbers, two of them are randomly assigned from a set of numbers.
When I run the following code I don't get an error, but I also don't get a result.
What am I missing?
I don't really need the print out in console.log, this is just to check if the array is constructed correctly
var x = -2;
function createEnemy(){
var yArray = [60,145,230];
var speedArray = [30,45,55,60];
var randY = Math.floor(Math.random() * yArray.length);
var randSpeed = Math.floor(Math.random() * speedArray.length);
var enemy = [yArray[randY], speedArray[randSpeed], x];
}
function printEnemies()
{
var allEnemies = [];
(function setEnemies()
{
allEnemies.push(createEnemy());
allEnemies.push(createEnemy());
allEnemies.push(createEnemy());
allEnemies.push(createEnemy());
}());
for(var j in allEnemies)
{
for(var p in allEnemies[j] )
{
for(var i = 0; i < allEnemies[j][p].length; i++ )
{
console.log(allEnemies[j][p][i]);
}
}
}
}
printEnemies();
You forgot to return your enemy :)
function createEnemy() {
var yArray = [60,145,230];
var speedArray = [30,45,55,60];
var randY = Math.floor(Math.random() * yArray.length);
var randSpeed = Math.floor(Math.random() * speedArray.length);
var enemy = [yArray[randY], speedArray[randSpeed], x];
return enemy;
}
Make sure you return something from createEnemy:
return [yArray[randY], speedArray[randSpeed], x];
Also, you might prefer something like this loop to the nested one you've implemented:
allEnemies.forEach(function (arr) {
console.log(arr[0], arr[1], arr[2]);
});
Looks like you're missing a 'return enemy' from the createEnemy function and you have an unnecessary tertiary level loop. Here's some modified lines (with some indentation updates for readability).
CODE:
var x = -2;
function createEnemy() {
var yArray = [60,145,230];
var speedArray = [30,45,55,60];
var randY = Math.floor( Math.random() * yArray.length );
var randSpeed = Math.floor( Math.random() * speedArray.length );
var enemy = [yArray[randY], speedArray[randSpeed], x];
return enemy; // Added a return of the enemy.
}
function printEnemies() {
var allEnemies = [];
( function setEnemies() {
allEnemies.push(createEnemy());
allEnemies.push(createEnemy());
allEnemies.push(createEnemy());
allEnemies.push(createEnemy());
}()
);
for(var j in allEnemies) {
for(var p in allEnemies[j] ) {
console.log (allEnemies [j][p] ); // Removed additional depth of loop
}
}
}
printEnemies();

Javascript constructor with closure using outside variables referencing other variables

var Beer = function(){
var moreBot = 100,
lessBot = 10,
wholeCase = moreBot + lessBot;
this.count = function(){
moreBot = 22;
lessBot = 33;
console.log(moreBot); //returns 22
console.log(lessBot); //returns 33
return wholeCase; //returns 110 instead of 55??
};
};
var Alc = new Beer();
So say I have this constructor using a closure which references the outside function variables. Then why is it that when I return wholeCase after changing the variables moreBot and lessBot do I get the sum of the originally assigned values? Thank you in advance for your expertise!
wholeCase is set at construction time. Your example is not significantly different from:
var foo = 5,
bar = 6;
var sum = foo + bar; // sum is 11
foo = 100000;
console.log(sum); // sum is still 11; we never changed sum
You either need to recompute wholeCase each time you use it, or just make it a function:
var Beer = function(){
var moreBot = 100,
lessBot = 10,
computeWholeCase = function() { return moreBot + lessBot };
this.count = function(){
moreBot = 22;
lessBot = 33;
return computeWholeCase(); // run computeWholeCase to return 55
};
};

How to give a variable a random value in javascript

How would I give a variable a random value in javascript?
I can do this:
var myMake = ["Chevy","Subaru","Kia","Honda","Toyota"];
var x = Math.floor(Math.random() * 4 + 1);
var rand = myMake[x];
alert(rand);
which gets the desired effect, giving the variable rand a random value of one of these:
Chevy, Subaru, Kia, Honda, Toyota
but would there be a way to make a function/method that does something like this?:
var rand = randVal("Chevy", "Subaru", "Kia", "Honda", "Toyota");
Thanks!!
function randVal(){
var x = Math.floor(Math.random() * arguments.length);
return arguments[x];
}
the arguments is an array like object that refers gives a list of all supplied arguments to a function.
Just to be different!
var x = ["Chevy","Subaru","Kia","Honda","Toyota"].sort(function() {
return 0.5 - Math.random();
})[0];
alert(x);
jsfiddle
And as a function, but accepting an Array
var randMe = function ( me ) {
if ( me ) {
return me.sort(function() {
return 0.5 - Math.random();
})[0];
}
}
alert(randMe(['a','b','c']));
jsfiddle
And some prototyping as well
Array.prototype.rand = function() {
return this.sort(function() {
return 0.5 - Math.random();
})[0];
}
alert(['a','b','c'].rand());
jsfiddle
Also the actual shuffle function from here.
You can do that very easy with jQuery:
(function($) {
$.rand = function(arg) {
if ($.isArray(arg)) {
return arg[$.rand(arg.length)];
} else if (typeof arg === "number") {
return Math.floor(Math.random() * arg);
} else {
return 4; // chosen by fair dice roll
}
};
})(jQuery);
var items = ["Chevy","Subaru","Kia","Honda","Toyota"];
var item = $.rand(items);

Javascript error with returns and multiple the return

And I am sorry to bother with this noob-stuff, but currently new to all this. But learning slowly.
In the first lines of code im getting a return (in this code i get 20*2=40. in the next phase I want to multiplie the return (40) with 20. = 800. so in the outcome it will show 40 And 800. But i only get it to be in the outbox [function], it says. and a msg; "it looks like you didnt print out a value for newNumber".
What do I do wrong? Thanks for all help!
var timesTwo = function (number) {
return number * 2;
};
timesTwo(20);
var newNumber = function (tal) {
(timesTwo * tal);
console.log(newNumber);
};
newNumber(20);
What you need to do is assign the result to a variable, and in the second function return the result:
var timesTwo = function(number) {
return number * 2;
};
var twoTimesResult = timesTwo(20);
var newNumber = function (tal) {
return twoTimesResult * tal;
};
var result2 = newNumber(20);
console.log(result2);
If you wanted to be fancy you could also do the following:
function multiplier(num, multiplier) {
var by = num * multiplier;
return function (number) {
return number * by;
};
}
var multiplyResult = multiplier(20, 2);
console.log(multiplyResult(20));
I'm answering this question too because I think these types of things are fun.
Another approach you could take is the OOP approach.
From your example you have a common multiplier of 20 and a beginning constant of 2.
I would personally attack this problem like so to avoid multiple variables:
// Create a calc object
var Calc = (function () {
// Constructor
Calc = function () {
// Initial constant
this.current_val = 2;
}
// Prototype methods
Calc.prototype = {
// inc() method
inc: function () {
return this.current_val * 20;
}
}
// Return object
return Calc;
})();
// Object Instance
var obj = new Calc();
// Initial call to inc() -> 40
obj.current_val = obj.inc();
// Log
console.log(obj.current_val);
// Second call to inc() -> 800
obj.current_val = obj.inc();
// Log
console.log(obj.current_val);
// Third call to inc() -> 16000
obj.current_val = obj.inc();
// Log
console.log(obj.current_val);
I made a jsfiddle so you can see the output.

Categories