so..
var songList = ["1", "2" ,"3","4","5","6","7","8","9","10"];
so my idea is to make a function which returns the first 5 Set of the values according to the index.
if
getList("1"); // is called.
it should result in "1 2 3 4 5" output.
and if
getList("2"); // is called
it should result in " 6 7 8 9 10"
It seems you need something like this:
var songList = ["01R!Wagner=_W!_March.mid ", "1004. score.mid ", "1005. yanni-one mans dream.mid ", "1006. haggstrom.mid ", "1007. la campanella pi.mid ", "1008. chp op18.mid ", "1009. Avicii - Wake Me Up.mid ", "101. Titanic my-heart will go on.mid ", "1010. 3intro.mid ", "1011. cast int.mid ", "1012. Action52Cheetahmen.mid ", "1013. pinkband.mid ", "1014. goldendreams.mid ", "1015. Reflections Of A Passion (Yanni).mid ", "1016. Nostalgia (Yanni).mid ", "1017. Rozen Maiden - Kinjirareta Asobi.mid ", "1018. Triple baka.mid ", "102. Konduktor.mid ", "1020. kraftwerk-franz schubert.mid ", "1021. naruto shippuuden - Blue Bird.mid ", "1022. naruto shippuuden - DIVER.mid ", "1023. dire-dire-docks-arranged-.mid ", "1024. koopa-s-theme.mid ", "1025. theme.mid ", "1026. the-last-spartan.mid ", "1027. xbox-startup-sequence.mid ", "1028. sml1-1.mid ", "1029. fourside1.mid ", "103. Minecraft - Sweden.mid ", "1030. eb hotel.mid ", "1031. smoke.mid ", "1032. whoboss.mid ", "1033. entrtanr.mid ", "1034. Eiffel 65- I'm blue (dabadee).mid "];
function makeList(index) {
var start = Math.max(0, (index-1)*5), // to avoid negative indexes
end = Math.min(index*5, songList.length); // to avoid out-of-bound
return songList.slice(start, end);
}
How about this
var songList = ["song_1.mp3","song_2.mp3",
"song_3.mp3","song_4.mp3",
"song_5.mp3","song_6.mp3",
"song_7.mp3","song_8.mp3"]
function makeList(index){
var songsLength = songList.length;
var num_songs = (index+5);
var next_songs = [];
if (num_songs > songsLength){
console.log("cant select index that is greater than length");
} else {
for(var i = index; i < num_songs;i++ ){
next_songs.push(songList[i]);
}
return next_songs;
}
}
You can pass any index to start from your list. with num_songs you can change how many songs you want to return. Remember that the index starts at 0, so if you want to be able to pass makeList(1) to return the first element, you could also set for (var i = (index-1); i < songsLength; i++)
makeList(3) will return the same as songList.slice(3, 8)
Check the fiddle
Related
This question already has answers here:
Why does generating a random number outside of a loop, causes it to be always the same?
(2 answers)
Closed 1 year ago.
here is my code
// import user input prompt
var inquirer = require('inquirer');
var emptyFamArray = [];
// ask the user how many relatives do they have
const getQuestions = () => {
inquirer.prompt([
{
name: "relatives_names",
type: 'input',
message: "Please input family first names seperated by a space. only 1-10 family members please!",
},
]).then((answers => {
// console.log(answers)
let test1 = JSON.stringify(answers.relatives_names).split(' ');
// console.log(test1);
let randomArrayName = test1[Math.floor(test1.length * Math.random())]
let randomArrayNameTwo = test1[Math.floor(test1.length * Math.random())]
console.log(randomArrayName)
if(test1.length > 10){
console.log('to many names please input 10 or less')
} else if (test1.length == 9){
console.log(randomArrayName + " Gets " + randomArrayNameTwo + " for christmas pickings!");
}else if (test1.length == 5){
console.log(randomArrayName + " Gets " + randomArrayNameTwo + " for christmas pickings!");
console.log(randomArrayName + " Gets " + randomArrayNameTwo + " for christmas pickings!");
console.log(randomArrayName + " Gets " + randomArrayNameTwo + " for christmas pickings!");
console.log(randomArrayName + " Gets " + randomArrayNameTwo + " for christmas pickings!");
console.log(randomArrayName + " Gets " + randomArrayNameTwo + " for christmas pickings!");
when it console logs it does randomise the names but it only returns the same value over and over
example
kylee Gets gerald for christmas pickings!
kylee Gets gerald for christmas pickings!
kylee Gets gerald for christmas pickings!
how would I fix this? im stuck and not entirly sure how to make the variables random everytime when logged
Thanks
When you are printing to the console the random selection have already happened and it happens only ones before you print out the names.
To make it select a random name each time , convert the selection to a function which you will call every time you want to print to console. For example:
var selectRandomName = function(names) {
return names[Math.floor(names.length * Math.random())]
}
console.log(selectRandomName(names) + " GETS " + selectRandomName(names) + " for Christmas pickings!");
Obviously this is oversimplified and you probably should also prevent selection of the same name twice and other similar cases, but this is out of the scope of current question. I assume this is some sort of exercise, as in real world application you should use some readily available matching libraries.
I have an array that contains several countries followed by an option and a number.
0 " UK One 150 "
1 " Switzerland Two 70 "
2 " China Two 120 "
3 " Switzerland One 45 "
4 " China One 90 "
5 " UK Two 50 "
This is how I get the array using xpath:
var iterator = document.evaluate('//xpath/li[*]', document, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);
try {
var thisNode = iterator.iterateNext();
var arrayList = [];
while (thisNode) {
arrayList.push(thisNode.textContent);
thisNode = iterator.iterateNext();
}
for (var i = 0; i < arrayList.length; i++) {
console.log(arrayList[i]);
}
} catch (e) {
dump('Error' + e);
}
arrayList
What I would like to do with this array is to sort out and return only the matches. E.g. I would like for it to return only UK and China, so the array would look like this.
0 " UK One 150 "
1 " China Two 120 "
2 " China One 90 "
3 " UK Two 50 "
You can do it like this with help of sort() filter() and regex
What i did is first filter all the elements which contains either UK or China.
Now on this filtered array i need to capture the number using regex and sorted them in descending order.
let arr =[
"UK One 150 ",
"Switzerland Two 70 ",
"China Two 120 ",
"Switzerland One 45 ",
"China One 90 ",
"UK Two 50 ",
];
let op = arr.filter(e=>
/(UK|China)/gi.test(e))
.sort((a,b)=>{a.match(/\d+/g) - b.match(/\d+/g)}
);
console.log(op);
You can filter your array using the regular expression and then sort the result on the numeric value.
let data =["UK One 150 ","Switzerland Two 70 ","China Two 120 ","Switzerland One 45 ","China One 90 ","UK Two 50 "],
result = ((arr) => data.filter(s => new RegExp(arr.join('|'), 'ig').test(s)))(['UK', 'China'])
.sort((a,b)=> +a - +b);
console.log(result);
You can use a form of Schwartzian transform to "decorate" the data by extracting the name of the country, and the number using a array.map() and regex.
Now you can filter by the country, sort by the number, and extract the str using another map.
const arr =[
"UK One 150 ",
"Switzerland Two 70 ",
"China Two 120 ",
"Switzerland One 45 ",
"China One 90 ",
"UK Two 50 ",
];
const pattern = /^(\S+)\D+(\d+)/;
const requestedCounteries = new Set(['UK', 'China']);
const result = arr
.map(str => str.match(pattern)) // ['UK One 150 ', 'UK', '150']
.filter(([,country]) => requestedCounteries.has(country))
.sort(([,,a], [,,b]) => +b - +a)
.map(([str]) => str);
console.log(result);
I have a code that I am working on , it is for ordering pizza. I have been coding for 7 days and I want to find out how can I make the pizza prices bigger by the size of the pizza
For example , small pizza is 15.75$ medium is 16.75 and big is 17.75
Each time I run the code , the output is 15.75
(Look at the bottom portion)
employee = confirm("Are you ready to take an order?");
if (employee === true) {
console.log("Here is the order");
} else {
console.log("Ask another employee to take the order. If there is no one, then please take the order ");
}
let orderCount = 0;
const takeOrder = (topping, crustType) => {
orderCount++;
console.log("Order: " + crustType + " pizza topped with " + topping);
};
//
// Order comes here like this - takeOrder('pepperoni', //'texas style');
takeOrder('pepperoni', 'texas style');
//
const getSubTotal = (itemCount) => {
return itemCount * 14.5;
};
//const ^^
console.log("The Sub-Total is " + getSubTotal(orderCount) + "$");
const getTax = (itemCount) => {
return itemCount * 1.25;
};
console.log("The tax is " + getTax(orderCount) + "$");
const getTotal = () => {
return getSubTotal(orderCount) + getTax(orderCount);
};
console.log("And the final total is " + getTotal() + "$");
console.log("Thank you for taking this order.")
As for one of the comments, the price relative to size is not in your logic:
let priceBySize = {
'S': 15.75,
'M': 16.75,
'L': 14.5,
}
// size of order required - might consider also to pass quantity
takeOrder('pepperoni', 'texas style', 'M');
takeOrder('margherita', 'clasic style', 'L');
const getSubTotal = (itemCount, size) => {
return itemCount * priceBySize[size];
};
Also instead of fixed prices for size maybe you'll prefer to have multipliers for sizes and base price per type of pizza.
I make my own dictionary, I keep all word in an object. I use by put some content into content variable
and loop for find the word if which word found, should add message.
How I have to do it?
Can I have result like this
Boom is an American company. It wants to make a new plane. The plan is to have a plane in 2023 The plane will(to happen in the future) be supersonic. It will(to happen in the future) fly from London to New York in three hours. The flight(a journey in an aircraft) ticket will(to happen in the future) not be extremely expensive. It will(to happen in the future) cost as much as a standard business class ticket.
mycode
let content = "Boom is an American company. It wants to make a new plane. The plan is to have a plane in 2023 The plane will be supersonic. It will fly from London to New York in three hours. The flight ticket will not be extremely expensive. It will cost as much as a standard business class ticket.";
var myDictionary =
{
will: "to happen in the future",
flight: "a journey in an aircraft",
cost: "the amount of money needed to buy",
particular: "or this and not any other"
}
for(let i in myDictionary) {//each word
for(i=0;/**/)//this word found, such as "will" have to 4 rounds
{
/*loop for find, how many position in this word.
if this word has 2 positions that first loop add my transalate message after the fist position of word and round 2, if more it's have to keep loop until no found this position and out to main loop for find next word
add in the second position.
*/
generate(i);
}
}
function generate(word)
{
let find_position = content.indexOf(word);
console.log(find_position);
let length_of_word = word.length;
let find_position_after_word = find_position + length_of_word;
let transalate_word = getProperty(word);
let output = content.slice(0, find_position_after_word), transalate_word, content.slice(find_position_after_word)].join('');
}
function getProperty(word_for_transalate)
{
return myDictionary[word_for_transalate];
}
Try reduce with replace
var output = Object.keys(myDictionary).reduce( function(a,b,i){
if (i == 1)
{
a = content.replace( new RegExp( a, "gi" ), a + "(" + myDictionary[ a ] + ")" );
}
a = a.replace( new RegExp( b, "gi" ), b + "(" + myDictionary[ b ] + ")" );
return a;
});
Demo
var content = "Boom is an American company. It wants to make a new plane. The plan is to have a plane in 2023 The plane will be supersonic. It will fly from London to New York in three hours. The flight ticket will not be extremely expensive. It will cost as much as a standard business class ticket.";
var myDictionary = {
will: "to happen in the future",
flight: "a journey in an aircraft",
cost: "the amount of money needed to buy",
particular: "or this and not any other"
};
var output = Object.keys(myDictionary).reduce(function(a, b, i) {
if (i == 1) {
a = content.replace(new RegExp(a, "gi"), a + "(" + myDictionary[a] + ")");
}
a = a.replace(new RegExp(b, "gi"), b + "(" + myDictionary[b] + ")");
return a;
});
console.log( output );
Find position of string within your string and append the value of key-value pair next to it within braces.
var a = "Boom is an American company. It wants to make a new plane.";
var obj = {
"wants" : "2",
"is": "one"
}
for(var key in obj) {
let position = a.indexOf(key) + key.length + 1;
a = [a.slice(0, position), '('+obj[key]+')', a.slice(position)].join('');
}
console.log(a)
I am taking an online JavaScript class and am stuck on a problem involving objects. In the following code, my assignment is to output a string that retrieves the name of each ranger (e.g. lighthouseRock.ranger1.name) and match their station to the corresponding item in the superBlinders array.
If I hard-code the ranger1 property, the output format is in the right ballpark. However, if I try to be creative and build a variable (thisRanger) to dynamically insert the appropriate ranger into my object, the routine returns an error "TypeError: Cannot read property 'name' of undefined". My thisRanger variable builds OK but whenever I try to insert it into my chain after lightHouseRock it causes the undefined problem. Here is my code:
var superBlinders = [ ["Firestorm", 4000], ["Solar Death Ray", 6000], ["Supernova", 12000] ];
var lighthouseRock = {
gateClosed: true,
weaponBulbs: superBlinders,
capacity: 30,
secretPassageTo: "Underwater Outpost",
numRangers: 0
};
function addRanger(location, name, skillz, station) {
location.numRangers++;
location["ranger" + location.numRangers] = {
name: name,
skillz: skillz,
station: station
};
}
addRanger(lighthouseRock, "Nick Walsh", "magnification burn", 2);
addRanger(lighthouseRock, "Drew Barontini", "uppercut launch", 3);
addRanger(lighthouseRock, "Christine Wong", "bomb defusing", 1);
var dontPanic = function () {
var message = "Avast, me hearties!\n";
message += "There be Pirates nearby! Stations!\n";
for (var i = 1; i <= lighthouseRock.numRangers; i++) {
var thisRangerNumber = i;
var thisRanger = "ranger" + thisRangerNumber;
// message += lighthouseRock.ranger1.name + ", man the " + superBlinders[lighthouseRock.ranger1.station][0] + "!\n";
message += lighthouseRock.thisRanger.name + ", man the " + superBlinders[lighthouseRock.thisRanger.station][0];
};
console.log(message);
}
The expected output should look something like this:
Avast, me hearties!
There be Pirates nearby! Stations!
<name>, man the <superblinder>!
<name>, man the <superblinder>!
<name>, man the <superblinder>!
How can I insert thisRanger into my code so that it gives me the expected output? Thank you very much for your help!
Working code!
It outputs all you want it todo!
UPDATE you have an error in your code I fixed that also..
Ranger2 will always be stationed on undefined since there aren't 3 stations when counting as an array, remember array in javascript starts counting from 0(zero). I changed Drew barontini to "0"
addRanger(lighthouseRock, "Nick Walsh", "magnification burn", 2);
addRanger(lighthouseRock, "Drew Barontini", "uppercut launch", 0);
addRanger(lighthouseRock, "Christine Wong", "bomb defusing", 1);
CODE OUTPUT
Avast, me hearties!
There be Pirates nearby! Stations!
Nick Walsh, man the Supernova,12000 Drew Barontini, man the Firestorm,4000Christine Wong, man the Solar Death Ray,6000
I didn't do much to change your code. But what I did is that I change your code into
message += lighthouseRock[thisRanger].name + ", man the " + superBlinders[lighthouseRock[thisRanger].station] +"\n";
Its important to know with javascript that you can use brackets [] to get to an object property if you build the stirng dynamicly.
var superBlinders = [ ["Firestorm", 4000], ["Solar Death Ray", 6000], ["Supernova", 12000] ];
var lighthouseRock = {
gateClosed: true,
weaponBulbs: superBlinders,
capacity: 30,
secretPassageTo: "Underwater Outpost",
numRangers: 0
};
function addRanger(location, name, skillz, station) {
location.numRangers++;
location["ranger" + location.numRangers] = {
name: name,
skillz: skillz,
station: station
};
}
addRanger(lighthouseRock, "Nick Walsh", "magnification burn", 2);
addRanger(lighthouseRock, "Drew Barontini", "uppercut launch", 0);
addRanger(lighthouseRock, "Christine Wong", "bomb defusing", 1);
var dontPanic = function () {
var message = "Avast, me hearties!\n";
message += "There be Pirates nearby! Stations!\n";
for (var i = 1; i <= lighthouseRock.numRangers; i++) {
var thisRangerNumber = i;
var thisRanger = "ranger" + thisRangerNumber;
// message += lighthouseRock.ranger1.name + ", man the " + superBlinders[lighthouseRock.ranger1.station][0] + "!\n";
message += lighthouseRock[thisRanger].name + ", man the " + superBlinders[lighthouseRock[thisRanger].station] +"\n";
};
console.log(message);
}
dontPanic();