MCPcopy
hub / github.com/darkreader/darkreader / lowerCalcExpression

Function lowerCalcExpression

src/utils/color.ts:456–488  ·  view source on GitHub ↗
(color: string)

Source from the content-addressed store, hash-verified

454// expressions from the given string. It can only lower expressions to a certain
455// degree so we can keep this function easy and simple to understand.
456export function lowerCalcExpression(color: string): string {
457 // searchIndex will be used as searchIndex and as a "cursor" within
458 // the calc(...) expression.
459 let searchIndex = 0;
460
461 // Replace the content between two indices.
462 const replaceBetweenIndices = (start: number, end: number, replacement: string) => {
463 color = color.substring(0, start) + replacement + color.substring(end);
464 };
465
466 // Run this code until it doesn't find any `calc(...)`.
467 while ((searchIndex = color.indexOf('calc(')) !== -1) {
468 // Get the parentheses ranges of `calc(...)`.
469 const range = getParenthesesRange(color, searchIndex);
470 if (!range) {
471 break;
472 }
473
474 // Get the content between the parentheses.
475 let slice = color.slice(range.start + 1, range.end - 1);
476 // Does the content include a percentage?
477 const includesPercentage = slice.includes('%');
478 // Remove all percentages.
479 slice = slice.split('%').join('');
480
481 // Pass the content to the evalMath library and round its output.
482 const output = Math.round(evalMath(slice));
483
484 // Replace `calc(...)` with the result.
485 replaceBetweenIndices(range.start - 4, range.end, output + (includesPercentage ? '%' : ''));
486 }
487 return color;
488}
489
490const knownColors: Map<string, number> = new Map(Object.entries({
491 aliceblue: 0xf0f8ff,

Callers 2

color.tests.tsFile · 0.90
parseColorWithCacheFunction · 0.85

Calls 3

getParenthesesRangeFunction · 0.90
evalMathFunction · 0.90
replaceBetweenIndicesFunction · 0.85

Tested by

no test coverage detected