Skip to content

Commit

Permalink
Clean up a lot of !-- undefined and !== ''
Browse files Browse the repository at this point in the history
  • Loading branch information
limefrogyank committed Nov 17, 2024
1 parent ca5a2e6 commit b052505
Show file tree
Hide file tree
Showing 11 changed files with 49 additions and 91 deletions.
2 changes: 1 addition & 1 deletion siunitx.js

Large diffs are not rendered by default.

21 changes: 8 additions & 13 deletions src/angMethods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,13 @@ function parseAngle(parser: TexParser, text: string, options: IAngleOptions): IA
}

function convertToArc(ang: IAnglePiece): void {
if (ang.minutes !== null || ang.seconds !== null) {
if (ang.minutes || ang.seconds) {
// already arc format
return;
}

// This ignores exponents.
if (ang.degrees.decimal !== '') {
if (!ang.degrees.decimal) {
const firstFraction = +('0.' + ang.degrees.fractional);
ang.degrees.fractional = '';
ang.degrees.decimal = '';
Expand All @@ -109,11 +109,11 @@ function convertToArc(ang: IAnglePiece): void {

function convertToDecimal(ang: IAnglePiece): void {
let value = 0;
if (ang.seconds !== undefined && ang.seconds !== null) {
if (ang.seconds && ang.seconds !== null) {
value = +ang.seconds.whole / 60;
ang.seconds = null;
}
if (ang.minutes !== undefined && ang.minutes !== null) {
if (ang.minutes && ang.minutes !== null) {
value = (+ang.minutes.whole + value) / 60;
ang.minutes = null;
}
Expand Down Expand Up @@ -146,7 +146,6 @@ function degreeOverDecimal(parser: TexParser, inputNode: MmlNode, symbolToUse: s
replacementNode.appendChild(parser.create('token', 'mn', {}, split[1]));
const parent = numNode.parent;
parent.replaceChild(replacementNode, numNode);
//console.log(JSON.parse(JSON.stringify(numNode)));
degreeNodeToAdd = inputNode as MmlNode;
}
}
Expand Down Expand Up @@ -227,8 +226,8 @@ function displayAngleMml(parser: TexParser, ang: IAnglePiece, options: IAngleOpt
}

let secondsNodeToAdd: MmlNode;
if (ang.seconds !== undefined && ang.seconds !== null) {
const secondsValue = +(ang.seconds.whole + (ang.seconds.decimal !== '' ? '.' : '') + ang.seconds.fractional);
if (ang.seconds && ang.seconds !== null) {
const secondsValue = +(ang.seconds.whole + (ang.seconds.decimal ? '.' : '') + ang.seconds.fractional);
let moddedAngleSymbolSecond = '\\mathrm{' + options["angle-symbol-second"] + '}';
if (moddedAngleSymbolSecond === "\\mathrm{''}") {
// TODO: Localize the degree-seconds
Expand Down Expand Up @@ -284,15 +283,11 @@ export function processAngle(parser: TexParser): MmlNode {
const globalOptions: IOptions = { ...parser.options.siunitx as IOptions };

const localOptions = findOptions(parser, globalOptions);

//const options = processOptions(globalOptions, localOptions);
//options.forEach((v, k) => globalOptions[k] = v);

Object.assign(globalOptions, localOptions);

const text = parser.GetArgument('ang');

// FIXME: processOption here twice in processAngle?
//processOptions(globalOptions, localOptionString);
const ang = parseAngle(parser, text, globalOptions);
// TODO: consider error checking result
// Is there an exponent?? Throw an error... or ignore it?
Expand Down
4 changes: 1 addition & 3 deletions src/complexMethods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ const ComplexDefault: IComplex = {
};

export function parseComplexNumber(parser: TexParser, text: string, options: IOptions): IComplex {
// console.log("Complex text: ");
// console.log(text);

const complex = { ...ComplexDefault };
// Check if polar input
Expand Down Expand Up @@ -214,7 +212,7 @@ export function processComplexQuantity(parser: TexParser): void {

let quantityProductNode = null;
const trimmedQuantityProduct = globalOptions["quantity-product"].trimStart();
if (trimmedQuantityProduct !== '') {
if (trimmedQuantityProduct) {
const spacerNode = (new TexParser(trimmedQuantityProduct, parser.stack.env, parser.configuration)).mml();
const spacerUnicode = findInnerText(spacerNode);
quantityProductNode = parser.create('token', 'mo', {}, spacerUnicode);
Expand Down
2 changes: 2 additions & 0 deletions src/error/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,7 @@ export class siunitxError {
static NoUncertaintyToClose = () => new TexError('siunitx:noUncertaintyToClose', data.noUncertaintyToClose);

static UncertaintyAlreadyClosed = () => new TexError('siunitx:uncertaintyAlreadyClosed', data.uncertaintyAlreadyClosed);

static DenominatorParsingError = (denominator:string, permode:string) => new TexError('siunitx:denominatorParsingError', data.denominatorParsingError, denominator, permode);

}
3 changes: 2 additions & 1 deletion src/error/resource.en.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@
"literalUnitsForbidden": "%1 is detected as a literal unit. These are forbidden globally. Use interpreted units instead (i.e. \\kilo\\gram).",
"macroNotDefined": "The unit macro, %1, has not been defined.",
"noUncertaintyToClose": "Trying to close an uncertainty that doesn't exist.",
"uncertaintyAlreadyClosed": "Uncertainty was already closed."
"uncertaintyAlreadyClosed": "Uncertainty was already closed.",
"denominatorParsingError": "Couldn't parse %1 using per-mode option of %2."
}
10 changes: 5 additions & 5 deletions src/numDisplayMethods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ export function convertUncertaintyToBracket(uncertainty: IUncertainty, piece: IN
if (diff > 0) {
uncertainty.fractional = uncertainty.whole.slice(diff, uncertainty.whole.length);
uncertainty.whole = uncertainty.whole.slice(0, diff);
if (uncertainty.fractional !== '') {
if (uncertainty.fractional) {
uncertainty.decimal = options["output-decimal-marker"];
}
} else if (diff < 0 && options["uncertainty-mode"] === 'full') {
Expand Down Expand Up @@ -155,7 +155,7 @@ function displayUncertaintyBracketMml(uncertainty: IUncertainty, parser: TexPars
const openUncertainty = (new TexParser(options["output-open-uncertainty"], parser.stack.env, parser.configuration)).mml();

let number = uncertainty.whole;
number += (options["uncertainty-mode"] === 'compact-marker' || options["uncertainty-mode"] === 'full') && uncertainty.decimal !== '' ? options["output-decimal-marker"] : '';
number += (options["uncertainty-mode"] === 'compact-marker' || options["uncertainty-mode"] === 'full') && uncertainty.decimal ? options["output-decimal-marker"] : '';
number += uncertainty.fractional;
const numberNode = parser.create('token', 'mn', {}, number);
const closeUncertainty = (new TexParser(options["output-close-uncertainty"], parser.stack.env, parser.configuration)).mml();
Expand Down Expand Up @@ -214,7 +214,7 @@ export function createExponentMml(num: INumberPiece, parser: TexParser, options:
}
root.appendChild(exponential);
}
} else if (num.exponent !== '' && num.exponent !== '0') {
} else if (num.exponent && num.exponent !== '0') {
const exponentSignNode = parser.create('token', 'mo', {}, num.exponentSign);
const exponentValueNode = parser.create('token', 'mn', {}, num.exponent);
const supPart = num.exponentSign === '-'
Expand All @@ -225,13 +225,13 @@ export function createExponentMml(num: INumberPiece, parser: TexParser, options:
if (num.whole === '1' && num.fractional === '' && !options["print-unity-mantissa"]) {
root.appendChild(exponential);
} else {
if (num.exponentMarker !== '') {
if (num.exponentMarker) {
if (options["output-exponent-marker"] !== '') {
const customExponentMarker = (new TexParser(options["output-exponent-marker"], parser.stack.env, parser.configuration)).mml();
root.appendChild(customExponentMarker);
root.appendChild(supPart);
} else {
if (num.whole !== '' || num.fractional !== '') {
if (num.whole || num.fractional) {
if (options["tight-spacing"]) {
exponentProductNode.attributes.set('lspace', '0em');
exponentProductNode.attributes.set('rspace', '0em');
Expand Down
21 changes: 9 additions & 12 deletions src/numMethods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,10 @@ export function generateNumberPiece(): INumberPiece {

export function pieceToNumber(piece: INumberPiece): number {
let build = piece.sign + piece.whole;
if (piece.fractional !== '') {
if (piece.fractional) {
build += '.' + piece.fractional;
}
if (piece.exponent !== '') {
if (piece.exponent) {
build += 'e' + piece.exponentSign + piece.exponent;
}
try {
Expand All @@ -83,9 +83,9 @@ function getLastNumPiece(numPiece: INumberPiece):INumberPiece{

function parseDigits(text: string, numPiece: INumberPiece) {
const num = getLastNumPiece(numPiece);
if (num.exponentMarker !== '') {
if (num.exponentMarker) {
num.exponent += text;
} else if (num.decimal !== '') {
} else if (num.decimal) {
num.fractional += text;
} else {
num.whole += text;
Expand All @@ -100,7 +100,7 @@ function parseDecimals(text: string, numPiece: INumberPiece) {
function parseComparators(text: string, numPiece: INumberPiece) {
const num = getLastNumPiece(numPiece);

if (num.prefix !== ''){
if (num.prefix){
throw siunitxError.ComparatorAlreadySet(num.prefix, text);
}
num.prefix += text;
Expand All @@ -119,7 +119,7 @@ function parseExponentMarkers(text: string, numPiece: INumberPiece) {

function parseSigns(text: string, numPiece: INumberPiece) {
const num = getLastNumPiece(numPiece);
if (num.exponentMarker !== '') {
if (num.exponentMarker) {
num.exponentSign += text;
} else {
num.sign += text;
Expand Down Expand Up @@ -218,21 +218,21 @@ export function parseNumber(parser: TexParser, text: string, options: INumOption

}

if (!options["retain-explicit-decimal-marker"] && num.decimal !== '' && num.fractional === '') {
if (!options["retain-explicit-decimal-marker"] && num.decimal && !num.fractional) {
num.decimal = '';
}
if (!options["retain-explicit-plus"] && num.sign === '+') {
num.sign = '';
}
// adding exponent to value check here. Without it, exponentials without a base won't stay negative. (-e10)
const value = +(num.whole + (num.decimal !== '' ? '.' : '') + num.fractional + (num.exponent === '' ? '' : 'e' + num.exponentSign + num.exponent));
const value = +(num.whole + (num.decimal ? '.' : '') + num.fractional + (num.exponent === '' ? '' : 'e' + num.exponentSign + num.exponent));
if (value === 0 && !options["retain-negative-zero"] && num.sign === '-') {
num.sign = '';
}

if (!options["retain-zero-uncertainty"]) {
for (let i = num.uncertainty.length - 1; i >= 0; i--) {
const uncertaintyValue = +(num.uncertainty[i].whole + (num.uncertainty[i].decimal !== '' ? '.' : '') + num.uncertainty[i].fractional);
const uncertaintyValue = +(num.uncertainty[i].whole + (num.uncertainty[i].decimal ? '.' : '') + num.uncertainty[i].fractional);
if (uncertaintyValue === 0) {
num.uncertainty.splice(i, 1);
}
Expand All @@ -247,9 +247,6 @@ export function processNumber(parser: TexParser): MmlNode {

const localOptions = findOptions(parser, globalOptions);

//processOptions(globalOptions, localOptionString);
//const options = processOptions(globalOptions, localOptionString);
//options.forEach((v,k)=> globalOptions[k] = v);
Object.assign(globalOptions, localOptions);

let text = parser.GetArgument('num');
Expand Down
11 changes: 5 additions & 6 deletions src/numPostProcessMethods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ import { IOptions } from "./options/options";

function convertToScientific(parser: TexParser, numOriginal: INumberPiece, options: INumPostOptions): INumberPiece {
//convert to actual number and use formating to print scientific
const num = JSON.parse(JSON.stringify(numOriginal));
const val = (+(num.sign + num.whole + num.decimal + num.fractional + (num.exponent !== '' ? ('e' + num.exponentSign + num.exponent) : ''))).toExponential();
const num :INumberPiece = JSON.parse(JSON.stringify(numOriginal));
const val = (+(num.sign + num.whole + num.decimal + num.fractional + (num.exponent ? ('e' + num.exponentSign + num.exponent) : ''))).toExponential();
// parse that back in
const newNum = parseNumber(parser, val, options as IOptions);

//don't forget to check for trailing zeros and put them back
let trailingZeros = 0;
// count trailing zeros in original fractional part
if (num.fractional !== '') {
if (num.fractional) {
for (let i = num.fractional.length - 1; i >= 0; i--) {
if (num.fractional[i] === '0') {
trailingZeros++;
Expand All @@ -25,7 +25,7 @@ function convertToScientific(parser: TexParser, numOriginal: INumberPiece, optio
}
}
// count trailing zeros in original whole part (if all of fractional part was zeros)
if (num.whole !== '' && num.fractional.length === trailingZeros) {
if (num.whole && num.fractional.length === trailingZeros) {
for (let i = num.whole.length - 1; i >= 0; i--) {
if (num.whole[i] === '0') {
trailingZeros++;
Expand All @@ -39,7 +39,7 @@ function convertToScientific(parser: TexParser, numOriginal: INumberPiece, optio
newNum.fractional += '0';
}
// add a decimal if the original didn't have one, but we need it.
if (newNum.decimal === '' && trailingZeros > 0) {
if (!newNum.decimal && trailingZeros > 0) {
newNum.decimal = '.';
}
// copy the new values to the original reference
Expand Down Expand Up @@ -205,7 +205,6 @@ function roundFigures(parser: TexParser, num: INumberPiece, options: INumPostOpt
// whole can't be '0', and converting fractional to number and back to string gets rid of leading zeros.
const combined = num.whole === '0' ? (+num.fractional).toString() : num.whole + (+num.fractional).toString();
if (combined.length > options["round-precision"]) {
//console.log(num.whole + num.decimal + num.fractional);
const firstDrop = +combined.slice(options["round-precision"], options["round-precision"] + 1);
const toRound = +combined.slice(options["round-precision"] - 1, options["round-precision"]);

Expand Down
29 changes: 4 additions & 25 deletions src/options/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,17 +49,17 @@ export function processSISetup(parser: TexParser): void {

const optionsString = parser.GetArgument('sisetup');

const options = processOptions(globalOptions, optionsString);
const options = optionStringToObject(optionsString, globalOptions);
Object.assign(parser.options.siunitx, options);

// We are adding the sisetup options to the parser options. These are global once the page is loaded.
// (the globalOptions variable is just a copy and will reset between each siunitx command)

// TODO: Figure out a how to limit these to grouping curly braces.
// For now, you'll have to reset the options manually with another sisetup command.

// In LaTeX, you can limit these options to grouping curly braces.
// For MathJAx, you just need to write new delimiters for text: $$ ... $$
}

// LaTeX commands (in the value portion) MUST end with a space before using a comma to add another option
function optionStringToObject(optionString: string, globalOptions: IOptions): Partial<IOptions> {
// No good way to extend typing for patch
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand All @@ -77,26 +77,5 @@ function optionStringToObject(optionString: string, globalOptions: IOptions): Pa
options[key] = value;
}

return options;
}

// LaTeX commands (in the value portion) MUST end with a space before using a comma to add another option
export function processOptions(globalOptions: IOptions, optionString: string): Record<string, string | boolean | number> {
// No good way to extend typing for patch
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const optionObject : EnvList = (ParseUtil.keyvalOptions as any)(optionString, globalOptions as unknown as { [key: string]: number }, true, true) ;
const options = {};

for (let [key, value] of Object.entries(optionObject)) {
const type = typeof globalOptions[key];
if (typeof value !== type) {
if (type === 'number' && value.toString().match(/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[-+]\d+)?$/)) {
value = parseFloat(value.toString());
} else {
throw siunitxError.InvalidOptionValue(key, type);
}
}
options[key] = value;
}
return options;
}
Loading

0 comments on commit b052505

Please sign in to comment.