var obj = {
name1: 1,
name2: 2
}
function myF(obj) {
console.log(obj.name1) // by idea it must return 1
};
myF(obj)
Does anybody know how to pass object in function?
Yes objects make great parameters.
var p1 = {
name: "Tom",
age: 23,
isMale: true
};
var p2 = {
name: "Alicia",
age: 21,
isMale: false
};
var p3 = {
name: "Landon",
age: 1,
isMale: true
};
function greeting(person) {
var str = '';
str += 'Hello my name is ';
str += person.name + ' ';
str += 'I'm a ' + person.age + ' year old ';
if (person.isMale) {
str += age > 18 ? 'man' : 'boy';
} else {
str += age > 18 ? 'woman' : 'girl';
}
if (person.age < 3) {
str = 'Bah'
}
console.log(str);
};
greeting(p1); // 'Hello my name is Tom I'm a 23 year old man';
greeting(p2); // 'Hello my name is Alicia I'm a 21 year old woman;
greeting(p3); // 'Bah';
Objects are good for when you have a grouping of values that belong together and you don't want to pass them in individually (If they belong together they rarely should be passed on their own.)
This is very common practice. Many libraries will utilize a config object so one does not have to specify multiple params
Example:
function makeSquare(height, width, color, border)
Could be easier represented with
function makeSquare(config)
This would make it easier for users to leave out some parameters, say you wanted to makeSquare without a border you would not need to include the border param if you are passing and object.
With parameters
makeSquare(10, 20, red, null)
with Obj
config = {
height: 10,
width: 10,
color: 'red'
};
makeSquare(config);
If you had an extensive amount of configuration options you could see where this may save quite a bit of development time and space
Related
I am trying to create a JSON object, with a random string as the name, just like how Firebase does it.
Goal: replace child name with random string.
For example:
"Users" : {
"mGKgNDOw0qd77m6tmdDh76zOQOm2" : {
"email" : "someuser#gmail.com",
"firstName" : "some",
"lastName" : "user",
"username" : "someuser"
},
"vyMiCS7olNPh9bCXoKWqcIFNWVy2" : {
"email" : "someuser2#gmail.com",
"firstName" : "some",
"lastName" : "user2",
"username" : "someuser2"
}
}
This is what I got so far, I manage to get my head around with a string randomise function.
randomString(length) {
return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}
And I would like to push my data into the object with random string as the name.
I tried string interpolation but it does not work.
var expensesObject = {
uid: {
amount: spentAmount,
category: selectedCategory,
date: formattedDate,
time: formattedTime,
note: note
}
}
Consider this code
var users = {}
users[ randomString(20) ] = {
amount : spentAmount,
category : selectedCategory,
date : formattedDate,
time : formattedTime,
note : note
}
You can do this by setting directly the object's key using []:
var expensesObject = {}
expensesObject[uid] = {
amount: spentAmount,
category: selectedCategory,
date: formattedDate,
time: formattedTime,
note: note
}
You could use a single random number for a distinct place. The check if lower or upper case.
Then assign to the new key the property of uid and delete the property.
function replaceUID(object) {
object[random(28)] = object.uid;
delete object.uid;
}
function random(size) {
var r, s = '';
while (s.length < size) {
r = Math.floor(Math.random() * 62);
s += r >= 36 ? (r - 26).toString(36).toUpperCase() : r.toString(36);
}
return s;
}
var expensesObject = { uid: { amount: 'spentAmount', category: 'selectedCategory',
date: 'formattedDate', time: 'formattedTime', note: 'note' } };
replaceUID(expensesObject);
console.log(expensesObject);
Copy the object uid to a new object containing the random string
var expensesObject = {
uid: {
amount: 5,
category: "catA",
date: "02-03-2017",
time: "14:00:00",
note: "Notes"
}
};
var finalobject = {};
let propertyName = randomString(10); //get the random string
finalobject[propertyName] = expensesObject.uid; //copy uid object
console.log(finalobject);
function randomString(length) {
return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}
You could do something like this:
function randomString(length) {
return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}
var keylength = 16; // <-- change as needed
var myObject = {
amount: spentAmount,
category: selectedCategory,
date: formattedDate,
time: formattedTime,
note: note
}
var expensesObject = {};
var uuid = randomString(keylength);
expensesObject[uuid]=myObject; // <-- use [ var_name ]
You also can create string and convert it to JSON object like this:
var expensesObjectStr = "{"+ '"'+ uid+'"'+": {"+
'"amount"'+":"+ spentAmount+","+
'"category"'+":"+'"'+ selectedCategory+'"'+","+
'"date"'+": "+'"'+ formattedDate+'"'+","+
'"time"'+": "+'"'+ formattedTime+'"'+","+
'"note"'+": "+'"'+ note+'"'+
"} }";
var obj = jQuery.parseJSON(expensesObjectStr);
Here small fiddle - https://jsfiddle.net/skyr9999/2dvffaty/
var temp = expensesObject[uid];
expensesObject[randomString(<length>)] = temp;
I'm trying to figure out how to extract e.g. -13, as a negative value out of a polynomial, e.g. -13x^2+2-12x^4. So far, I've successfully take out the powers. Additionally, my solution came up to this:
/\(+)(-)\d{1,4}/g
I know it's wrong syntax, but I'm not sure how to represent the + or - which goes with the following number.
It would be good if you can show me how to count the next x like the end of an common/searched phrase, I'm not sure about the term. You know, if it is -3x^ and the point is to extract -3, then it should be like /\ + or - \/d{1,4} x_here/g
var formula = '-13x^2+2-12x^4';
formula.match(/[+-]?\d{1,4}/g);
Returns:
["-13", "2", "+2", "-12", "4"]
If you wish to organize the numbers into coefficients and powers, here's an approach that works:
var formula = '-13x^2+2-12x^4';
function processMatch(matched){
var arr = [];
matched.forEach(function(match){
var vals = match.split('^');
arr.push({
coeff: parseInt(vals[0]),
power: vals[1] != null ? parseInt(vals[1]) : 0
})
})
console.log(arr);
}
processMatch(formula.match(/[+-]?\d+x\^\d+|[+-\s]\d[+-\s]/g))
/* console output:
var arr = [
{ coeff: -13, power: 2 },
{ coeff: 2, power: 0 },
{ coeff: -12, power: 4 }
];*/
I think you want:
var str = '2x^2-14x+5';
var re = /([+-]?\d{1,4})/g;
var result = str.match(re);
I have hundred of objects with structure like
{
movieName: 'xyz',
time: '02:15:50'
timeAsText: null
}
I need to set timeAsText with a text as "136 minutes" based on property 'time'.
Seconds should be rounded up.
Could you point me out what could be the faster approach?
I tried this with two methods (DEMO); the first using map, and the second using a plain for...loop. As you can see from the demo the plain loop is considerably faster:
var out = [];
for (var i = 0, l = arr.length; i < l; i++) {
var obj = arr[i];
var time = obj.time.split(':').map(Number);
if (time[2] > 0) { time[1]++; }
obj.timeAsText = (time[0] * 60) + time[1] + ' minutes';
out.push(obj);
}
the best to do is probably that, and, seeing the numbers of similar answers, probably the only one.
-first, you use split(':') to make your string become a array of parseable string;
-then, parse the value to int. Use parseInt
at this time, you should have a array like that
[number_of_hours, number_of_minutes,number_of_second]
-then you just have to add the different values like
obj.timeAsText = array[0]*60+array[1]+Math.round(array[2]/60)+' minutes';
The full answer :
var arr=obj.time.split(':').forEach(function(entry){
entry=parseInt(entry);
});
obj.timeAsText= arr[0]*60+arr[1]+Math.round(array[2]/60)+" minutes";
Try this
var obj = {
movieName: 'xyz',
time: '02:15:50'
timeAsText: null
}
var a = obj.time.split(':'); // split it at the colons
var minutes = parseInt(+a[0]) * 60 + parseInt(+a[1]) + Math.round(parseInt(+a[2])/60);
obj.timeAsText = minutes + " minutes";
I don't know if it's the fastest, but it's the most easily readable one:
var test = {
movieName: 'xyz',
time: '02:15:50',
timeAsText: null
};
test.time.replace(/^(\d{2}):(\d{2}):(\d{2})$/, function(m, p1, p2, p3) {
// Multiplication and division implicitly converts p1 and p3 to numbers
return p1*60 + parseInt(p2) + Math.ceil(p3/60);
});
I am trying to build a webapp that gets data from server and shows it to user. Script gets data from server every 10 seconds and if data has changed it alerts user. This is the code I'm using now, but it alerts every 10 second whether the data has changed or not.
So how do I need to alter my scipt to make it compare the old JSON and the new JSON and see if they are different, and if they are show alert before updating data shown to user?
$('#ListPage').bind('pageinit', function(event) {
getList1();
});
setInterval ( "getList1()", 10000 );
var old = "";
function getEmployeeList1() {
$.getJSON(serviceURL + 'getemployees.php?' + formArray, function(data) {
if(data != old){ // data from the server is not same as old
$('#nollalista li').remove();
keikka = data.key;
$.each(keikka, function(index, lista) {
$('#nollalista').append('<li><a href="employeedetails.html?id=' + lista.IND + '">' +
'<h4>' + lista.OSO + '</h4>' +
'<p>' + lista.AIKA + '</p>' +'</a></li>');
});
$('#nollalista').listview('refresh');
if(old != "")
alert("New data!");
old = data;
}
});
}
A very easy (but kind of lame) solution is comparing the string representations:
if(JSON.stringify(a) != JSON.stringify(b)) { ... }
Your code alerts every 10 sec, because your comparison
if(data != old){ // data from the server is not same as old
returns true everytime.
You can use this library to compare json in javascript
https://github.com/prettycode/Object.identical.js
and modify the comparison to
if(!Object.identical(data,old)){ // data from the server is not same as old
usage:
var a = { x: "a", y: "b" },
b = { x: "a", y: "b" },
c = { y: "b", x: "a" },
d = { x: "Chris", y: "Prettycode.org", developerYears: [1994, 2011] },
e = { y: "Prettycode.org", developerYears: [1994, 2011], x: "Chris" };
f = { y: "Prettycode.org", developerYears: [2011, 1994], x: "Chris" };
console.log(Object.identical(a, b)); // true (same properties and same property values)
console.log(Object.identical(a, c)); // true (object property order does not matter, simple)
console.log(Object.identical(d, e)); // true (object property order does not matter, complex)
console.log(Object.identical(d, f)); // false (arrays are, by definition, ordered)
Below is a regular function with named parameters:
function who(name, age, isMale, weight)
{
alert(name + ' (' + (isMale ? 'male' : 'female') + '), ' + age + ' years old, ' + weight + ' kg.');
}
who('Jack', 30, true, 90); //this is OK.
What I want to achive is; whether you pass the arguments in order or not; the function should produce a similar result (if not the same):
who('Jack', 30, true, 90); //should produce the same result with the regular function
who(30, 90, true, 'Jack'); //should produce the same result
who(true, 30, 'Jack', 90); //should produce the same result
This enables you to pass a list of arguments in any order but still will be mapped to a logical order. My approach up to now is something like this:
function who()
{
var name = getStringInArgs(arguments, 0); //gets first string in arguments
var isMale = getBooleanInArgs(arguments, 0); //gets first boolean in arguments
var age = getNumberInArgs(arguments, 0); //gets first number in arguments
var weight = getNumberInArgs(arguments, 1); //gets second number in arguments
alert(name + ' (' + (isMale ? 'male' : 'female') + '), ' + age + ' years old, ' + weight + ' kg.');
}
There is a little problem here; functions such as getStringInArgs() and getNumberInArgs() go through all the arguments each time to find the arg by type at the specified position. I could iterate through args only once and keep flags for the positions but then I would have to do it inside the who() function.
Do you think this approach is logical and the only way? Is there a better way to do it?
EDIT 1: Code above actually works. I just want to know if there is a better way.
EDIT 2: You may wonder if this is necessary or whether it makes sense. The main reason is: I'm writing a jQuery function which adds a specific style to a DOM element. I want this function to treat its arguments like shorthand CSS values.
Example:
border: 1px solid red;
border: solid 1px red; /*will produce the same*/
So; here is the real and final code upto now:
(function($){
function getArgument(args, type, occurrence, defaultValue)
{
if (args.length == 0) return defaultValue;
var count = 0;
for(var i = 0; i < args.length; i++)
{
if (typeof args[i] === type)
{
if (count == occurrence) { return args[i]; }
else { count++; }
}
}
return defaultValue;
}
$.fn.shadow = function()
{
var blur = getArgument(arguments, 'number', 0, 3);
var hLength = getArgument(arguments, 'number', 1, 0);
var vLength = getArgument(arguments, 'number', 2, 0);
var color = getArgument(arguments, 'string', 0, '#000');
var inset = getArgument(arguments, 'boolean', 0, false);
var strInset = inset ? 'inset ' : '';
var sValue = strInset + hLength + 'px ' + vLength + 'px ' + blur + 'px ' + color;
var style = {
'-moz-box-shadow': sValue,
'-webkit-box-shadow': sValue,
'box-shadow': sValue
};
return this.each(function()
{
$(this).css(style);
});
}
})(jQuery);
Usage:
$('.dropShadow').shadow(true, 3, 3, 5, '#FF0000');
$('.dropShadow').shadow(3, 3, 5, '#FF0000', true);
$('.dropShadow').shadow();
I find using objects to be more straight-forward and less error prone in the future:
var person = {
name: 'Jack',
age: 30,
isMale: true,
weight: 90
};
who(person);
function who(person){
alert(person.name +
' (' + (person.isMale ? 'male' : 'female') + '), ' +
person.age + ' years old, ' +
person.weight + ' kg.');
}
That way when you come back years later you don't have to lookup to see if age was the first, second, or fifth number and is more descriptive of what you are trying to accomplish.
This seems unnecessarily complex, not just from the perspective of the function, which needs to reorder its arguments, but also from the perspective of whoever is calling. You say that the function can accept its paramters in any order, but that's not entirely true. Since your determination of which variable is which is based on type, it relies on each variable being a different type. The name and gender can be anywhere, but the numeric arguments have to be in a specific order. It also prevents someone from passing in "30" or "90", which are numbers but will be regarded as strings - confusing it with the name and not finding an age or weight.
You can cache the arguments of a specific type in the arguments array. This is a big hack, you could follow the same pattern with the other getTypeInArgs
function getNumberInArgs(args, index) {
if (!args.numbers) {
args.numbers = [];
for (var i=0; i < args.length; i++) {
// You have to implement isNumber
if ( isNumber (args[i]) ) {
args.numbers.push(args[i];
}
}
}
return args.numbers[index];
}
I've never heard of accepting arguments in any order, except for the implode function in PHP, and it's marked on its documentation page as a big hack for historical reasons. So I wouldn't do this. If the order is too confusing, I would use the approach of taking a literal object, as suggested by WSkid.
You could try copying the arguments array into something you can destructively update:
untested code: Edit: I think it works now.
function args_getter(their_arguments){
//copy arguments object into an actual array
//so we can use array methods on it:
var arr = Array.prototype.slice.call(their_arguments);
return function(type){
var arg;
for(var i=0; i<arr.length; i++){
arg = arr[i];
if(type == typeof arg){
arr.slice(i, 1);
return arg;
}
}
return "do some error handling here"
}
}
function foo(){
var args = args_getter(arguments);
var b1 = args('boolean');
var b2 = args('boolean');
var n1 = args('number');
console.log(n1, b1, b2);
}
//all of
// foo(1, true, false),
// foo(true, 1, false), and
// foo(true, false, 1)
// should print (1, true, false)
This is still O(N^2) since you go through the array every time. However this shouldn't be an issue unless your functions can receive hundreds of arguments.
I agree with Griffin. This cannot be done unless you limit the choices more than you have. As it is, you have a string, a boolean and two numbers. Without some more rules on what can be in what position, you cannot tell which number is which. If you're willing to make some rule about which number comes first or which number comes after some other argument, then you can sort it out. In general, I think this is a bad idea. It's much better (from the standpoint of good programming) to use an object like WSkid suggested.
Anyway, if you wanted to make a rule like the weight has to come after the age, then it could be done like this:
function findParm(args, type) {
for (var i = 0; i < args.length; i++) {
if (typeof args[i] == type) {
return(i);
}
}
return(-1);
}
function who(name, age, isMale, weight) {
// assumes all variables have been passed with the right type
// age is before weight, but others can be in any order
var _name, _age, _isMale, _weight, i;
var args = Array.prototype.slice.call(arguments);
_name = args[findParm(args, "string")]; // only string parameter
_isMale = args[findParm(args, "boolean")]; // only boolean parameter
i = findParm(args, "number"); // first number parameter
_age = args[i];
args.splice(i, 1); // get rid of first number
_weight = args[findParm(args, "number")]; // second number parameter
// you now have the properly ordered parameters in the four local variables
// _name, _age, _isMale, _weight
}
who("fred", 50, false, 100);
Working here in this fiddle: http://jsfiddle.net/jfriend00/GP9cW/.
What I would suggest is better programming is something like this:
function who(items) {
console.log(items.name);
console.log(items.age);
console.log(items.weight);
console.log(items.isMale);
}
who({name: "Ted", age: 52, weight: 100, isMale: true});
function who({name, age, isMale, weight})
{
alert(name + ' (' + (isMale ? 'male' : 'female') + '), ' + age + ' years old, ' + weight + ' kg.');
}
who({name:'Jack', age:30, isMale:true, weight90});
Taking parameters as an object, allows you to pass arguments in any order.
There is no way you can do this since you have arguments of the same type.
Unless age and weight have non-overlapping ranges, you can't do this. How are you supposed to distinguish between 30 and 60 for weight or age??
This code:
function who(items) { console.log(items.name); console.log(items.age); console.log(items.weight); console.log(items.isMale);}who({name: "Ted", age: 52, weight: 100, isMale: true});
That a previous posted sent seems sensible. But why make things complicated. My experience when people make things complicated things go wrong.
BTW - The solution above (as the previous posted gave) is similar to the Perl solution.