MCPcopy Create free account
hub / github.com/cortex-js/compute-engine / rationalValue

Function rationalValue

src/math-json/utils.ts:315–368  ·  view source on GitHub ↗
(
  expr: MathJsonExpression | undefined | null
)

Source from the content-addressed store, hash-verified

313 * - ["Power", n, 1]
314 * - ["Divide", n, d]
315 *
316 * The denominator is always > 0.
317 */
318export function rationalValue(
319 expr: MathJsonExpression | undefined | null
320): [number, number] | null {
321 if (expr === undefined || expr === null) return null;
322
323 if (symbol(expr) === 'Half') return [1, 2];
324
325 const h = operator(expr);
326 if (!h) return null;
327
328 let numer: number | null = null;
329 let denom: number | null = null;
330
331 if (h === 'Negate') {
332 const r = rationalValue(operands(expr)[0]);
333 if (r) return [-r[0], r[1]];
334 }
335
336 if (h === 'Rational' || h === 'Divide') {
337 const [n, d] = operands(expr);
338 numer = machineValue(n) ?? NaN;
339 denom = machineValue(d) ?? NaN;
340 }
341
342 if (h === 'Power') {
343 const [base, exp] = operands(expr);
344 const exponent = machineValue(exp);
345 if (exponent === 1) {
346 numer = machineValue(base);
347 denom = 1;
348 } else if (exponent === -1) {
349 numer = 1;
350 denom = machineValue(base);
351 }
352 }
353
354 if (h === 'Multiply') {
355 const [op1, op2] = operands(expr);
356
357 if (operator(op2) === 'Power') {
358 const [op21, op22] = operands(op2);
359 if (machineValue(op22) === -1) {
360 numer = machineValue(op1);
361 denom = machineValue(op21);
362 }
363 }
364 }
365
366 if (numer === null || denom === null) return null;
367
368 if (Number.isInteger(numer) && Number.isInteger(denom)) return [numer, denom];
369
370 return null;
371}

Callers 3

numeratorDenominatorFunction · 0.90
serializeAddFunction · 0.90
serializeMultiplyFunction · 0.90

Calls 5

operandsFunction · 0.85
machineValueFunction · 0.85
symbolFunction · 0.70
operatorFunction · 0.70
isIntegerMethod · 0.45

Tested by

no test coverage detected