Print 42 characters on each line from string - javascript

Problem: I'm using qzTray to print a receipt, earlier i was using html format but the print quality was not good. so i shifted to JavaScript and wrote bunch of functions to print the receipt, i am using this function to print 42 character on each line, i have a string of 105 characters, the string will be printed in 3 lines. I've written some code but its not working entirely, can anyone give me a hint how to do this ?
first line is printed fine but from second line and onward the substr looks like its not working, i don't know why.
Thanks is advance.
window.const_alignLeft = '\x1B\x61\x30';
window.const_newLine = '\x0A';
function getItemRowFull(itemTitle, itemPrice = null) {
var totalColsPerPage = 42;
var leftCols = 35;
var marginSpace = totalColsPerPage === 48 ? '' : ' ';
if(itemTitle.length > leftCols) {
leftCols = (!itemPrice) ? totalColsPerPage : leftCols;
let itemTitleLength = itemTitle.length;
let receipt = '';
let startFrom = 0;
let remainingCharacters = itemTitle.length;
while (startFrom < itemTitleLength) {
receipt += const_alignLeft + marginSpace + itemTitle.substr(startFrom, startFrom + leftCols);
receipt += const_newLine;
remainingCharacters = (remainingCharacters + itemTitleLength) - (itemTitleLength + leftCols);
startFrom = (startFrom + leftCols);
}
return receipt;
}
}
Image In the image below the function will be used to paragraph related to notes.

Related

Not properly referencing cells

I am coding a phone number formatter for a large database. Everything is working, but there is an inconsistent printing of blank cells. Most of the cells are read through and are properly formatted, but there are some that show blank outputs in the wrong cells.
I have tried fixing this by resetting the cleanNumber variable to a blank string but this just posed another issue on line 33 with indexOf().
function myFunction() {
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); // connects sheet to code
var startRow = 18;
var endRow = 41;
for (var i = startRow; i <= endRow; i++) { // i = currnet row | row to end at | add 1 to count each time
var workingCell = activeSheet.getRange(i, 2).getValue();
Logger.log("Original number: " + workingCell)
//If blank, move to next row
exit: if (workingCell.length == 0.0) {
var blank = "";
activeSheet.getRange(i, 3).setValue(blank);
Logger.log("This row is blank")
//break exit;
}
// cleanNumber if it isn't formatted already
else if (isNaN(workingCell)) { // runs if active cell is not a preformatted number
var cleanNumber = workingCell.replace(/\D/g, ''); // removes all non-numeric values
activeSheet.getRange(i, 3).setValue(cleanNumber);
Logger.log("Extra char's removed: " + cleanNumber)
}
// runs if active cell is already preformatted
else {
activeSheet.getRange(i, 3).setValue(workingCell);
Logger.log("No need for formatting: " + workingCell)
}
// If cleanNumber has a country code(+1), remove it
if ((cleanNumber.indexOf("1")) == 0) {
cleanNumber = cleanNumber.substring(1); //removes first character = "1"
activeSheet.getRange(i, 3).setValue(cleanNumber);
Logger.log("Country code removed: " + cleanNumber);
}
// If number is longer than 10 characters, create an extension variable - with entire number, remove 10 characters from front
if (cleanNumber.length > 10.0) {
var extension = cleanNumber.substring(10, 15);
var phoneNumber = cleanNumber.substring(0, 10);
var formatted = phoneNumber.slice(0, 3) + "-" + phoneNumber.slice(3, 6) + "-" + phoneNumber.slice(6, 15);
var finalPhoneNumber = formatted + " ext. " + extension;
activeSheet.getRange(i, 3).setValue(finalPhoneNumber);
Logger.log("This number is in its final ext. format: " + finalPhoneNumber);
}
//if number doesnt have an extension, put it into final format
else if (cleanNumber.length = 10.0) {
var frontFinal = cleanNumber.substring(0, 3);
var midFinal = cleanNumber.substring(3, 6);
var endFinal = cleanNumber.substring(6, 10);
var finalNumber = frontFinal + "-" + midFinal + "-" + endFinal;
activeSheet.getRange(i, 3).setValue(finalNumber);
Logger.log("This number is in its final format: " + finalNumber);
}
//if number is less than 10 numbers
else {
Logger.log("This number is shorter than 10 numbers" + cleanNumber);
}
cleanNumber = " ";
}
}
The pre-formatted numbers are on the left and the output is in the right column.
Here is some sample data, please consider that the issue seems to be stemming from blank rows.
Unformatted
1999-111-1111
1+2222-222222
4444444444 ext. 223
9738094395
9172609107
866.786.6682
973 330 2212
(631)563-4000 ext. 234
I look forward to solving this issue, thank you for the help :)
You can do it with ARRAYFORMULA or you may use the RegExp in your script.
=ArrayFormula(REGEXREPLACE(REGEXREPLACE(REGEXREPLACE(TO_TEXT(A2:A),"\D",),"^(?:1)?(\d{3})(\d{3})(\d{4})(\d{0,5}).*$","$1-$2-$3 ext. $4")," ext\. $",))
You are recommended to use batch operations
const values = [
['1999-111-1111'],
['1+2222-222222'],
['4444444444 ext. 223'],
[9738094395],
[9172609107],
['866.786.6682'],
['973 330 2212'],
['(631)563-4000 ext. 234'],
['973-809-4395'],
['']
];
const results = [];
for (const value of values) {
const cleanNumber = value[0].toString().replace(/\D/g, '');
const m = cleanNumber.match(/^(?:1)?(\d{3})(\d{3})(\d{4})(\d{0,5}).*$/);
if (m) {
let finalNumber = `${m[1]}-${m[2]}-${m[3]}`;
if (m[4]) { finalNumber += ` ext. ${m[4]}`; }
results.push([finalNumber]);
}
else {
results.push(value);
}
}
console.log(results.flat());

How can I get my result logged horizontally rather than vertically?

Hello you beautiful coders!
Today I've been working on a little quiz called "Chessboard" but ran into a weird situation.
but my code is spitting out results vertically but I need to make it horizontally so that I can repeat this process a few more times to make a board out of it. Here's my code:
let value = 8;
for (i = 1; i <= value ; i++) {
if ( i % 2 == 0 ) {
let x = i;
console.log(x);
} else {
let y = " ";
console.log(y);
}
}
this above code outputs
2
4
6
8
How can I make these results show horizontally like so:
2 4 6 8
So that I can repeat this process in a new line afterward?
I've been thinking about this for awhile but.... I might just be too dumb to figure this out?
I THINK I have to nest this if function again in this function to achieve this but not sure how...
Thanks in advance!!
Add an empty string at the beginning of the code, append the results to it, and log it to console, as illustrated below:
var res = "";
let value = 8;
for (i = 1; i <= value ; i++) {
if ( i % 2 == 0 ) {
let x = i;
res += x + ' ';
} else {
let y = " ";
res += y;
}
}
console.log(res);
A console.log will always show on a new line in the console. I would add each result to an array and then convert the array into a string. Then console log it once.
let value = 8;
// create empty array
const results = [];
for (let i = 1; i <= value; i++) {
if ( i % 2 == 0 ) {
let x = i;
// rather than console logging, add to empty array
results.push(x);
} else {
let y = " ";
results.push(y);
}
}
// convert array to string, seperated by spaces
const str = results.join(" ");
console.log(str)

JavaScript - How would i add var into an array with prompts and get the average with a button

This is my code. I know that it is wrong but I need some help to start a prompt list. My goal is to get 4 marks with a button then you input and have it in an array. It then gets averaged and that gets shown with an alert.
<html>
<head>
<title>Quiz</title>
</head>
<body>
Average your marks
<button onclick="myFunction()">Start</button>
<script type="text/javascrypt">
var student = []
var student[0] = prompt("Name:");
var student[1] = prompt("mark=");
var student[2] = prompt("mark=");
var student[3] = prompt("mark=");
var student[4] = prompt("mark=");
var student[5] = student[1] + student[2] + student[3] + student[4] / 4;
function myFunction() {
if (confirm(student) == true)
}
</script>
</body>
</html>
i actually think you are almost there:
change every avArray to student. and the first time to var student = []
edit:
also write function instead of fuction
edit 2
finally: because you use var you define a variable. so only use var with var student = []
var student[0] is wrong because student is already defined. so use student[0] =
Because prompt always returns a string you want to use Number to make it a number that you can calculate with.
So your final code would look something like this:
var name = prompt("Name:");
var grades = [];
grades[0] = Number(prompt("mark="));
grades[1] = Number(prompt("mark="));
grades[2] = Number(prompt("mark="));
grades[3] = Number(prompt("mark="));
var average = (grades[0] + grades[1] + grades[2] + grades[3]) / 4;
function myFunction() {
confirm(name + ": " + average)
}
Average your marks:
<button onclick="myFunction()">Start</button>
You want to make sure that you are adding int values, not String values - which are the return result of prompt.
Try this:
// Forces the user to input an int by retrying until an int is input
function intPrompt(msg) {
while (true) {
var num = parseInt(prompt(msg));
if (!isNaN(num)) return num;
}
}
Now here's the code that will read 4 marks from the user and average them:
alert((intPrompt('mark 1') + intPrompt('mark 2') + intPrompt('mark 3') + intPrompt('mark 4')) / 4);
Quite a few errors, here are some I've spotted so far:
<script type="text/javascrypt">
Spell javascript correctly
var student[0] = prompt("Name:");
You use var only when defining the student the first time, remove it from the next appearances of student.
if (confirm(student) == true)
Student is an array, not a string. You will need to convert it to a string in some way to use it for confirm AFAIK.
var student[5] = student[1] + student[2] + student[3] + student[4] / 4;
I just tested this line out, and averaging doesn't work correctly, you need to prevent concatenation, maybe proper brackets.
Calculation of average is not the perfect one and you try to put everything into array, even if it does not belong there.
Check the example: http://codepen.io/anon/pen/rWxMEP
<html>
<head>
<title>Quiz</title>
<body>
Average your marks<button onclick=myFunction()>Start</button>
<script type="text/javascrypt">
let name;
let studentMarks = [];
const numOfMarks = 4;
let sumMark = 0;
let msg;
let myFunction = function() {
name = prompt("Name");
if (name.length !== 0){
for(i = 0; i < numOfMarks; i++){
msg = "Enter mark (" + parseInt(parseInt(numOfMarks)-parseInt(i) )+" left)";
studentMarks[i] = prompt(msg);
sumMark += parseFloat(studentMarks[i]);
}
alert(name + "'s average mark is "+ sumMark/numOfMarks);
}
}
</script>
</body>
</html>

Displaying current & total page number N(N)

I am new to Javascript,so forgive my silly mistakes in advance.
I have a requirement where I have to print current and total page number excluding even pages which are blank.
Example : For 5 page long document,it should display like:
1(3)
2(3)
3(3)
Any sort of info is welcome since I am in dire need of this code to work.
I have tried this but it doesn't work:
var current_page=0 ;
var total_pages=0;
if((current_page<total_pages)||(current_page=total_pages))
{
current_page++;
if(current_page % 2!==0)
{
total_pages++;
}
}
Also, this one too doesn't worked :(
var temp = (this.pageNum) + "(" + (this.numPages) + ")" ;
You have a logical error here:
current_page = total_pages // Note single = symbol between.
You are assigning instead of comparing. Please use == to compare:
current_page == total_pages
Or === for strict comparison as the type of both the variables is same.
Does that help?
function (totalPages, currentPage)
{
if (currentPage%2==1) return "";
var tp = parseInt(totalPages/2+1);
var cp = parseInt(currentPage/2+1);
return "" + cp + "(" + tp + ")";
}

JavaScript loops to store data in an array

I have a friend who has an assignment on arrays and because I lack experience in Javascript and she just needs some real quick help understanding how to implement a Javascript loop to store data in an array which converts a letter grade to a number. Can someone just guide her in a general direction?
https://docs.google.com/fileview?id=16uNNiooLalkm1QlszrqEPr2qqMGLjhrtQx7qCLw-7d2ftygre8GM6hyceJHj&hl=en\
Update: She states that she doesn't understand how to make it prompt again after the first time while storing data. Can someone just write a translation for a C++ code for do {}?
Here's a more or less complete solution - but it doesn't output the results to the HTML page but outputs it with the alert boxes.
var done = false,
classes = [],
total_credits = 0,
avg = 0;
while(!done){
var class_name = prompt("Enter class name"),
letter_grade = prompt("Enter letter grade for "+class_name),
credit_hours = prompt("Enter credit hours for "+class_name),
number_grade = {"A":4,"B":3,"C":2,"D":1,"F":0}[letter_grade];
if(class_name && letter_grade && credit_hours){
classes.push({
class_name: class_name,
letter_grade: letter_grade,
number_grade: number_grade,
credit_hours: credit_hours
});
total_credits += parseInt(credit_hours,10);
avg += number_grade*credit_hours;
}else
done = true;
}
avg = avg/total_credits;
for(var i=0; i<classes.length; i++){
alert(classes[i].class_name + " | " +
classes[i].letter_grade + " | " +
classes[i].credit_hours);
}
alert("Total credits: " + total_credits);
alert("GPA: " + avg.toFixed(2));
Basically, she should use a while loop.
in (mostly) pseudocode:
more_entries = true;
while(more_entries)
{
response = prompt("Question for the user","");
if (response == null)
{
more_entries = false;
}
else
{
// store value somewhere
}
}
Of course, this needs to be expanded to multiple prompts.

Categories

Resources