higher order functions using arrays in javascript - 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>

Related

Using already created functions inside a new Javascript function

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);
}

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;
};

Using formal parameter in built-in method calls

I want to get an element from JavaScript object.
Erroneous way is:
function getColor(response)
{
var color = response.payload.products[0].SKUS.color;
return color;
}
function getSize(response)
{
var size = response.payload.products[0].SKUS.size;
return size;
}
But i want to do it in the following way
function(response,color_size)
{
//var color_size = response.payload.products[0].SKUS+"."+color_size;
// It is string concatenation. So i can't able to get the desired result.
//return color_size;
}
Any suggestion to do this?? Single method for getting color,size,etc..
function getColorAndSize(response) {
var color = getColor(response);
var size = getSize(response);
return {
color:color,
size:size
};
}

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.

How to convert javascript array to function

I have an array of arbitrary values. I Wrote a function that transforms the array to an array of functions that return the original values, so instead of calling a[3], I will call a3.
Here is my code which does not work? code. It gives this error Cannot call method '1' of undefined.
var numToFun = [1, 2, { foo: "bar" }];
var numToFunLength = numToFun.length;
function transform(numTo) {
for (var i = 0; i < numToFunLength; i++) {
(function(num){
numTo.unshift(function() {
return num;
});
}(numTo.pop()))
}
}
var b = transform(numToFun);
console.log(numToFun);
console.log(b[1]());​
Others have already answered your question while I was writing mine but I will post it anyway - this may be somewhat easier to follow without all of those popping and unshifting:
function transform(numTo) {
var r = [];
for (var i = 0; i < numTo.length; i++) {
r[i] = (function (v) {
return function() {
return v;
}
}(numTo[i]));
}
return r;
}
(I have also changed the hard-coded length from numToFunLength to numTo.length so the transform() function would work for other inputs than only the global numToFun variable.)
See DEMO.
UPDATE: even more elegant way to do it using the Sugar library:
function transform(array) {
return array.map(function (v) {
return function() {
return v;
}
});
}
I like this syntax because it makes it more explicit that you want to map an array of values to an array of functions that return those values.
See DEMO.
Your function transform does not return anything. That is why b is undefined.
return numTo;
jsFiddle Demo
On the other hand, the array will be passed to the function as a reference anyways, so the original array will be changed. It is not a problem if you don't return anything, just omit the var b = transform(numToFun); line and simply write transform(numToFun).
Your transform function isn't returning anything. So b is undefined

Categories

Resources