24-hour dropdown menu using Array.from( Array(n) ).map(String) - javascript

trying to get better at making my code less dense but I'm stumped on this one. what's the best way to use a dropdown menu to choose between options 1-24, while the array is nested within an object?
I am trying to make a chrome extension to create notifications for different time functions from the local time (ie 1hr, 3hrs, 12hrs, etc)
I know it works with this array here:
var d = new Dropdown({
id: 'd',
val: 'custom:',
data: ['1 hour', '2 hours', '3 hours', '4 hours', '5 hours', '6 hours', '7 hours', '8 hours', '9 hours', '10 hours', '11 hours', '12 hours', '13 hours', '14 hours', '15 hours', '16 hours', '17 hours', '18 hours', '19 hours', '20 hours', '21 hours', '22 hours', '23 hours', '24 hours'],
cb: function cb(newval) {
alert(newval);
}
});
for the future, to avoid the rewriting of 24 separate options would this logic work? it returns the items as an array of strings with the values being updated as the first parameter, but I am not sure if it's bad practice.
let h = Array.from(Array(24).toString(),
(_hour, index) => `${[index + 2]} hours`).map(String);
const itr = h.values();
console.log(Array.isArray(h)); // outputs true
console.log(itr); // outputs {[Iterator]}
// here's where I get lost
if there's an easier way that I'm just missing please let me know. I prefer this to the html input, since I am not messing with dates in the timer, just logging the local time +n.

Use map and check to use plural or not.
const hours = new Array(24).fill(0).map((_, i) => `${i+1} hour${i > 0 ? 's' : ''}`)
console.log(hours)

You can use spread the array and then use map() on it.
const arr = [...Array(24)].map((_, i) => `${i + 1} hours`);
console.log(arr)

Related

Morris line chart is not working properly

I created this simple line chart using morris.js. But it is not showing data properly. I don't know why?
Please check it at js fiddle.
Js fiddle: link
new Morris.Line({
element: 'multi-line-mp',
data: [
{
day: 'Jan 1',
sales: '0',
purchases: '1'
},
{
day: 'Jan 2',
sales: '14',
purchases: '3'
},
{
day: 'Jan 3',
sales: '45',
purchases: '0'
},
{
day: 'Jan 4',
sales: '47',
purchases: '32'
},
{
day: 'Jan 5',
sales: '90',
purchases: '10'
}
],
xkey: 'day',
ykeys: ['Sales', 'Purchases'],
labels: ['Sales', 'Purchases'],
resize: true
});
The date format of your xkey (day) is not good, this is rather a string than a real date.
You have 2 choices:
change the format of the xkey to be a real date (like 2021-01-01 instead of Jan 1)
set the option parseTime to false, so that it won't try to format the string to be a date
In case you change the format of xkey, you still can change the way the date is displayed thanks to the function dateFormat (see the documentation for this here: http://morrisjs.github.io/morris.js/lines.html)

How to get Highcharts XAxis to Display in 2 Minute Intervals

I am somewhat new to Highcharts and I am trying to pull off something that I am sure can be done but I cant figure it out.
I have posted my jsfiddle here: https://jsfiddle.net/dfeagin/1hn6c9ad/7/
Here is what the data looks like in my categories section for that axis:
categories: ['1/20/2020 9:22:02 PM', '1/20/2020 9:22:03 PM', '1/20/2020 9:22:04 PM', '1/20/2020 9:22:08 PM', '1/20/2020 9:22:09 PM', '1/20/2020 9:22:10 PM', '1/20/2020 9:22:12 PM', '1/20/2020 9:22:14 PM', '1/20/2020 9:22:15 PM', '1/20/2020 9:22:16 PM', '1/20/2020 9:22:18 PM', '1/20/2020 9:22:19 PM'.....]
On the XAxis, which represents minutes, there are a total of 46 minutes between the start to end time frame. I want to show two minute increments and just show the minute number vs. a date/time stamp:
0 2 4 6 8 10 ..... 42 44 46
How can I get it to do that? The data will have differing numbers of data points between those two minute increments but I want the 2 min intervals to be consistent.
Another note: I am generating the data that I feed to Highcharts in a .net web application so if it helps the situation I can send in a series of minute numbers vs. time/date stamps. So I could be sending over:
categories: ['0', '0', '0', '1', '1', '2', '2', '2', '2', '2', '2', '2', '3', ... '43', '43', '43', '44', '44', '45', '45', '45', '45', '45', '45', '45', '46', '46']
I think you would be better setting the chart up as spline rather than each series, with a datetime x-axis and putting data into the series as an array of date/value x/y pairs.
This way you can have more control over the xAxis ticks in this case setting tick interval to 2 minutes, and is more flexible in general.
Use a custom formatter to manipulate the tick value.
https://jsfiddle.net/gazx45oy/
Chart type:
chart: {
type: 'spline',
xAxis settings:
xAxis: [{
type: 'datetime',
startOnTick: true,
minPadding: 0,
tickInterval: 120000,
labels: {
formatter: function () {
return (this.value - this.axis.min) / 60000;
},
Series data:
var vesselSteamTemp = [
[Date.UTC(2020,20,1,9,22,2), 119],

Localizing day and month in moment.js [duplicate]

This question already has answers here:
display day and month, without a year according to locale
(5 answers)
Closed 5 years ago.
How can I localize current day and month (without year) in moment.js? What I want is exactly the output of moment().format('LL') but without the year part.
Consider the following example:
moment().locale('tr').format('LL') // "1 Haziran 2017"
moment().locale('en').format('LL') // "June 1, 2017"
What I want is these:
moment().locale('tr').format('??') // "1 Haziran"
moment().locale('en').format('??') // "June 1"
For error prone solution for all supported locales, you need to remove year with .replace and check for unnecessary symbols left:
function getCurrDayAndMonth(locale) {
var today = locale.format('LL');
return today
.replace(locale.format('YYYY'), '') // remove year
.replace(/\s\s+/g, ' ')// remove double spaces, if any
.trim() // remove spaces from the start and the end
.replace(/[рг]\./, '') // remove year letter from RU/UK locales
.replace(/de$/, '') // remove year prefix from PT
.replace(/b\.$/, '') // remove year prefix from SE
.trim() // remove spaces from the start and the end
.replace(/,$/g, ''); // remove comma from the end
}
['af' , 'ar-dz', 'ar-kw', 'ar-ly', 'ar-ma', 'ar-sa', 'ar-tn', 'ar', 'az', 'be', 'bg', 'bn', 'bo', 'br', 'bs', 'ca', 'cs', 'cv', 'cy', 'da', 'de-at', 'de-ch', 'de', 'dv', 'el', 'en-au', 'en-ca', 'en-gb', 'en-ie', 'en-nz', 'eo', 'es-do', 'es', 'et', 'eu', 'fa', 'fi', 'fo', 'fr-ca', 'fr-ch', 'fr', 'fy', 'gd', 'gl', 'gom-latn', 'he', 'hi', 'hr', 'hu', 'hy-am', 'id', 'is', 'it', 'ja', 'jv', 'ka', 'kk', 'km', 'kn', 'ko', 'ky', 'lb', 'lo', 'lt', 'lv', 'me', 'mi', 'mk', 'ml', 'mr', 'ms-my', 'ms', 'my', 'nb', 'ne', 'nl-be', 'nl', 'nn', 'pa-in', 'pl', 'pt-br', 'pt', 'ro', 'ru', 'sd', 'se', 'si', 'sk', 'sl', 'sq', 'sr-cyrl', 'sr', 'ss', 'sv', 'sw', 'ta', 'te', 'tet', 'th', 'tl-ph', 'tlh', 'tr', 'tzl', 'tzm-latn', 'tzm', 'uk', 'ur', 'uz-latn', 'uz', 'vi', 'x-pseudo', 'yo', 'zh-cn', 'zh-hk', 'zh-tw'].forEach(localeName => {
console.log(
localeName + ':',
getCurrDayAndMonth(moment().locale(localeName)));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>
Do you just want the string representation? If so, it might be easier to just trim the last 5 chars from the end of the output, like so:
var today = moment().locale('tr').format('LL') // "1 Haziran 2017"
today = today.substring(0, today.length - 5); // "1 Haziran"
This'll work for the next 8000 years, so no real need to worry about future years breaking it.
You could even do smarter regex matching, or just remove everything with ", 20XX" from the string. Depends on your uses of it though, this is more of a hacky workaround than a direct solution.
Here's an example of how it can work:
var d = moment().locale('tr');
console.log(d.format('D MMMM'));
JSFiddle: https://jsfiddle.net/webbm/wuwkwzou/

how to get date Object when select from dropdown list

I have a drop down list(screenshot attached),when we select any one like this year so how can we send StartIndex and EndIndex in backend using date Object using javascript,angular js.
Thanks In Advance any help will be appriciated
StatIndex:2016-01-01T00:00:00+5:30
EndIndex :2016-12-31T23:59:59+5:30
code for Index Range
this.indexRanges = ['This Year', 'Last Year', 'This Quarter', 'Last Quarter', 'This Month', 'Last Month', 'This Week',
'Last Week', 'Last 72 Hours', 'Last 48 Hours', 'Last 24 Hours', 'Today', 'Yesterday', 'Last Hours', 'This Hours',
'This 30 Minutes', 'Last 30 Minutes', 'This 15 Minutes', 'Last 15 Minutes', 'This 10 Minutes', 'Last 10 Minutes'];
send in backend using date Object using javascript,angular js
You most likey want the start date:
StatIndex:2016-01-01T00:00:00+5:30
This can be converted to a Date object quite easily using the Date constructor. For example:
var StatIndex = '2016-01-01T00:00:00+5:30';
const date = Date(StatIndex);
const toSend = {date:date};
const json = JSON.stringify(toSend);
As #Hassan Tariq mentioned in the comments, you need to write your own methods for it. To help you with there is a good library to play with dates moment.js

Learning JavaScript: Is there a way to change the image file of a group of images without using individual ids?

Trying to teach myself JavaScript with a Tarot card program I plan on building on as I learn.
Right now I am trying to figure out how to change the image of a card from back to face when a user clicks on it, and I'm trying to do it all in JavaScript.
So far I've figured out how to change the img src with the card idea, but it only changes the first one. Is there a way to do this without having to write a separate function for each card? Or without using unique ids?
I've been researching for hours. I'm stuck.
<p align="center">
<img id="card" onclick="someFunc()" src="img-tarot-card-back-001.jpg">
<img id="card" onclick="someFunc()" src="img-tarot-card-back-001.jpg">
<img id="card" onclick="someFunc()" src="img-tarot-card-back-001.jpg">
<img id="card" onclick="someFunc()" src="img-tarot-card-back-001.jpg">
<img id="card" onclick="someFunc()" src="img-tarot-card-back-001.jpg">
</p>
<script>
function someFunc() {
document.getElementById('card').src="img-tarot-card-front-001.jpg";
}
</script>
In terms of how to do it with your existing code, pass a reference to the image into your function within the HTML:
<img onclick="someFunc(this)" src="img-tarot-card-back-001.jpg">
^^^^
"this" references the current image element
Note: I removed your id attribute, as IDs must be unique within a document.
Then update your function to use that instance:
function someFunc(card) {
card.src="img-tarot-card-front-001.jpg";
} // Fixed this ending brace too
However, since you're just learning, you should start off on the right path. Try not to put Javascript in your HTML, it's bad practice. You should bind to those elements within your Javascript alone, for example:
document.querySelector("img") // Grab all <img> elements
.addEventListener("click", function(e) { // Listen for a "click" event
var clickedImage = e.target; // The clicked image will be stored in the target
clickedImage.src = "img-tarot-card-front-001.jpg"
});
Now your HTML is clean and Javascript-free:
<img src="img-tarot-card-back-001.jpg">
I used querySelector and addEventListener here which are not supported on all browsers and are difficult concepts when just learning Javascript. However they are very important and if you can learn them now you'll set yourself up well for the future.
Here is a quick snippet, might be a good jump start for peoples passing by.
You have to choose between 78 cards. The deck can be shuffled without limit. A card when chosen is discarded from the deck. When 5 cards had been selected, they get revealed all together.
The cards, when selected, are pulled from this repository:
https://github.com/mcnuttandrew/tarot-deck
let cards = [
'00 The fool.svg',
'01 The magician.svg',
'02 The high priestess.svg',
'03 The empress.svg',
'04 The emperor.svg',
'05 Hierophant.svg',
'06 The lovers.svg',
'07 The chariot.svg',
'08 Strength.svg',
'09 The hermit.svg',
'10 Coins.svg',
'10 Cups.svg',
'10 Swords.svg',
'10 Wands.svg',
'10 Wheel of fortune.svg',
'11 Justice.svg',
'12 The hanged man.svg',
'13 Death.svg',
'14 Temperance.svg',
'15 The Devil.svg',
'16 The Tower.svg',
'17 The star.svg',
'18 The moon.svg',
'19 The sun.svg',
'20 Judgement.svg',
'21 The world.svg',
'2 Coins.svg',
'2 Cups.svg',
'2 Swords.svg',
'2 Wands.svg',
'3 Coins.svg',
'3 Cups.svg',
'3 Swords.svg',
'3 Wands.svg',
'4 Coins.svg',
'4 Cups.svg',
'4 Swords.svg',
'4 Wands.svg',
'5 Coins.svg',
'5 Cups.svg',
'5 Swords.svg',
'5 Wands.svg',
'6 Coins.svg',
'6 Cups.svg',
'6 Swords.svg',
'6 Wands.svg',
'7 Coins.svg',
'7 Cups.svg',
'7 Swords.svg',
'7 Wands.svg',
'8 Coins.svg',
'8 Cups.svg',
'8 Swords.svg',
'8 Wands.svg',
'9 Coins.svg',
'9 Cups.svg',
'9 Swords.svg',
'9 Wands.svg',
'Ace Coins.svg',
'Ace Cups.svg',
'Ace Swords.svg',
'Ace Wands.svg',
'King Coins.svg',
'King Cups.svg',
'King Swords.svg',
'King Wands.svg',
'Knight Coins.svg',
'Knight Cups.svg',
'Knight Swords.svg',
'Knight Wands.svg',
'Princess Coins.svg',
'Princess Cups.svg',
'Princess Swords.svg',
'Princess Wands.svg',
'Queen Coins.svg',
'Queen Cups.svg',
'Queen Swords.svg',
'Queen Wands.svg'
];
let hats = [], hhh = 1;
cards.forEach((e) => {
hats.push({content: `<h${hhh}><span data-card="${e}" class="back"></span></h${hhh}>`});
(hhh >= 6) ? hhh = 1 : hhh++
})
let timer;
function loop5(){
let i = 0
clearInterval(timer)
timer = setInterval(function(){
shuffle()
if (i >= 20){
clearInterval(timer)
}
i++
}, 200)
}
loop5()
function shuffle(){
hats.sort(() => Math.random() - 0.5)
out.innerHTML = hats.map(e => e.content).join("")
}
let count = 0;
out.addEventListener("click", (e) => {
if (e.target.dataset.card && count < 5){
cards.splice(e.target.dataset.card, 1);
user.innerHTML += `<img class="blur" src="https://raw.githubusercontent.com/mcnuttandrew/tarot-deck/9e885d3608454a03f275c2c3375e9e9f45788b22/svgs/${e.target.dataset.card}">`
e.target.outerHTML = ""
document.querySelectorAll(".user > span")[count++].className = ""
k(3,233,100); k(1,603,200);
}
if (count === 5){
document.querySelectorAll("#user > img").forEach((e) => {
e.className = ""
})
k(10,1233,100); k(3,1603,500);
count++;
}
})
// gain, frequency, duration
let a = new AudioContext()
function k(w,x,y){
//console.log("Gain:"+w, "Hz:"+x, "ms:"+y)
v = a.createOscillator()
u = a.createGain()
v.connect(u)
v.frequency.value = x
v.type = "square"
u.connect(a.destination)
u.gain.value = w * 0.01
v.start(a.currentTime)
v.stop(a.currentTime + y *0.001)
}
body {background: midnightblue; color: antiquewhite;}
div, span {display: flex }
.user > span { max-width: 18rem; padding: 0 0 0 0.5rem; }
button {cursor: pointer }
.back {display: table-cell; background: black; height: 2.4em; width: 2.6em; border-radius: 0.2em; border: 2px blue solid}
.back:hover {filter: invert(0.2); cursor: pointer}
.out {display: flex;justify-content: center;flex-direction: row;}
.user { display: grid;
height: 100px;
grid-template-columns: 1fr 1fr 1fr 1fr 1fr;padding: 0 0rem 0 2rem;}
.card {height: 2.4em; width: 2.6em; }
img {width: 16vw }
.blur {filter: blur(10px);}
<button onclick="loop5()">Shuffle cards</button> <b>Choose 5 cards</b>
<div id="out"></div>
<div class="user">
<span class="">What is happening at the moment?</span>
<span class="blur">How can I weather it easily and with grace?</span>
<span class="blur">What is the lesson?</span>
<span class="blur">What is leaving at this time?</span>
<span class="blur">What is arriving at this time?</span>
</div>
<div id="user" class="user"></div>
Hint: Go full page, ask a question, and do not use it too much each days. Warmly.

Categories

Resources