Using formal parameter in built-in method calls - javascript

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

Related

Using function of an object after grabbing it from array

When I try to grab the object from the array, the type is undefined. Therefore I cannot use a method from the undefined object as it doesn't exist. I am relatively new to JavaScript and I have come straight from Java so the way of retrieving objects is kind of new to me. This is what I currently have.
var fleetAmount = 0;
var fleets = [];
function Fleet(number) {
this.number = number;
this.activities = [];
this.addActivity = function (activity) {
this.activities.push(activity);
};
fleets.push(this);
}
var getFleet = function(fleetNumber) {
return fleets[fleetAmount - fleetNumber];
}
This is where I try to grab the object and preform the function
const Fl = require(‘fleet.js’);
const fleet = Fl.getFleet(fleetNumber);
fleet.addActivity(activity);
I am also working in Node.js, which is how I am using the require method.
In combination with the answer from #audzzy I changed the getFleet() function so that it would be more efficient. I tested it out and it worked. This is what I used
function getFleet(fleetNumber) {
let result = fleets.filter(function (e) {
return e.number = fleetNumber;
})
return result[0];
}
Thanks for the help! I appreciate it.
you want to create a new fleet object and add it, not "this"..
adding "this" would cause a circular reference, where
this.fleets[i] = this (and all fleets would have the same value)
when calling get fleet, I would check that a fleet was returned from get fleet
in case amount is less than the number you send to getFleet (where according to what you posted: 1 returns the last, 2 returns second to last etc..)..
I hope this explanation makes sense.. anyways, this should work..
var fleets = [];
doStuff();
function doStuff(){
addFleet(1);
addFleet(2);
addFleet(7);
addFleet(3);
// should return null
let fleet1 = getFleetByNumber(5);
// should return the fleet with number 7, and not change the fleet with number 1
let fleet2 = getFleetByNumber(7);
if(fleet2){
fleet2.addActivity("activity");
}
console.log(`fleets: ${JSON.stringify(fleets)} \nfleet1: ${JSON.stringify(fleet1)} \nfleet2: ${JSON.stringify(fleet2)}`);
}
function addFleet(number) {
let fleet = { number: number,
activities: [] };
fleet.addActivity = function (activity) {
this.activities.push(activity);
};
fleets.push(fleet);
}
function getFleetByNumber(fleetNumber) {
return fleets.find(function (e) {
return e.number == fleetNumber;
});
}
function getFleet(fleetNumber) {
let result = null;
if(fleets.length - fleetNumber >= 0){
result = fleets[fleets.length - fleetNumber];
}
return result;
}

Convert to lower case and upper case , inside class with method using Javascript

Create a Str class with methods to:
Add lower method to convert a string to lower case.
Str.lower('EAT') // eat
Add upper method to convert a string to upper case.
Str.upper('today') // TODAY
I try with code below , but did not work
class Str {
constructor(lower,upper) {
this.lower = lower.toLoweCase();
this.upper = upper.toUpperCase();
}
}
Str.lower('HALO');
It is working
class Str {
constructor(lower,upper) {
this.lower = lower.toLowerCase();
this.upper = upper.toUpperCase();
}
}
let x = new Str('HALO','what');
x.lower; //halo
Your code this.lower = lower.toLowerCase(); is not creating a function. It is simply declaring a variable that holds the value of lower.toLowerCase(). Instead you should try the following
class Str {
constructor(lower,upper) {
this.lowerName = lower.toLowerCase();
this.upperName = upper.toUpperCase();
}
lower(input) {
return input.toLowerCase();
}
}
let y = Str.prototype.lower('WHAT'); //what
Unless you're creating an instance of Str, else invoking the function lower like above because the function sits inside prototype of class/object. You can picture it as function borrowing from Str class
Another way you can try as below:
class Str {
constructor(lower = "",upper="") {
this.lowerName = lower.toLowerCase();
this.upperName = upper.toUpperCase();
}
lower(input) {
return input.toLowerCase();
}
}
let strInstance = new Str();
console.log(strInstance.lower('WHY'));
Now the above code lets you create an instance of Str and invoke the function

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>

Access grandchild of a variable (parent.child.grandchild) without dots and one pair of brackets

I'm building a canvas-related class with a kind of conversion table. The conversion table can be edited by the user. (Isn't really relevant, but maybe you want to know why):
cLayout = function(option) {
//obtaining the canvas (el) here
this.setup = function(option) {
t=this.table;
for (var p in t)
{
el[t[p][0]] = option[p]||t[p][1]
}
}
this.setup(option)
}
cLayout.prototype.table = {
width:[['style']['width'],"100%"],
height:['style'['height'],"100%"],
bg:[['style']['backgroundColor'],""],
position:[['style']['position'],"absolute"],
left:['style'['left'],"0px"],
top:['style'['left'],"0px"]
}
Example:
var b = new cLayout({left:'10%',width:'90%'})
Real question:
Normally, I'd use el['style']['width'] to set el.style.width.
But I want to use el[something] without the second pair of brackets: I want the property name to be completely variable (I also want to be able to set el['innerHTML']). So, is there a way to get a grandchild by using a[b], without using a[b][c]?
P.S. Of course, I don't want to use eval.
No it is not possible. If you have nested objects, you cannot just skip a level.
You could write a helper function though, which takes a string like "child.grandchild" and sets the corresponding property:
function setProp(obj, prop, val) {
var parts = prop.split('.');
while(parts.length > 1) {
obj = obj[parts.shift()];
}
obj[parts.shift()] = val;
}
(You should also test whether a certain property is available.)
Then your code could look like:
var cLayout = function(option) {
//obtaining the canvas (el) here
this.setup = function(option) {
for(var p in this.table) {
setProp(el, this.table[p][0], option[p]||t[p][1]);
}
}
this.setup(option)
}
cLayout.prototype.table = {
width:['style.width',"100%"],
height:['style.height',"100%"],
//...
}

Javascript: Getting the newest array

I've been thinking about how to display the newest array (because the array list would update from time to time.). I think there's a default function to it but I can't find it. Anyone knows it?
var bgImg = new Array();
bgImg[0] = "background.jpg";
bgImg[1] = "background2.jpg";
bgImg[2] = "background3.jpg";
bgImg[3] = "background4.jpg";
If you want the last element of the array,
>>> a = ['background1','background2'];
["background1", "background2"]
>>> b = a[a.length-1]
"background2"
You shouldn't need to manually assign indexes. Just do bgImg.push('background2.jpg'), and it will mutate the array for you. In your case the syntax would be...
var last = bgImg[bgImg.length-1]
If you want the newest then you need to make a variable and set it with whatever you update when you push the newest one, if it doesn't become the last one.
You could create a little object to handle this for you.
function creatImageState() {
var images = [];
return {
get latest() {
return images[images.length - 1];
},
set latest (value) {
images.push(value);
}
};
}
var s = creatImageState();
s.latest = "a.png";
s.latest = "b.png";
alert(s.latest);
IE doesn't support getters and setters so you probably need to use this.
function creatImageState() {
var images = [];
return {
getLatest : function() {
return images[images.length - 1]
},
setLatest : function(value) {
images.push(value);
}
};
}
var s = creatImageState();
s.setLatest("a.png");
s.setLatest("b.png");
alert(s.getLatest());

Categories

Resources