Using already created functions inside a new Javascript function - javascript

I'm beginner, so this question might be silly.
I had to do 4 Javascript Function, I will put them below
function Square(a) {
b=a*a;
return b;
}
//2.Functia Half//
function Half(a) {
b=a/2;
return b;
}
//3.Functia Percent//
function Percent(a,b) {
procent=a/b*100;
return procent + "%";
}
//4.Functia Area//
function Area(a) {
pi=3.14;
circlearea=a*a*pi;
final=circlearea.toFixed(0);
return final;
}
Now i have to create the last function, which does:
Applies Half function on the parameter I've given to the new function(a), stores is in a new variable(result), result becomes parameter for the function square, the result will be stored again in a new variable(resultSquare), resultSquare will be used in Area function and stored in a new variable(resultArea). In the end, I need percent function, to find out the percent of resultArea from resultSquare. I tried like this, but no luck:
function new function{
result=Half(a);
return result;
resultSquare=Square(result);
return resultSquare;
}
It just returns result variable and does nothing else. Can you help? Thank you in advance.

You can't return something twice. Once you return something, it breaks out of the function. Remove the first return result; statement and it should work.
Also why are you doing
function new function { }
The proper syntax is
function [Function Name](parameters) { }

The result exits the function - so anything after a return statement will not be run. You need to return the last item:
function newFunction(a) {
var result = Half(a);
var resultSquare = Square(a);
var resultArea = Area(a);
return Percent(resultSquare, resultArea);
}

Related

func.apply with THIS applying to no object

I don't understand why the following code passes this and arguments to func.apply.
I tried to play with the code to figure out what it is doing, searched on the internet, etc., but couldn't find anything about using apply this way.
function work(a, b) {
alert( a + b );
}
function spy(func) {
function wrapper(...args) {
wrapper.calls.push(args);
return func.apply(this,arguments);
}
wrapper.calls = []
return wrapper;
}
work = spy(work)
work(1, 2); // 3
work(4, 5); // 9
The following call returns the result of wrapper
work.apply(this,arguments(a,b))
The result of spy is the same as the above.
But what makes this and arguments do the right thing in wrapper? Because without the this it doesn't work and why when i declare
let work = spy(work)
It doesn't work.
work is already declared here (function declaration). You can use var instead if you want to redeclare.
In this particular example, you are not using this inside work function. So it doesn't make a difference even if you invoke func like this func(...args) as below:
function work(a, b) {
alert( a + b );
}
function spy(func) {
function wrapper(...args) {
wrapper.calls.push(args);
console.log({ this: this });
return func(...args);
}
wrapper.calls = []
return wrapper;
}
var work = spy(work)
work(1, 2);
work(4, 5);

JSONP parsing in javascript/node.js

If I have an string containing a JSONP response, for example"jsonp([1,2,3])", and I want to retrieve the 3rd parameter 3, how could I write a function that do that for me? I want to avoid using eval. My code (below) works fine on the debug line, but return undefined for some reason.
function unwrap(jsonp) {
function unwrapper(param) {
console.log(param[2]); // This works!
return param[2];
}
var f = new Function("jsonp", jsonp);
return f(unwrapper);
}
var j = 'jsonp([1,2,3]);'
console.log(unwrap(j)); // Return undefined
More info: I'm running this in a node.js scraper, using request library.
Here's a jsfiddle https://jsfiddle.net/bortao/3nc967wd/
Just slice the string to remove the jsonp( and );, and then you can JSON.parse it:
function unwrap(jsonp) {
return JSON.parse(jsonp.slice(6, jsonp.length - 2));
}
var j = 'jsonp([1,2,3]);'
console.log(unwrap(j)); // returns the whole array
console.log(unwrap(j)[2]); // returns the third item in the array
Note that new Function is just as bad as eval.
Just a little changes and it'll work fine:
function unwrap(jsonp) {
var f = new Function("jsonp", `return ${jsonp}`);
console.log(f.toString())
return f(unwrapper);
}
function unwrapper(param) {
console.log(param[2]); // This works!
return param[2];
}
var j = 'jsonp([1,2,3]);'
console.log(unwrap(j)); // Return undefined
without return your anonymous function is like this :
function anonymous(jsonp) {
jsonp([1,2,3]);
}
because this function doesn't return so the output will be undefined.

Data structure adding and removing items using constructor functions

Its the beginning of a data structure exercise and I am trying to write an add and remove function -its should be so simple and I don't get why its wrong?! Also the way to do it 8using a constructor function, prototype etc. must stay the way it is)
Any help much appreciated!
function Thestack () {
this.array=[];
}
Thestack.prototype.plus = function (i) {
this.array.push(i);
return this; // cannot be edited
};
Thestack.prototype.minus = function () {
this.array.pop();
};
var smallstack = new Thetack();
smallstack.plus(something); //followed by
smallstack.minus();
should return: something
your minus function does not have a return statement, so it just returns undefined by default
You could as in the add function return this so you can continue chaining of methods, return the element removed or return the length of the remaing array
// return this for chaining
Thestack.prototype.minus = function () {
this.data.pop();
return this;
};
// return the removed item
Thestack.prototype.minus = function () {
//edits the data array in place and returns the last element
return this.data.pop();
};
// return the length of the remaining array
Thestack.prototype.minus = function () {
this.data.pop();
return this.data.length;
};

higher order functions using arrays in javascript

I am trying to create a higher order function in javascript someMathArray(x) { } that returns a function and takes another single argument. I want the function to take an original array, say [1,2,3,4] then apply another function for example, named mult2(a) { return a*2 }(however, I want this to work for any function I pass in. I don't want mult2(a) to be hard coded into the function) and then return an array containing [2,4,6,8]
Something like this?
function someMathArray(array) {
return function(fun) {
return array.map(fun);
};
}
var fun = someMathArray([1,2,3,4,5]);
var output = fun(function(a) { return a*2; });
document.getElementById('output').innerHTML = JSON.stringify(output);
<div id="output"></div>
or
function someMathArray(array) {
return array.map.bind(array);
}
var fun = someMathArray([1,2,3,4,5]);
var output = fun(function(a) { return a*2; });
document.getElementById('output').innerHTML = JSON.stringify(output);
<div id="output"></div>

using multiple return statements in JavaScript

I am trying to use multiple returns but just keep breaking the code. I have tried a few examples, but cant find the right combination.
How can I combine these two return statements into one?
$(".bar").popover({
content:
function (){
return $(this).data('dataObj').status;
return $(this).data('dataObj').timeline;
}
});
Use
function (){
return $(this).data('dataObj');
}
OR
function (){
// return an array
return [ $(this).data('dataObj').status, $(this).data('dataObj').timeline ]
}
OR
function (){
// return a associative array
return { "status": $(this).data('dataObj').status, "timeline": $(this).data('dataObj').timeline }
}
And process the components in the caller.
Update
The content parameter for popover needs a string as argument, you can do this:
function (){
return $(this).data('dataObj').status + " " + $(this).data('dataObj').timeline;
}
Putting aside this specific case, where the plugin demands a certain type of return value (apparently a string in this case), you can't really... A return statement terminates the function. What you'll have to do is return an object (or an array) containing those two values -
var status = $(this).data('dataObj').status;
var timeline = $(this).data('dataObj').timeline;
return [status,timeline];
Or
var status = $(this).data('dataObj').status;
var timeline = $(this).data('dataObj').timeline;
var returnObj = {'status':status, 'timeline':timeline};
return returnObj;
You can return objext ir array containig those two items
$(".bar").popover({
content:
function (){
return
{
status: $(this).data('dataObj').status;
timeline: $(this).data('dataObj').timeline;
}
}
});
Try returning an array with .status and .timeline as elements.
Ok Lix was faster.

Categories

Resources