Combines two arrays into one sentence - javascript

I'm new in javascript and I don't know how to merge some array. I want to reverse word manually but I mess up. It's my code:
function reverseString(kata) {
let currentString = kata;
let newString = '';
let cetakKata = '';
for (let i = kata.length - 1; i >= 0; i--) {
newString = newString + currentString[i];
}
console.log(newString);
const splitNewString = newString.split(' ')
console.log(splitNewString);
for (let i = 0; i < splitNewString.length; i++) {
const cetak = splitNewString[i].split('').reverse().join('')
cetakKata = cetakKata + cetak
}
console.log(cetakKata);
}
reverseString('hello java script');
my output:
scriptjavahello
output I want:
script java hello

function ReversedStringSentence (stringData) {
return stringData.split(" ").reverse().join(" ");
}
ReversedStringSentence("I am Greater everyday")

Reverse without .reverse()
reverseString('hello java script');
function reverseString(kata) {
let splited = kata.split(' ');
let reversed = [];
for (let i = 0; i < splited.length;i++) {
reversed.push(splited[(splited.length - 1) - i ]);
}
let stringReversed = reversed.join(' ');
console.log(stringReversed);
}

You probably wants to learn javascript and that's why you're doing it like you do, but there are already functions that does what you're trying to do.
arr.reverse() // reverses array
I don't know how many programming languages that you have learned, but what works best for me is to just read through all documentation so I know what kind of options I have at hand. I won't remember it all, but I will recognize them when I have to search for solutions.
https://developer.mozilla.org/en-US/docs/Learn/JavaScript
function reverseString(kata) {
const AT_SPACE = ' ';
return kata
.split(AT_SPACE)
.reverse()
.join(AT_SPACE);
}
let reversedKata = reverseString('hello java script');
console.log(reversedKata)

Related

Search for string or number in a string or number

I'm trying to implement a search of an object with multiple key/value pairs that can be either string or number.
This is what I'm currently using (simplified, of course):
const input = 'Hello WORld 21'; // this could also be of type number
const search = 'O w'; // this could also be of type number
let result = true;
let startTime, endTime;
const t0 = performance.now();
for (let i = 0; i < 1000000; i++) {
let parsedInput = JSON.stringify(input).toLowerCase().replace(/(^"|"$)/g, '');
let parsedSearch = JSON.stringify(search).toLowerCase().replace(/(^"|"$)/g, '');
result = parsedInput.indexOf(parsedSearch);
}
const t1 = performance.now();
console.log(`Call to doSomething took ${t1 - t0} milliseconds with result = ${result}`);
// ~393ms on a Ryzen 5600X
So this works, but seems to be expensive, especially when I go through tens of thousands of objects (or even more). So I wonder if there is a more elegant way to implement a search like this.
Thank you in advance!
Edit: Based on Sergio J's answer, here is what I got now:
const t2 = performance.now();
let i, s;
for (let j = 0; j < 1000000; j++) {
i = isNaN(input) ? input.toLowerCase() : input.toString().toLowerCase();
s = isNaN(search) ? search.toLowerCase() : search.toString().toLowerCase();
result = i.indexOf(s);
}
const t3 = performance.now();
console.log(`Call to doSomething took ${t3 - t2} milliseconds with result = ${result}`);
// ~66ms on a Ryzen 5600X
you may not need that Json.stringify, just toString() in the cases where the input is a number (check with isNaN()).
There are some post here talking about the efficiency of different methods.
JavaScript: indexOf vs. Match when Searching Strings? check the link to find the most suitable for your needs and users.
Here is a code snippet with a indexOf version, extracted in a function, that checks input and search values to convert them to string if necessary, and tells you what has been found.
function stringFinderIndexOf(input, search) {
let isNumber = !isNaN(input);
if (isNumber) {
input = input.toString();
}
let isSearchANumber = !isNaN(search);
if (isSearchANumber) {
search = search.toString();
}
let foundElement = input.toLowerCase().indexOf(search.toLowerCase()) !== -1;
if (foundElement) {
let isNumberText = isNumber ? "a numeric value" : "a text";
console.log("found with indexOf in " + isNumberText);
}
}
Of course, if you have as I understand an object, and you want to loop through, you could use Object.values() and a for loop.
function stringInObjectFinder(input, search) {
let values = Object.values(input)
for (const key in values) {
stringFinderIndexOf(key, search);
}
}
Find full code in a sandbox with a couple of functions using other methods as string.match(regex).
https://codesandbox.io/s/focused-chatterjee-gqijlr?file=/src/index.js
-------- Addition --------
Edit: as author suggested cleaner if, it is always a good idea to extract the if as a method with an explanatory name. In this case was left in order to put all code in a function to explain myself.
You can see in the function duplicated code already (smells).
function transformToStringIfNecessary(input) {
let isInputANumber = !isNaN(input);
if (isInputANumber) {
input = input.toString();
}
return input;
}
function containsInputTheSearchValue(input, search) {
return input.toLowerCase().indexOf(search.toLowerCase()) !== -1;
}
function stringFinderIndexOf(input, search) {
let isNumber = !isNaN(input);
input = transformToStringIfNecessary(input);
search = transformToStringIfNecessary(search);
let parsedInput = containsInputTheSearchValue(input, search);
if (parsedInput) {
let isNumberText = isNumber ? "a numeric value" : "a text";
console.log("found with indexOf in " + isNumberText);
}
}
You could clean the code even more, but guess you got the point.
Hope it helps.

Finding the index of several identical words

I have a laTeX string like this
let result = "\\frac{x}{2}+\\frac{3}{x}";
I want to find the index of "frac"s in the string and put them in a array then I want to find the first '}' char after "frac" and replace it with "}/" and finally remove "frac" from the string.
I used this block of code but it just work correctly when we have one "frac"
let result = "\\frac{x}{2}+\\frac{3}{x}";
if (result.indexOf("frac") != -1) {
for (let i = 0; i < result.split("frac").length; i++) {
let j = result.indexOf("frac");
let permission = true;
while (permission) {
if (result[j] == "}") {
result = result.replace(result[j], "}/")
permission = false;
}
j++;
}
result = result.replace('frac', '');
}
}
console.log(result)
OUTPUT: \\{x}//{2}+\\{3}{x}
Could anyone help me to improve my code?
Something like this?
frac(.+?)}
is the literal frac followed by a capture group that will capture one or more of anything .+ until a } and replace it with that anything plus a }/
Using the function replacement to grab index and replace
let result = "\\frac{x}{2}+\\frac{3}{x}";
let pos = [];
const newRes = result.replace(/frac(.+?)}/g,function(match, found, offset,string) {
console.log(match,found,offset,string)
pos.push(offset)
return `${found}/`; // return the found string with the added slash
})
console.log(pos)
console.log(newRes)
Older answer using two sets of code
let result = "\\frac{x}{2}+\\frac{3}{x}";
let re = /frac/gi, res, pos = [];
while ((res = re.exec(result))) {
pos.push(res.index);
}
const newRes = result.replace(/frac(.+?)}/g,"$1}/")
console.log(pos)
console.log(newRes)

How should I fix this asynchronicity problem in my "Josephus Problem" code?

Background
I'm new to JavaScript and am solving various formulations of the Josephus Problem to better understand the syntax. Using a circularLinkedList implementation*, I've solved the classic formulation: Wikipedia||Numberphile. I've also solved the problem for any fixed number of fighters and a fixed number of skips between eliminations (e.g., if skipping two fighters between eliminations, 1 eliminates 4, 5 eliminates 8, etc). I am now trying to solve the problem given any function that indicates the number of skips at a given moment.
Problem
I can't access the return value of my skip function. I understand from 1, 2, 3 that my issue involves asynchronicity, but am having trouble isolating takeaways from the long responses involving AJAX and jQuery, which I'm unfamiliar with. Could I get an ELI5 solution? I apologize for my lack of understanding.
Code
function winnerStepFunc(num, func) {
let cll = new circularLinkedList(); //Initializing list with participants
for (let a = 0; a < num; a++) {
cll.append(a);
}
function next(funcSteps) { //Generating string indicating #steps from function's output
let toEvaluate = "start";
for (let i = 0; i < funcSteps; i++) {
toEvaluate += ".next"
}
return toEvaluate;
}
let start = cll.getHead(); //Selecting first eliminator
while (cll.size() > 1) {
let toCheck = func(); // PROBLEM LINE
console.log("toCheck = " + toCheck); //toCheck = undefined
let str = next(toCheck);
while (eval(str) !== start && cll.size() > 1) { //
let locCurrent = cll.indexOf(start.element);
start = eval(str).next;
cll.removeAt(((locCurrent + toCheck)% cll.size()));
}
cll.delete(eval(str).next.element);
start = start.next;
}
console.log(start.element + 1);
}
function callFunction(name, args) { // builds function string to be evaluated
let result = name + "(";
for (let i = 0; i < args.length -1; i++) {
result += args[i] + ", ";
}
result += args[args.length-1] + ")";
return result;
}
function callFunction(name) {
let result = `${name}()`;
return result;
}
function addOne() { //<--The first basic example I'm trying:
return ++globalTimes; //Make the step increase by one for each elimination
}
var globalTimes = 0;
winnerStepFunc(12, function(){eval(callFunction("addOne"))});
*CLL Implementation
You don't return in your function. I would remove all the eval stuff and just call the function directly.
winnerStepFunc(12, addOne);

how to convert passed string to Camel Case

Hi I'm working on a problem that requires me to 'returns the passed string convertedToCamelCase'
I tried doing it like this
let wordsArr = words.toLowerCase().split(" ")
for (let i = 1; i<wordsArr.length; i++){
wordsArr[i] = wordsArr[i].charAt(0).toUpperCase()
wordsArr.slice(1)
}
return wordsArr.join("")
but that doesnt seem to work and now im stuck
Something like this should work if it doesn't contain punctuation
let camelot = "I have to push the pram a lot";
const makeCamel = s => {
let camelArray = s.toLowerCase().split(' ')
let newArray = [camelArray[0]]
for (let i in camelArray) {
if (i >= 1) {
let capLetter = camelArray[i][0].toUpperCase()
let rest = camelArray[i].slice(1);
let newWord = capLetter + rest
newArray.push(newWord);
}
}
return newArray.join('');
}
makeCamel(camelot)

How can I match a word inside of a string to word in a list EXACTLY?

I have been playing around with a pokemon API for a couple of days.
I have an array with all pokemon listed and have a string that looks something like this '<#user_id pidgeotto>'
I would like to check this string, against an array and get that EXACT name
My issue is that I ALSO get things that would be included, like pidgeot.
How can I match the array exactly to the string and ONLY log the one name?
let pokemonArray = ["pidgeot", "pidgeotto", "charizard", "goldeen"];
let y = '<#user_id> pidgeotto';
function handleMessage(message) {
for (let i = 0; i <= message.length; i++) {
if (y.includes(message[i])) {
console.log(message[i])
}
}
}
handleMessage(pokemonArray);
No errors, just not getting the result I am looking for.
Split the y string at the space and see if second part is exact using === comparison
let pokemonArray = ["pidgeot", "pidgeotto", "charizard", "goldeen"];
let y = '<#user_id> pidgeotto';
let yName = y.split(' ')[1];
function handleMessage(message) {
for (let i = 0; i <= message.length; i++) {
if (message[i] === yName ) {
console.log(message[i])
}
}
}
handleMessage(pokemonArray);
you could do it by this way to avoid the first element in PokemonArray
let pokemonArray = ["pidgeot", "pidgeotto", "charizard", "goldeen"];
let y = '<#user_id> pidgeotto';
function handleMessage(message) {
for(let i = 0; i <= message.length; i++) {
let splitedY = y.split(message[i])
if(splitedY.length > 1 && splitedY[1] !== "") {
console.log(message[i])
}
}
}
handleMessage(pokemonArray);
Here is the one liner for this:
const match = pokemonArray.find(pokemon => new RegExp(`\\b${pokemon}\\b`, `i`).test(y));
Simply use array find method and match your string using regex.
Hope this helps :)

Categories

Resources