I am learning ES 6 online and I have test:
Implement the findLargestString function, which has a single argument
strings (an array of strings), which will set the largestString
variable defined at the top to the string which has the longest length
of the array of strings passed in as the strings parameter.
On start I have method:
let largestString;
function findLargestString(strings) {
// set largestString to point to the
// longest string found in the strings array passed in
}
So I am tried:
let largestString;
function findLargestString(strings) {
let largestString = '';
strings.forEach((string) => {
if (string.length > largestString.length) {
largestString = string;
}
});
return largestString;
}
But this return error:
largestString should be set to the largest string passed in
Expected undefined to equal 'computers'.
How can I make it?
Your code seems to be working fine for me
let largestString;
function findLargestString(strings) {
let largestString = '';
strings.forEach((string) => {
if (string.length > largestString.length) {
largestString = string;
}
});
return largestString;
}
var arr = new Array('', 'aa', 'test')
console.log(findLargestString(arr));
Use the return value of your function and take a look at how 'let' works
let largestString = findLargestString(strings);
Related
This is a double question because I can just post once every 90 minutes.
First I have to write a function that replaces a character of a string.
//====================== EXAMPLE ========================
var str = "I,Really,Like,Pizza";
characterRemover(str, ",");
"I Really Like Pizza"; // <====== EXPECTED OUTPUT
//=========================================================
And puts a space in place of the chosen character. I tried this but is not working.
function chracterRemover(str, cha){
var replaced = str.split('cha').join(' ');
return replaced;
}
It returns just the same string.
And the second thing is that I have to write a function that returns true if the data type introduced is an arrat and false for the rest.
//====================== EXAMPLE ========================
var one = { name: "antonello" };
false; // <====== EXPECTED OUTPUT
var two = ["name", "antonello"];
true; // <====== EXPECTED OUTPUT
var three = [[], [], {}, "antonello", 3, function() {}];
true; // <====== EXPECTED OUTPUT
//=========================================================
I've tried this.
function isArrayFun(array){
if {
typeof array = 'array';
return "Array";
} else {
return "Not an array"
}
}
But as well, it doesnt work.
I get this error:
Uncaught SyntaxError: Unexpected token '{'
I don't know why.
Thanks in advance for the help.
// First One
const str = "I,Really,Like,Pizza";
console.log(str.split(',').join(' '));
// Second One
function isArrayFun(array){
return Array.isArray(array);
}
const one = { name: "antonello" };
console.log(isArrayFun(one));
const two = ["name", "antonello"];
console.log(isArrayFun(two));
const three = [[], [], {}, "antonello", 3, function() {}];
console.log(isArrayFun(three));
Problem 1:
You quoted cha so it's a literal string, not the variable. Use
function characterRemover(str, cha) {
var replaced = str.split(cha).join(' ');
return replaced;
}
var str = "I,Really,Like,Pizza";
console.log(characterRemover(str, ","));
Problem 2:
typeof returns object for arrays. The way to tell if something is an array is by calling Array.isArray().
You also have syntax errors in your if statement. The condition has to be inside (), not after {.
function isArrayFun(array) {
if (Array.isArray(array)) {
return "Array";
} else {
return "Not an array"
}
}
var one = { name: "antonello" };
console.log(isArrayFun(one));
var two = ["name", "antonello"];
console.log(isArrayFun(two));
var three = [[], [], {}, "antonello", 3, function() {}];
console.log(isArrayFun(three));
First question.
The function name is different than the function you called
you should use .split(cha) and not 'cha'. split cha will actually split your string by the string you passed into that parameter. And 'cha' looks for the string 'cha'
Working example:
var str = "I,Really,Like,Pizza";
function chracterRemover(str, cha){
var replaced = str.split(cha).join(' ');
return replaced;
}
console.log(chracterRemover(str, ","));
You could also use a simple RegExp instead of using split and join and take the function to another level by making it globally useful via a 3rd parameter, in which you could define the replacement:
var str = "I,Really,Like,Pizza";
function chracterRemover(str, cha, chaTo){
var reg = new RegExp(cha, "g");
return str.replace(reg, chaTo);
}
console.log(chracterRemover(str, ",", " "));
console.log(chracterRemover(str, ",", "."));
Second question:
There is already a function like that
Array.isArray(value)
you can pass any type of data into that value, if it is an array it returns true
working example:
let type1 = [1,5,6];
let type2 = {a: 47};
let type3 = 5;
let type4 = "hello";
console.log(Array.isArray(type1))
console.log(Array.isArray(type2))
console.log(Array.isArray(type3))
console.log(Array.isArray(type4))
I'm reading values from excel and then trying to build a function based on parameters it has.
It will have dynamic parameters in combination of strings and arrays as per its usage in function.
My sample code as below
excel
A1 = 'test'
A2 = ['test1','test2']
JS
function test(params){
..
var paramValues = params.split(","); //params1=A1, params2=A2 here params is sheet name
if(paramValues != null)
{
for(var pi = 0;pi<paramValues.length;pi++)
{
index = paramValues[pi].substring(6) //returns value of row number as index
var paramCellVal = await excel.getCellValue("A"+index) //returns 'test' in iteration 1,['test1','test2'] in iteration 2
actualParams.push(paramCellVal) //push values to array
}
console.log(actualParams+"actualParams"+typeof(actualParams)) //returns object
action = findFunction(...actualParams);
}
else
{
...
}
}
function findFunction(...actualParams){
run(...actualParams)
}
function run(param1, param2){
console.log(param1, typeof(param1))
console.log(param2, typeof(param2))
console.log(param2[0], typeof(param2[0]))
console.log(param2[0], typeof(param2[1]))
}
expected output:
'test', string
['test1','test2'], object
'test1', string
'test2', string
actual output:
'test', string
['test1','test2'], string
[, string
', string
My expectation is to build dynamic function with different set of variables, hence used spread syntax.
function run(param1, param2){
console.log(param1, typeof(param1))
console.log(JSON.stringify(param2), typeof(JSON.stringify(param2)))
console.log(JSON.stringify(param2[0]), typeof(JSON.stringify(param2[0])))
console.log(JSON.stringify(param2[1]), typeof(JSON.stringify(param2[1])))
}
I have a complex object in typescript that i want to be able to change with a single function (I know how hacky this sounds, but its a hobby project). The function takes a value and a path as a rest-parameter. The path can be of any length.
I want to change the property, but so far I've only come up with solutions that lose the reference to the original object, and as such is not a working solution.
I've tried using both whiles and for loops to iterate over the array and "zooming" in on the property. In each case, they lost the reference to the original object and thus didn't mutate it.
I've tried accessing the object directly, with a known length, and that works but its hardcoded to a length and as such isn't a good solution either. In a desperate case, i could make a function like this for each size I'm expecting (it's somewhat limited) but that hurts my pride.
Example
character: Character = {
characteristics: {
0: {
initial: 30,
advances: 15
}
1...
}
}
this.updateProperty(35, characteristics, 0, initial) //Change characteristics.0.initial to be 35 instead of 30
With a for/while loop:
updateProperty(value: string|number,...path: string[]) {
let scope: Object = this.character;
for(let p of path) {
scope = scope[p];
}
scope = value;
console.log(scope);
console.log(this.character);
}
the scope is updated correctly, but the character is not changed
With direct access (Here of length 3)
updateProperty(value: string|number,...path: string[]) {
this.character[path[0]][path[1]][path[2]] = value;
}
Here its updated correctly, but its no longer taking in any length as it will crash if its longer than 3 and break it if shorter than 3
Attempt to access it directly with an array
updateProperty(value: string|number,...path: string[]) {
this.character[path] = value;
}
Gives
ERROR in src/app/character.service.ts(27,20): error TS2538: Type 'string[]' cannot be used as an index type.
Considering your direct access works fine for you, you can try something like:
let character = {
characteristics: {
0 : {
initial: 30,
advances: 15
}
}
}
function updateProperty(value,...path) {
let finalOb, i;
for (i = 0; i < path.length; i ++) {
let tempOb
if (finalOb) {
tempOb = finalOb[path[i]];
} else {
tempOb = character[path[i]];
}
if (tempOb instanceof Array || typeof tempOb !== 'object') {
break;
} else {
finalOb = tempOb;
}
}
finalOb[path[i]] = value;
}
updateProperty(35, 'characteristics', '0', 'initial')
console.log(character)
updateProperty(value: string|number,...path: string[]) {
let scope: Object = this.character;
for(let p of path) {
scope = scope[p];
}
scope = value;
console.log(scope);
console.log(this.character);
this.character = scope; //?
}
I am working on a function where I pass an object (record) to a function. It then loops over the keys and checks to see if that key is in our second object (lookup). If there is a match, it replaces the value in our record with a manipulated version (turns it into a link). If there is no match, it keeps its original value.
This is what I am passing to the function:
{ Source: "1234", NTID: "joeBob", Department: "x123", Email: 'joebob#example.com' }
-Here is the function
function createLink2(record) {
// Link types
var output = {
'ntid': 'https://example.com/profile/',
'email': 'mailTo:'
};
// Vars
var i,
key,
keys = Object.keys(output);
// Loop over our object keys
Object.keys(record).forEach(function(k, ind) {
// Loop over each of the link types
for ( i = 0; i < keys.length; ++i ) {
key = keys[i];
// If our key matches that of our object, turn it into a link
if(k.toLowerCase() == key){
record = ''+record[k]+'';
}else{
// Return the original value of the property since its not a match. Not quite sure how to do this part.
}
}
});
return record;
}
My goal here is that it would replace the value of Email with joeBob#example.com and NTID with joeBob.
The issue I am having is with the return - Not quite sure how to edit the data and return the full object back.
change this line:
record = ''+record[k]+'';
to this:
record[k] = ''+record[k]+'';
Of course, you could do this more easily by referring to the properties of the object directly:
function createLink2(record) {
// Link types
var output = {
'NTID': 'https://example.com/profile/',
'Email': 'mailTo:'
};
// Loop over the output keys
Object.keys(output).forEach(function(k, ind) {
if(record.hasOwnProperty(k)) {
record[k] = '' + record[k] + '';
}
});
return record;
}
Note that you don't really need to return it since the contents of the object will be changed directly as mentioned by others in the comments.
Javascript objects are passed by reference. So if you modify the object in the function it will be enough. Example:
function test(obj) {
obj.a = 10
}
var x = {a: 2};
test(x);
console.log(x.a) //prints 10
So, all you have to do is modify the value of "Email" with whatever you want.
You can iterate over an array and return an object using .reduce()
function createLink2(record) {
// Link types
var output = {
'ntid': 'https://example.com/profile/',
'email': 'mailTo:'
};
// Vars
var keys = Object.keys(output);
// Loop over our object keys
record = keys.reduce(function(obj, currKey) {
if (obj[currKey] != undefined) {
obj[currKey] = '' + obj[currKey] + ''
}
return obj;
}, record);
return record;
}
console.log(createLink2({ntid: "12345", email: "joebob#gmail.com"}));
This is my assignment:
By now you should have worked with the length property of strings, e.g. "hello".length. Your task is to write a function called stringLength that accepts a string as a parameter and computes the length of that string; however, as you may have guessed, you are not allowed to use the length property of the string!
Instead, you'll need to make use of the string method called slice.
For our purposes, we can consider slice as taking one argument -- the index to begin slicing from, and returns a new string starting from that index onwards.
This is what I tried:
function stringLength(string){
var count = count++;
if(string.slice(0)){
return count}
return stringLength(string.slice(0,-1))
}
console.log(stringLength("game"))
I am trying to slice each character of the string back to start index, index 0, and then accumulate my count variable. I do not understand why my count variable is not accumulating.
An iterative proposal.
function stringLength(string) {
var count = 0;
while (string) {
string = string.slice(1);
count++;
}
return count;
}
console.log(stringLength("game"));
A recursive proposal.
function stringLength(string) {
return string ? 1 + stringLength(string.slice(1)) : 0;
}
console.log(stringLength("game"));
Hmm i tried to write code in the same format that you did.
function stringLength(str, count){
if(!str.slice(0)){
return count;
}
return stringLength(str.slice(0,-1), ++count)
}
console.log(stringLength("game", 0))
I'll point out the mistakes in your original code so that its easy to understand.
The recursion base case was incorrect. string.slice(0) will return
true if the string is non-empty, so use !string.slice(0)
The count value was not initialized and it wasn't being passed down
the recursion.
Your count variable is a separate variable for each function invocation, so it will always get the same value and not keep incrementing.
You could use this:
function stringLength(string){
return string ? 1 + stringLength(string.slice(0,-1)) : 0;
}
console.log(stringLength("game"))
A bit shorter would be to take out the first character instead of the last:
return string ? 1 + stringLength(string.slice(1)) : 0;
You really should try to figure it out yourself. Otherwise, are you really learning the subject?
function stringLength(string) {
if(!string) return 0;
var length = -1;
while(string.slice(length) !== string) --length;
return -length;
}
A variation taking into account your odd definition of slice():
function stringLength(string) {
var length = 0;
while(string.slice(length) !== "") ++length;
return length;
}
I guess you could try to use recursion like this:
function stringLength(string) {
if (string) {
return 1 + stringLength(string.slice(1))
} else return 0
}
function stringLength(string) {
var len = 0;
while (string) {
string = string.substring(1);
len++;
}
return len;
}
console.log(stringLength("boss"));
this works as well.