Created
November 24, 2025 09:19
-
-
Save steveast/232098c1da07afc93533f57a531fcf58 to your computer and use it in GitHub Desktop.
Parses numeric values from Buy and Sell elements in the DOM, handling spaces, commas, dots, and negatives, then sums each group and the combined total, returning detailed parsed data for further use.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (() => { | |
| // Надёжный парсер чисел из текста | |
| function parseNumber(text) { | |
| if (!text && text !== 0) return NaN; | |
| let s = String(text).replace(/\u00A0/g, ' ').trim(); // NBSP -> space | |
| // Удалим буквы и символы валют, оставим цифры, точку, запятую, минус, скобки и пробелы | |
| s = s.replace(/[^\d\-,.\s()]/g, ''); | |
| // Скобки считаем признаком отрицательного числа: "(1 234,56)" -> -1234.56 | |
| const negative = /\(.*\)/.test(s); | |
| s = s.replace(/[()]/g, ''); | |
| // Удалим пробелы (между тысячами) — но сначала разберёмся с комбинацией точка/запятая | |
| s = s.replace(/\s+/g, ''); | |
| // Если и точка, и запятая есть — считаем, что последняя встречающаяся из них разделитель дробной части | |
| if (s.indexOf('.') !== -1 && s.indexOf(',') !== -1) { | |
| const lastDot = s.lastIndexOf('.'); | |
| const lastComma = s.lastIndexOf(','); | |
| if (lastDot > lastComma) { | |
| // точка — десятичная, удаляем запятые как разделители тысяч | |
| s = s.replace(/,/g, ''); | |
| } else { | |
| // запятая — десятичная, удаляем точки и заменяем запятую на точку | |
| s = s.replace(/\./g, '').replace(/,/g, '.'); | |
| } | |
| } else if (s.indexOf(',') !== -1) { | |
| // только запятая — считаем её десятичной | |
| s = s.replace(/,/g, '.'); | |
| } // иначе остаются точки как десятичные или ничего | |
| const num = parseFloat(s); | |
| if (isNaN(num)) return NaN; | |
| return negative ? -Math.abs(num) : num; | |
| } | |
| function sumForSelector(selector) { | |
| const els = Array.from(document.querySelectorAll(selector)); | |
| const values = els.map(el => { | |
| // берём видимый текст | |
| const text = (el.textContent || '').trim(); | |
| return { text, value: parseNumber(text) }; | |
| }); | |
| const valid = values.filter(v => !isNaN(v.value)); | |
| const total = valid.reduce((acc, v) => acc + v.value, 0); | |
| return { countAll: values.length, parsed: values, validCount: valid.length, total }; | |
| } | |
| // Селекторы (точно такие классы, как в вопросе) | |
| const buySel = '.typography-subtitle2.text-TextBuy'; | |
| const sellSel = '.typography-subtitle2.text-TextSell'; | |
| const buy = sumForSelector(buySel); | |
| const sell = sumForSelector(sellSel); | |
| const combinedTotal = (buy.total || 0) + (sell.total || 0); | |
| console.group('Summation result'); | |
| console.log('Buy:', { total: buy.total, itemsFound: buy.countAll, parsedCount: buy.validCount }); | |
| console.table(buy.parsed.map((p, i) => ({ index: i, text: p.text, value: p.value }))); | |
| console.log('Sell:', { total: sell.total, itemsFound: sell.countAll, parsedCount: sell.validCount }); | |
| console.table(sell.parsed.map((p, i) => ({ index: i, text: p.text, value: p.value }))); | |
| console.log('Combined total (Buy + Sell):', combinedTotal); | |
| console.groupEnd(); | |
| // Возвращаем объект для дальнейшей работы | |
| return { buy, sell, combinedTotal }; | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment