Skip to content

Commit bb968f7

Browse files
feat: sort equations alphabetically when preprocessing mdl file (#56)
Fixes #55
1 parent e9bbbc6 commit bb968f7

1 file changed

Lines changed: 38 additions & 2 deletions

File tree

src/Preprocessor.js

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,13 +117,49 @@ let preprocessModel = (mdlFilename, spec, profile = 'genc', writeFiles = false)
117117
// Emit the encoding line and optional insertions.
118118
if (opts.emitEncoding) {
119119
B.emitLine(ENCODING, 'pp')
120+
B.emitLine('', 'pp')
120121
}
121122
if (insertions) {
122123
B.emitLine(insertions, 'pp')
123124
}
124-
// Emit formula lines without comment contents.
125+
126+
// Split into separate equations
125127
eqns = splitEquations(mdl)
128+
129+
// Extract the LHS variable name (minus any double quotes) for each equation,
130+
// which we will use to sort the equations alphabetically
131+
const unsortedEqns = []
126132
for (let eqn of eqns) {
133+
// Ignore the encoding
134+
eqn = eqn.replace('{UTF-8}', '')
135+
// Remove ":RAW:" flag
136+
eqn = eqn.replace(/:RAW:/, '')
137+
// Remove whitespace
138+
eqn = eqn.trim()
139+
if (eqn.length > 0) {
140+
// Split on newlines so that we look only at the first line of each equation
141+
let key = eqn.split(/\n/)[0]
142+
// Ignore double quotes
143+
key = key.replace(/\"/, '')
144+
// Ignore any whitespace that remains
145+
key = key.trim()
146+
// Ignore case
147+
key.toLowerCase()
148+
unsortedEqns.push({
149+
key,
150+
eqn
151+
})
152+
}
153+
}
154+
155+
// Sort the equations alphabetically by LHS variable name
156+
const sortedEqns = unsortedEqns.sort((a, b) => {
157+
return (a.key < b.key) ? -1 : (a.key > b.key) ? 1 : 0;
158+
})
159+
160+
// Emit formula lines without comment contents.
161+
for (const elem of sortedEqns) {
162+
const eqn = elem.eqn
127163
let iComment = eqn.indexOf('~')
128164
if (iComment >= 0) {
129165
let formula = B.lines(eqn.substr(0, iComment))
@@ -142,7 +178,7 @@ let preprocessModel = (mdlFilename, spec, profile = 'genc', writeFiles = false)
142178
}
143179
}
144180
if (opts.emitCommentMarkers) {
145-
emitPP('~~|')
181+
B.emitLine('~~|\n', 'pp')
146182
} else {
147183
B.emitLine('', 'pp')
148184
}

0 commit comments

Comments
 (0)