Data structure adding and removing items using constructor functions - javascript

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

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

How to dynamically change a function

I have a function that has already been assigned and I would like to append some additional script. When I display the function like:
var func = obj.when_clicked;
alert(func);
The following is displayed:
function object_123(){
object_123_Action();
}
The type is a "function" and the function is executed elsewhere which I cannot change, the code is:
this.when_clicked();
I need to modify the function by appending my own code so it becomes:
function object_123(){
object_123_Action();
my_clicked(obj);
}
Then add that back and over write the when_clicked function.
It does work if I manually add the code like:
obj.when_clicked = function object_123(){object_123_Action();my_clicked(obj);};
However, I do not know what is in the function initially, all I want is to append the:
my_clicked(obj);
I do need the obj to be the actual object of interest which is obj.
You can wrap it:
var f = this.when_clicked;
this.when_clicked = function() {
// Call the original
var rv = f.apply(this, arguments);
// your code here
// Return the original function's return value
return rv;
};
Function#apply calls the original with the specified this flag. arguments is provided by the JavaScript engine: It's a pseudo-array of the arguments your function was called with, so the above just passes all of them on.
Be sure to think about what it means if your function throws an exception, and catch them if you want to suppress them.
If you do this often, you can giev yourself a utility function:
function wrapFunction(f, wrapper) {
return function() {
var rv = f.apply(this, arguments);
wrapper.apply(this, arguments);
return rv;
};
}
Then
this.when_clicked = wrapFunction(this.when_clicked, function() {
// Your code here
});
Or if you want access to the original's return value, potentially changing it:
function wrapFunction(f, wrapper) {
return function() {
var rv = f.apply(this, arguments);
rv = wrapper.call(this, rv, arguments);
return rv;
};
}
Then
this.when_clicked = wrapFunction(this.when_clicked, function(rv, args) {
// Your code here, using `rv` and `args`, which is a pseudo-array
// Potentially update `rv`
return rv;
});
You can store your functions in an array on the object.
Then, loop though the functions in another function and execute them.
var myObj = { 'myfunctions': [ ] };
and to add functions:
myObj.myFunctions.push (function () { /*function code here*/ });
Or if you already have a named function:
myObj.myFunctions.push (nameOfFunction);
And to call all the functions, use this function (don't add this function to myObj)
function executeMyFunctions (myObj) {
for (var i = 0; i < myObj.myFunctions.length; i++) {
myObj.myFunctions[i]();
}
}
Used this answer on another question of #peter. Meant to post here.

How to return an array from constructor and successfully chain the object in Javascript

I've been going through the jQuery code and I have seen a few links that have this question. I am asking it again because I did not really understand any of them so please do not mark this question as duplicate. I've gone through the following stackoverflow links:
How can jQuery return an array and still have it to be a jQuery object
How does jQuery chaining work
How does jQuery return an array of the selected objects
Gone through all of those links and I do not get how it works. All I ask is a very simple example of returning an array from a constructor object and still chaining it. I have tried the following code:
(function(window, document, undefined)
{
var lhd = function(selector)
{
return new Lhd(selector);
}
function Lhd(selector)
{
var elem = document.querySelectorAll(selector),
elems = {};
return this.makeArray(elems, elem);
}
Lhd.prototype = {
makeArray: function(arr, result)
{
var ret = result || [];
Array.prototype.push.apply(ret, arr);
return ret;
},
click: function()
{
console.log('click');
return this;
}
};
window.lhd = lhd;
})(window, document);
I'm able to return an array but unable to chain it.
I'm able to return an array
You must not return an array, you must make the new instance (this) become array-like.
function lhd(selector) {
return new Lhd(selector);
}
function Lhd(selector) {
var elems = document.querySelectorAll(selector);
this.length = 0; // initialise a length
Array.prototype.push.apply(this, elems); // push onto the instance
// don't `return` anything - it's a constructor
}
Lhd.prototype.click = function() {
console.log('click');
return this;
};
You can use it now like lhd('a').click().click().

making a function in an object chainable

I am trying to achieve a chainable object, but cannot figure out how I can do this within a function.
This is how I would like it to work:
$donate.ga('testing').go(value);
My object currently looks like this:
var $donate = {
ga: function (value) {
}
};
You simply need to make each function to return the instance of the object:
var $donate = {
ga: function (value) {
// logic
return this;
}
};
It's already solved here. You must simply return the object in your function.
You need to return the Object like that:
var $donate = {
ga: function (value) {
//after some computation
return this;
},
go: function(val) {
//after some computation
return this;
}
};
If you don't return this (this is a reference to the current Object), you either return undefined or something else and your method defined in your Object is simply out of scope (unknown).
you have to return this; in each sub function before closing it.
for example
Your code
var $donate = {
ga: function (value) {
//perform your code here
return this; // <--- Dont forget to use this before closing the function nest
},
go: function(val) {
//perform your code here
return this; // <--- Dont forget to use this before closing the function nest
}
};

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