I searched on the internet for a sort algorithm which sorts the entries of a table in a "natural" way so 10 is after 1 and so on but I found not one solution which is "the perfect fit".
Now I am working on my own solution to do a sort algorithm. My question is now if it is efficient and applicable to create a number for each string in a table row based on the position of their letters in the abc and the position of this letter in the specific string and then sort by this created number?
Example:
abc would be a = 1; b = 2; c= 3 and then the "weight" for each letter should be higher with the string length:
a = 1 * 1(pos in str); b = 2 * 2; c = 3 * 3
so abc would be 14 as a number.
I don't want this to be a real natural sort.
I have used libraries and the built in Javascript function ".sort()" but they are not working for strings like 92593c17-5183-4db1-b4bd-d538abb4124bor ed06d686-8a04-4ae1-9500-975fb85a49d9 so it is not the right thing for me.
So is it a good way to sort strings by their letter-"weight"?
Have a look at this little example with localeCompate():
var s1 = '92593c17-5183-4db1-b4bd-d538abb4124';
var s2 = 'ed06d686-8a04-4ae1-9500-975fb85a49d9';
var s3 = '10';
var s4 = '1';
var s5 = 'a';
var s6 = 4;
$('#1').text(s1 + ' before ' + s2 + ': ' + (s1.toString().localeCompare(s2.toString()) == -1 ? 'yes' : 'no'));
$('#2').text(s2 + ' before ' + s3 + ': ' + (s2.toString().localeCompare(s3.toString()) == -1 ? 'yes' : 'no'));
$('#3').text(s3 + ' before ' + s4 + ': ' + (s3.toString().localeCompare(s4.toString()) == -1 ? 'yes' : 'no'));
$('#4').text(s4 + ' before ' + s5 + ': ' + (s4.toString().localeCompare(s5.toString()) == -1 ? 'yes' : 'no'));
$('#5').text(s5 + ' before ' + s6 + ': ' + (s5.toString().localeCompare(s6.toString()) == -1 ? 'yes' : 'no'));
$('#6').text(s6 + ' before ' + s1 + ': ' + (s6.toString().localeCompare(s1.toString()) == -1 ? 'yes' : 'no'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='1'></p>
<p id='2'></p>
<p id='3'></p>
<p id='4'></p>
<p id='5'></p>
<p id='6'></p>
Related
I am trying to create a calendar in JavaScript and I am trying to disable the previous day from today.
for (var c = 0; c < 42 - r; c++) {
var v = e[c].day;
var m = g(new Date(t, n - 1, v))
? `<div id="${v}/${n}/${t}" class="today" type="button" onclick="addRow(this)">`
: z(new Date(t, n - 1, v))
? `<div class="past">`
: `<div id="${v}/${n}/${t}" type="button" onclick="addRow(this)">`;
l.append(
m +
"" +
'<span class="month">' +
i[n - 1] +
"</span>" +
"" +
v +
"</div>"
);
}
So here v is a day, n is a month and t is a year. And here is g and z functions:
function g(e) {
return y(new Date()) == y(e);
}
function z(e) {
return y(new Date()) > y(e);
}
function y(e) {
return e.getFullYear() + "/" + (e.getMonth() + 1) + "/" + e.getDate();
}
So I am expection to have previous dates like this: <div class="past">, today is like this: <div id="${v}/${n}/${t}" class="today" type="button" onclick="addRow(this)"> and future is like this: <div id="${v}/${n}/${t}" type="button" onclick="addRow(this)">
But what I am having is <div class="past">, <div id="${v}/${n}/${t}" class="today" type="button" onclick="addRow(this)">, <div class="past">
So where do you think I am making things wrong?
The problem is that "2021/8/9" is greater than "2021/8/10" when you do string comparison (9 is greater than 1). You need those month/day values properly zero padded (2021/08/09) vs (2021/08/10).
Try
function y(e) {
return e.getFullYear()
+ "/" + String(e.getMonth() + 1).padStart(2, "0")
+ "/" + String(e.getDate()).padStart(2, "0");
}
I have a javascript, which I supposed to format phone number to +1 (222) 555 22-22, but for some reason it stops to work just on first number.. Can you elaborate what's I'm doing wrong?
document.getElementById('phone').addEventListener('input', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,1})(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[3] ? x[1] : '+' + x[1] + '(' + x[2] + ') ' + x[3] + (x[4] ? '-' + x[4] : '');
});
<input type="text" id="phone" placeholder="+1 (222) 444-5555"/>
I'm trying to write phone input masking function. Here it is:
let input = document.querySelector('input');
input.addEventListener('input', ()=>{
let x = event.target.value.replace(/\D/g, '').match(/(\d{0,1})(\d{0,3})(\d{0,3})(\d{0,2})(\d{0,2})/);
event.target.value = !x[2] ? x[1] : '+' + x[1] + ' (' + x[2] + ') ' + x[3] + (x[4] ? '-' + x[4] : '') + (x[5] ? '-' + x[5] : '');
})
<input />
It works, but with one problem. When I press the backspace key, I erase the phone number to something like +1 (111). Such an entry is valid for the regular expression, and the string is replaced by itself
Per #ggorlen's suggestion in the comments, here is one way to do this:
let input = document.querySelector('input');
input.addEventListener('keydown', (event)=>{
if (event.key === "Backspace" || event.key === "Delete") return;
let x = event.target.value.replace(/\D/g, '').match(/(\d{0,1})(\d{0,3})(\d{0,3})(\d{0,2})(\d{0,2})/);
event.target.value = !x[2] ? x[1] : '+' + x[1] + ' (' + x[2] + ') ' + x[3] + (x[4] ? '-' + x[4] : '') + (x[5] ? '-' + x[5] : '');
})
<input maxlength=18 />
str1 = booking_kode.substring(0, 3);
B = ["800", "807", "826", "847", "866"];
C = ["827", "846"];
E = ["867", "879"];
F = ["880", "899"];
if (str1 = array B){
print ('Prefix , first 3 digit = ' + str1 + '\n')
comm_code = 'B000'
print ('Comm_Code = ' + comm_code + '\n')
}
else if (str1 = array C) {
print ('Prefix , first 3 digit = ' + str1 + '\n')
comm_code = 'C000'
print ('Comm_Code = ' + comm_code + '\n')
}
else if (str1 = array E) {
print ('Prefix , first 3 digit = ' + str1 + '\n')
comm_code = 'E000'
print ('Comm_Code = ' + comm_code + '\n')
}
else if (str1 = array F) {
print ('Prefix , first 3 digit = ' + str1 + '\n')
comm_code = 'F000'
print ('Comm_Code = ' + comm_code + '\n')
}
else {
print ('Prefix , Nilai 3 digit pertama = ' + str1 + '\n')
comm_code = 'D000'
print ('Comm_Code = ' + comm_code + '\n')
}
Hello,
I want to know how to match the string Str1 with the value of the Array B,C,E,F.
I mean :
If Str1 = 800|| 807 || 826 || 847 || 866, Then Comm_code = B000
If Str1 = 827 || 846 then Comm_code = C000
If Str1 = 867 || 879 then Comm_code = E000
If Str1 = 880 || 899 then Comm_code = F000
Else Default --> Comm_code = D000
Please kindly advice.
p.s. : Fyi, I'm using EcmaScript 2015 / ES5.
Just use a simple String.prototype.indexOf:
str1 = booking_kode.substring(0, 3);
B = ["800", "807", "826", "847", "866"];
C = ["827", "846"];
E = ["867", "879"];
F = ["880", "899"];
if (B.indexOf(str1) > -1)
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'B000';
print ('Comm_Code = ' + comm_code + '\n');
}
else if (C.indexOf(str1) > -1)
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'C000';
print ('Comm_Code = ' + comm_code + '\n');
}
else if (E.indexOf(str1) > -1)
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'E000';
print ('Comm_Code = ' + comm_code + '\n');
}
else if (F.indexOf(str1) > -1)
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'F000';
print ('Comm_Code = ' + comm_code + '\n');
}
else
{
print ('Prefix , Nilai 3 digit pertama = ' + str1 + '\n');
comm_code = 'D000';
print ('Comm_Code = ' + comm_code + '\n');
}
You can achieve this with simple if else conditions using Array.indexOf() Methods. However make sure the str1 and the values in the array are of same variable type(string or a number).
if (B.indexOf(str1) > -1 ) { //if value exists in B
//do soemthing;
}
else if(C.indexof(str1) >-1 ) { //if value exists in C
//do soemthing
}
One possible solution to solve this is use Array.some() (I think it is included on ES5 based on this link). First you can create a method that will check if an element is on an array:
function arrayIncludes(arr, ele)
{
return arr.some(function(x) {return (x === ele);});
}
console.log(arrayIncludes([1,2], 2));
console.log(arrayIncludes([1,2], 5));
.as-console {background-color:black !important; color:lime;}
Then, your code can be reworked to this:
str1 = booking_kode.substring(0, 3);
B = ["800", "807", "826", "847", "866"];
C = ["827", "846"];
E = ["867", "879"];
F = ["880", "899"];
function arrayIncludes(arr, ele)
{
return arr.some(function(x) {return (x === ele);});
}
if (arrayIncludes(B, str1))
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'B000';
print ('Comm_Code = ' + comm_code + '\n');
}
else if (arrayIncludes(C, str1))
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'C000';
print ('Comm_Code = ' + comm_code + '\n');
}
else if (arrayIncludes(E, str1))
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'E000';
print ('Comm_Code = ' + comm_code + '\n');
}
else if (arrayIncludes(F, str1))
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'F000';
print ('Comm_Code = ' + comm_code + '\n');
}
else
{
print ('Prefix , Nilai 3 digit pertama = ' + str1 + '\n');
comm_code = 'D000';
print ('Comm_Code = ' + comm_code + '\n');
}
I have my own webshop and on the home page i have a lot of products with countdown.
So whats the problem?
The problem is, when i have many javascripts on home page then the broser will freezing, getting slow.
How i know this is an javascript problem ? I tried to disable javascript on the browser and my website works normal.
/*!
*
* Brian2000: BK_Countdown v1.1
* AKA: Brian's jQuery Robust Date/Time Countdown
* http://brian2000.com
*
* Copyright 2012-2013, Brian Kennedy
* Licensed under the GPL Version 3 license
* http://www.gnu.org/licenses/gpl-3.0.en.html
*
* Date: Wed Jan 9 2013 2:54PM EST
*
* You can't remove this part, and if you make changes or improve things, please keep me informed.
* Thank you, enjoy, and support Open Source!
*/
/*
This portion explains how to use the counter, I recomend not deleting it either ;-)
VARS [required]
------------------------------------------------
container: ID of Element for counter
targetDate: MM/DD/YYYY
targetTime: HH:MM:SS (0-23 Hour) [seconds are optional]
OPTIONS:
------------------------------------------------
order: format/output order
order: 1 = Label + Spacer + Value
order: 2 = Value + Spacer + Label (reverse from order 1)
spacer: text/string seperator between label and value
element: html element for label and value containers (default is span)
end: Message to display when date has passed
dayOf: Message to display on day of counter expiration
*/
function BK_CountDown(container, targetDate, targetTime, opts) {
/////////////////////////////////////////////////////
//vars
this.opts = opts;
this.complete = false; //for exiting interval
this.container = container; //target
DArray = targetDate.split('/');
this.targetDate = DArray[0] + '/' + DArray[1] + '/' + DArray[2];
TArray = targetTime.split(':');
this.targetHour = TArray[0]; //hr
this.targetMin = TArray[1]; //min
if (typeof TArray[2] == 'undefined') { //sec
this.targetSec = 0;
}else{
this.targetSec = TArray[2];
}
/////////////////////////////////////////////////////
// options
var defaults = {
'order' : "1",
'spacer' : ':',
'element' : 'span',
'end' : "Deal is ended!",
'dayOf' : "Deal is ended!"
}
if(typeof this.opts != "undefined") { //if options were assigned...
for(var i in defaults) { //assign defaults for unchanged opts
if(typeof this.opts[i] == "undefined") {
this.opts[i] = defaults[i];
}
}
}else{ //no options were assigned
this.opts = defaults;
}
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//////// assembly
/////////////////////////////////////////////////////
s = this.opts['spacer'];
this.c = container.substring(1);
e = this.opts['element'];
if(this.opts['order'] == 2){
//reverse assembly
$(container).append('<' + e + ' id="' + this.c + '_count_days" class="count_days"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_days" class="txt_days">' + s + ' Days</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_hours" class="count_hours"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_hours" class="txt_hours">' + s + ' :</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_min" class="count_min"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_min" class="txt_min">' + s + ' :</' + e + '>');
}
else{
//default assembly
$(container).append('<' + e + ' id="' + this.c + '_txt_days" class="txt_days">Days ' + s + '</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_days" class="count_days"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_hours" class="txt_hours">Hours ' + s + '</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_hours" class="count_hours"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_min" class="txt_min">Minutes ' + s + '</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_min" class="count_min"></' + e + '>');
}
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//////// Count Update function
this.count_update = function count_update(){
date = new Date(); //NOW
targetDate = new Date(this.targetDate);
targetDate.setHours(this.targetHour);
targetDate.setMinutes(this.targetMin);
targetDate.setSeconds(this.targetSec);
var UDate = Math.round(date.getTime()/1000);
var UTargetDate = Math.round(targetDate.getTime()/1000);
differance = UTargetDate - UDate;
days=Math.floor(differance/(60*60*24)*1);
hours=Math.floor((differance%(60*60*24))/(60*60)*1);
minutes=Math.floor(((differance%(60*60*24))%(60*60))/(60)*1);
seconds=Math.floor((((differance%(60*60*24))%(60*60))%(60))*1);
//if range is 0 don't display range
//days
if(days <= 0){$(this.container + '_count_days').remove();$(this.container + '_txt_days').remove();}
else{$(this.container + '_count_days').text(days);}
//hours
if(days <= 0 && hours <= 0){$(this.container + '_count_hours').remove();$(this.container + '_txt_hours').remove();}
else{$(this.container + '_count_hours').text(hours);}
//min
if(days <= 0 && hours <= 0 && minutes <= 0){$(this.container + '_count_min').remove();$(this.container + '_txt_min').remove();}
else{$(this.container + '_count_min').text(+minutes);}
//seconds
$(this.container + '_count_sec').text(seconds);
//Singular text for 'reverse' assembly
if(this.opts['order'] == 2){
if(days <= 1){$(this.container + '_txt_days').text(this.opts['spacer'] + ' dag en ');}
else{$(this.container + '_txt_days').text(this.opts['spacer'] + ' dagen en ')}
if(hours == 1){$(this.container + '_txt_hours').text(this.opts['spacer'] + ' uur en ');}
else{$(this.container + '_txt_hours').text(this.opts['spacer'] + ' uur en ');}
if(minutes == 1){$(this.container + '_txt_min').text(this.opts['spacer'] + ' min');}
else{$(this.container + '_txt_min').text(this.opts['spacer'] + ' min');}
if(seconds == 1){$(this.container + '_txt_sec').text(this.opts['spacer'] + '');}
else{$(this.container + '_txt_sec').text(this.opts['spacer'] + '');}
}
//end of countdown
if(days <= 0 && hours <= 0 && minutes <= 0 && seconds <= 0){
//timer is over, final output
//if date is today!
if(new Date().toDateString() == targetDate.toDateString()){
$(this.container).addClass('count_now');
$(this.container).text(this.opts['dayOf']);
}else{//if date is after today
$(this.container).addClass('count_end');
$(this.container).text(this.opts['end']);
}
this.complete = true;
}
};
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//run immediately
this.count_update();
//now loop this every second
var selfobject = this; //scope gets lost within setInterval (see: http://www.vonloesch.de/node/32)
var theCounter = setInterval(function(){
selfobject.count_update();
if(selfobject.complete == true){
clearInterval(theCounter);}
}, 1000);
}
HTML:
$(document).ready(function() {
var aanbiedingcountdown = new BK_CountDown('#deal1', '05/25/2014', '23:57', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal2', '05/26/2014', '23:57', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal3', '05/28/2014', '23:57', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal4', '05/28/2014', '15:10', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal5', '05/26/2014', '23:57', {order: 2, spacer: ''});
});
You see, for every countdown that i want i need to create an ID.
But what i want is that when the page load, the countdown dont need to run, it makes my website slower. So, only when the someone refresh the page then he get the right date & time.
Example: Time is now 16:00u, the countdown are set at 17h, so, when someone is still on my website (10min) without refreshing the page then the countdown is still 16h only if he refresh the page then countdown is 16:10h...
I've seen this on other websites and they have more than 100 products with countdowns on the same page and still works perfect because timer is not running only if people refresh the page the the timer will set to right date & time.
Demo: http://jsfiddle.net/uJk73/ (i removed seconds, i though site will go faster without this, but no succes)
Hope someone can help my with this.
Updated jsfiddle
So let's say you had 9 deals
<div id="countdowntimer">
<div id="deal1"></div>
<div id="deal2"></div>
<div id="deal3"></div>
<div id="deal4"></div>
<div id="deal5"></div>
<div id="deal6"></div>
<div id="deal7"></div>
<div id="deal8"></div>
<div id="deal9"></div>
</div>
Get rid of this loop in BK_CountDown()
//now loop this every second
/*var selfobject = this; //scope gets lost within setInterval (see: http://www.vonloesch.de/node/32)
var theCounter = setInterval(function(){
selfobject.count_update();
if(selfobject.complete == true){
clearInterval(theCounter);}
}, 1000);
*/
Then
$(document).ready(function() {
var deals = []; // create an array
deals.push( new BK_CountDown('#deal1', '05/24/2014', '23:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal2', '05/24/2014', '22:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal3', '05/24/2014', '12:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal4', '05/24/2014', '13:49', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal5', '05/24/2014', '14:49', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal6', '05/24/2014', '15:57', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal7', '05/24/2014', '15:58', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal8', '05/24/2014', '15:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal9', '05/24/2014', '16:00', {order: 2, spacer: ''}) );
var dealcounter = setInterval(function(){ // create one setTimeout
if (deals.length){
for (i in deals){
var selfobject = deals[i];
selfobject.count_update();
if(selfobject.complete == true) delete deals[i]; // remove from array
}
}else{
clearTimeout(dealcounter); // no more to count down, stop this loop
}
}, 5000); // 5 seconds
});