This question already has answers here:
How to explain callbacks in plain english? How are they different from calling one function from another function?
(34 answers)
Understanding Callbacks
(3 answers)
Closed 4 years ago.
How replacer argument function extract key and value from object value and mapped it to its key and value argument in JSON.Stringify(value, replacer, space) method.
I understood that key of the object become the key parameter of the replacer function and value become value parameter of this function.
let user={name:"anup", age:22};
JSON.stringify(user,function(key,value){
if(typeof value==="string"){
return undefined;
}
return value;
},null);
Here name becoming the key of the replacer function and "anup" becoming the value of the replacer function thats fine, but my question is how this mapping is happening?
Generally we call any method by passing argument in that method call, like
function a(c,d){
// logic
}
a(2,3);
But here in stringify method we are not passing any such thing to the replacer function or callback function, then how it is getting mapped?
Actually, I'm a newbie in javaScript world, so something I'm unable to understand. If you guide me in this regard , I'll be very thankful to you.
How JSON.stringify() works internally?
Thats probably some low level, highly optimized native code. But lets assume it is just a regular JavaScript function instead, that makes things easier. The function would be defined as such:
JSON.stringify = function(toStringify, replacer) {
Now that function has to determine what toStringify is first, e.g.:
if(typeof toStringify === "object") {
In that case, the code has to go over all the objects key/value pairs:
for(let key in toStringify) {
let value = toStringify[key];
Now the code can call the replacer with those pairs:
value = replacer(key, value);
Then a string can be built up as:
result += `"${key}": ${JSON.stringify(value)}`;
Then that result gets returned.
Related
This question already has answers here:
JavaScript variable number of arguments to function
(12 answers)
Closed 1 year ago.
In javascript I am in situation where i need to make variable arguments based on a length of an array, below is an sample code
function getValesList(json){
return getValues(json[0])+getValues(json[1])+getValues(json[2]);
}
function getValues(json1){
let valueList = Object.values(json1);
let valueListPipe = valueList.join("|");
return valueListPipe+lineSeparator;
}
where json is an array of JSON objects and I need to make a pipe delimiter file based on the length of incoming array. How to make it dynamic where I can do like a varargs in JAVA
If you're just passing N arguments of the same type, you can use the rest feature of Javascript for function arguments.
function getValuesList(...json){
return json.map(j => getValues(j)).join("");
}
This allows you go pass any number of separate arguments as in getValuesList(o1, o2, o3, o4) and the json parameter within your function will automatically be an array of however many arguments were passed.
This question already has answers here:
JavaScript variable number of arguments to function
(12 answers)
Closed 2 years ago.
I have one doubt here that I need to pass n nos of values as argument and calculating the total sum of it using Javascript. I am explaining some sample code below.
function add(a,b,c) {
return a+b+c;
}
var data =add(5,6,7);
console.log(data)
Here I am passing only 3 arguments to the function but I need to pass n numbers of argument to the function like inside function its known how many values have passed as argument and final I need the total sum and return it.
You can either reduce over it to sum all if you want to write it in a functional way like
function add(...numbers) {
return numbers.reduce((acc,no) => return acc + no),0);
}
or by using arguments keyword knowing it's only available if the function is normal function, not an arrow function.
here's a ref https://stackoverflow.com/a/38567145/1888435
also, arguments aren't an array it's an array-like and if you checked typeof arguments it will give you object.
As #slappy said you can get parameters as array
function add(...numbers){
// Values reach as array
console.log(numbers)
// Here you should use array inner functions
return numbers.reduce((sum,value) => sum+value, 0)
}
let data = add(5,6,7);
console.log(data)
This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Javascript: Get deep value from object by passing path to it as string [duplicate]
(5 answers)
Closed 5 years ago.
Consider I've an object myObj
And I've a string representing the path to some property inside it: foo.bar
What is the best way to get it from my object?
If I knew the string ahead I would do myObj.foo && myObj.foo.bar to get it safely
A simple solution would be to split the string 'foo.bar'.split('.') and than loop over it.
But i'm sure there is a better way
It's a duplicate of other question. they provided a great solution:
given a path and an obj get the property value this way
path.split('.').reduce((o, i) => o[i], obj)
A simple solution would be to split the string 'foo.bar'.split('.') and than loop over it.
Yep, that sounds like the best way. You can create a helper method that does exactly this, but there's nothing built in to the language or standard libraries to make things simpler than this.
function getFromPath(obj, path) {
var current = obj;
for(let piece of path.split('.')) {
current = current[piece];
}
return current;
}
Usage:
getFromPath({foo: {bar: "hello"}}, "foo.bar"); // "hello"
This question already has an answer here:
Function.call method as callback [duplicate]
(1 answer)
Closed 6 years ago.
I was looking at a question yesterday in which the poster was asking how to convert the case of an array's contents. I know that I can pass a reference to a function to map like:
function appendText (el){
return el += ' - appended text';
}
['a','b'].map(appendText); //["a - appended text", "b - appended text"]
But when I tried with
array.map(String.toUpperCase);
array.map(String.prototype.toUpperCase);
I get the error
Uncaught TypeError: String.prototype.toUpperCase called on null or undefined
Which makes it sound like the method isn't getting passed the element map would, as I understand it, be passing. Why doesn't this work?
You are not passing anything to the prototype / extension method. Simply use an arrow function to pass in the value of the array item.
To answer the logic behind the question, you simply can't pass the context-less (e.g. no this) prototype method (that is, from the base String class). map will run the function by name with the value as the first parameter (as shown with appendText(a))
function appendText (el){
return el += ' - appended text'
}
var array = ['a','b']
console.log(array.map(appendText))
console.log(array.map(a => appendText(a)))
console.log(array.map(a => a.toUpperCase()))
This question already has answers here:
Higher order functions - Javascript
(2 answers)
Closed 9 years ago.
javascript book "eloquent javascript"
function negate(func) {
return function(x) {
return !func(x);
};
}
var isNotNaN = negate(isNaN);
show(isNotNaN(NaN));
someone explain it and as title of question says what is higher-order function, what does this code do ?
When most people think of functions they accept objects or values as parameters and similarly return an object or value, such as function addTwoNumbers(int x, int y).
In mathematics and computer science, a "higher-order function" is just like any other function, except that in addition to arguments that are values it can also accept a function as an argument.
...that's all a higher-order function is, really :)
In the example you posted, negate is a higher-order function because it has a parameter func which is a function (or rather, assigned to a function).
negate goes further: it doesn't merely call func and negate its result, instead it returns an anonymous function (that's the inner return function(x) bit).
So the isNotNaN variable then has the type (and value) of that earlier anonymous function.
Higher-order function is a function that:
Take one or more functions as input.
Give another function as output.
What does your code do? it negates the function isNan (to isNotNan). It accept a function (isNan), and then output the negation (isNotNan). It's just that simple.