oakscriptjs 0.15.1 → 0.15.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/callsite/index.d.ts.map +1 -1
- package/dist/cjs/callsite/index.js +61 -7
- package/dist/cjs/callsite/index.js.map +2 -2
- package/dist/cjs/drawing/registry.d.ts +31 -3
- package/dist/cjs/drawing/registry.d.ts.map +1 -1
- package/dist/cjs/drawing/registry.js +188 -68
- package/dist/cjs/drawing/registry.js.map +2 -2
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/linefill/index.d.ts.map +1 -1
- package/dist/cjs/linefill/index.js +14 -5
- package/dist/cjs/linefill/index.js.map +2 -2
- package/dist/cjs/session/bars.d.ts +3 -0
- package/dist/cjs/session/bars.d.ts.map +1 -1
- package/dist/cjs/session/bars.js +10 -3
- package/dist/cjs/session/bars.js.map +2 -2
- package/dist/cjs/session/calendar.d.ts +19 -6
- package/dist/cjs/session/calendar.d.ts.map +1 -1
- package/dist/cjs/session/calendar.js +57 -18
- package/dist/cjs/session/calendar.js.map +2 -2
- package/dist/cjs/session/context.d.ts.map +1 -1
- package/dist/cjs/session/context.js +25 -8
- package/dist/cjs/session/context.js.map +2 -2
- package/dist/cjs/str/floatingdecimal.d.ts +3 -0
- package/dist/cjs/str/floatingdecimal.d.ts.map +1 -1
- package/dist/cjs/str/floatingdecimal.js +25 -12
- package/dist/cjs/str/floatingdecimal.js.map +2 -2
- package/dist/cjs/str/messageformat.d.ts.map +1 -1
- package/dist/cjs/str/messageformat.js +27 -8
- package/dist/cjs/str/messageformat.js.map +2 -2
- package/dist/cjs/str/numberformat.d.ts.map +1 -1
- package/dist/cjs/str/numberformat.js +9 -16
- package/dist/cjs/str/numberformat.js.map +3 -3
- package/dist/cjs/ta/index.d.ts.map +1 -1
- package/dist/cjs/ta/index.js +27 -0
- package/dist/cjs/ta/index.js.map +2 -2
- package/dist/cjs/ta/running-sum.d.ts +8 -1
- package/dist/cjs/ta/running-sum.d.ts.map +1 -1
- package/dist/cjs/ta/running-sum.js +13 -1
- package/dist/cjs/ta/running-sum.js.map +2 -2
- package/dist/cjs/time/timezone.d.ts +13 -1
- package/dist/cjs/time/timezone.d.ts.map +1 -1
- package/dist/cjs/time/timezone.js +64 -12
- package/dist/cjs/time/timezone.js.map +2 -2
- package/dist/esm/callsite/index.d.ts.map +1 -1
- package/dist/esm/callsite/index.js +76 -7
- package/dist/esm/callsite/index.js.map +1 -1
- package/dist/esm/drawing/registry.d.ts +31 -3
- package/dist/esm/drawing/registry.d.ts.map +1 -1
- package/dist/esm/drawing/registry.js +237 -80
- package/dist/esm/drawing/registry.js.map +1 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/linefill/index.d.ts.map +1 -1
- package/dist/esm/linefill/index.js +17 -7
- package/dist/esm/linefill/index.js.map +1 -1
- package/dist/esm/session/bars.d.ts +3 -0
- package/dist/esm/session/bars.d.ts.map +1 -1
- package/dist/esm/session/bars.js +11 -3
- package/dist/esm/session/bars.js.map +1 -1
- package/dist/esm/session/calendar.d.ts +19 -6
- package/dist/esm/session/calendar.d.ts.map +1 -1
- package/dist/esm/session/calendar.js +74 -21
- package/dist/esm/session/calendar.js.map +1 -1
- package/dist/esm/session/context.d.ts.map +1 -1
- package/dist/esm/session/context.js +34 -9
- package/dist/esm/session/context.js.map +1 -1
- package/dist/esm/str/floatingdecimal.d.ts +3 -0
- package/dist/esm/str/floatingdecimal.d.ts.map +1 -1
- package/dist/esm/str/floatingdecimal.js +27 -11
- package/dist/esm/str/floatingdecimal.js.map +1 -1
- package/dist/esm/str/messageformat.d.ts.map +1 -1
- package/dist/esm/str/messageformat.js +35 -9
- package/dist/esm/str/messageformat.js.map +1 -1
- package/dist/esm/str/numberformat.d.ts.map +1 -1
- package/dist/esm/str/numberformat.js +12 -18
- package/dist/esm/str/numberformat.js.map +1 -1
- package/dist/esm/ta/index.d.ts.map +1 -1
- package/dist/esm/ta/index.js +35 -0
- package/dist/esm/ta/index.js.map +1 -1
- package/dist/esm/ta/running-sum.d.ts +8 -1
- package/dist/esm/ta/running-sum.d.ts.map +1 -1
- package/dist/esm/ta/running-sum.js +16 -1
- package/dist/esm/ta/running-sum.js.map +1 -1
- package/dist/esm/time/timezone.d.ts +13 -1
- package/dist/esm/time/timezone.d.ts.map +1 -1
- package/dist/esm/time/timezone.js +97 -16
- package/dist/esm/time/timezone.js.map +1 -1
- package/package.json +1 -1
- package/src/callsite/index.ts +65 -7
- package/src/drawing/registry.ts +249 -79
- package/src/index.ts +1 -1
- package/src/linefill/index.ts +16 -7
- package/src/session/bars.ts +11 -3
- package/src/session/calendar.ts +84 -21
- package/src/session/context.ts +36 -9
- package/src/str/floatingdecimal.ts +27 -11
- package/src/str/messageformat.ts +40 -9
- package/src/str/numberformat.ts +13 -17
- package/src/ta/index.ts +41 -0
- package/src/ta/running-sum.ts +13 -1
- package/src/time/timezone.ts +99 -16
|
@@ -53,17 +53,31 @@ function chartSessions(chart) {
|
|
|
53
53
|
cache.set(chart, out);
|
|
54
54
|
return out;
|
|
55
55
|
}
|
|
56
|
+
const MAX_ARGUMENT_CALENDARS = 64;
|
|
57
|
+
const argumentCalendars = /* @__PURE__ */ new Map();
|
|
58
|
+
function argumentCalendar(timezone, session, rule, dayPlacement) {
|
|
59
|
+
const key = `${rule}|${dayPlacement}|${timezone}|${session}`;
|
|
60
|
+
let calendar = argumentCalendars.get(key);
|
|
61
|
+
if (!calendar) {
|
|
62
|
+
calendar = new import_calendar.TradingCalendar(timezone, { session }, rule, dayPlacement);
|
|
63
|
+
if (argumentCalendars.size >= MAX_ARGUMENT_CALENDARS) argumentCalendars.clear();
|
|
64
|
+
argumentCalendars.set(key, calendar);
|
|
65
|
+
}
|
|
66
|
+
return calendar;
|
|
67
|
+
}
|
|
56
68
|
function calendarFor(bars, chart, session, timezone, dayPlacement) {
|
|
57
69
|
if (!session && !timezone) return { bars, test: false };
|
|
58
70
|
const tz = timezone ?? chart.timezone;
|
|
59
71
|
if (session !== void 0 && (0, import_session.parsePineSession)(session) === null) {
|
|
60
72
|
const name = session.trim();
|
|
61
73
|
const symbol = name === "regular" && chart.regularSession ? chart.regularSession : chart.session;
|
|
62
|
-
return { bars: new import_bars.SessionBars(
|
|
74
|
+
return { bars: new import_bars.SessionBars(argumentCalendar(tz, toSpec(symbol).session, "symbol", false), bars.chart.period), test: true };
|
|
63
75
|
}
|
|
64
|
-
const spec = session ? { session } : { session: toSpec(chart.session).session };
|
|
65
76
|
return {
|
|
66
|
-
bars: new import_bars.SessionBars(
|
|
77
|
+
bars: new import_bars.SessionBars(
|
|
78
|
+
argumentCalendar(tz, session || toSpec(chart.session).session, session ? "pine" : "symbol", dayPlacement),
|
|
79
|
+
bars.chart.period
|
|
80
|
+
),
|
|
67
81
|
test: true,
|
|
68
82
|
// a PineScript session string: the rules of time.inSession (runs ending at 0000, days around a clock change)
|
|
69
83
|
inside: session ? (time) => (0, import_session.sessionRun)(time, session, tz, (0, import_timeframe.in_seconds)(bars.chart.period) * 1e3) !== null : void 0
|
|
@@ -104,11 +118,14 @@ function sessionPeriods(bars, chart, timeframe, session, timezone) {
|
|
|
104
118
|
const periodCache = /* @__PURE__ */ new WeakMap();
|
|
105
119
|
function periodsOfChart(chart, timeframe, session, timezone) {
|
|
106
120
|
const s = chartSessions(chart);
|
|
107
|
-
let
|
|
108
|
-
if (!
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
121
|
+
let byTimeframe = periodCache.get(chart);
|
|
122
|
+
if (!byTimeframe) periodCache.set(chart, byTimeframe = /* @__PURE__ */ new Map());
|
|
123
|
+
let bySession = byTimeframe.get(timeframe);
|
|
124
|
+
if (!bySession) byTimeframe.set(timeframe, bySession = /* @__PURE__ */ new Map());
|
|
125
|
+
let byZone = bySession.get(session ?? "");
|
|
126
|
+
if (!byZone) bySession.set(session ?? "", byZone = /* @__PURE__ */ new Map());
|
|
127
|
+
let p = byZone.get(timezone ?? "");
|
|
128
|
+
if (!p) byZone.set(timezone ?? "", p = sessionPeriods(s.bars, chart, timeframe, session, timezone));
|
|
112
129
|
return { s, p };
|
|
113
130
|
}
|
|
114
131
|
function periodTime(time, timeframe, chart, session, timezone) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/session/context.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * The session of a chart context, for code that does not run a whole script (a port with its own bar loop).\n *\n * The same values as the script API gives (`time(tf)`, `time_close(tf)`, `time_tradingday`, `session.*`, the periods\n * of `request.security`), from the session, corrections and holidays of the context. Bar times are in the unit of\n * the context (`timeUnit`, seconds by default, as `Bar.time`); PineScript time values are returned in ms.\n *\n * @module session/context\n */\n\nimport type { Bar } from '../types/index.js';\nimport { info, in_seconds } from '../timeframe/index.js';\nimport { afterCompletion, periodsOf, resample } from '../security/resample.js';\nimport { parsePineSession, sessionRun } from '../time/session.js';\nimport { SessionBars, sessionFlags, strayPeriods, type SessionFlags } from './bars.js';\nimport { TradingCalendar, type SessionSpec } from './calendar.js';\n\n/** The part of a chart context that the session functions read (a `ChartContext` of the script API fits). */\nexport interface SessionContext {\n /** Chart timeframe: \"5\", \"60\", \"1D\"... */\n timeframe?: string;\n /** Exchange time zone: \"America/New_York\", \"Etc/UTC\"... */\n timezone?: string;\n /** Session of the loaded bars: hours, corrections, holidays */\n session?: SessionSpec | string;\n /** Regular trading hours when the bars include extended hours (default: `session`) */\n regularSession?: SessionSpec | string;\n /** Unit of the bar times: 's' (default) or 'ms' */\n timeUnit?: 's' | 'ms';\n}\n\n/** The session calendars of a context: the loaded bars and the regular hours. */\nexport interface ChartSessions {\n bars: SessionBars;\n regular: SessionBars;\n /** ms per unit of the bar times */\n unit: number;\n}\n\nconst toSpec = (s: SessionSpec | string): SessionSpec => (typeof s === 'string' ? { session: s } : s);\nconst cache = new WeakMap<object, ChartSessions>();\n\n/**\n * Session calendars of a chart context (cached per context object).\n * @throws Error when the context has no timeframe, time zone or session\n */\nexport function chartSessions(chart: SessionContext): ChartSessions {\n const cached = cache.get(chart);\n if (cached) return cached;\n const { timeframe, timezone, session } = chart;\n if (!timeframe || !timezone || !session) {\n throw new Error('The chart context needs timeframe, timezone and session for the session functions.');\n }\n const loaded = toSpec(session);\n const regular = chart.regularSession ? toSpec(chart.regularSession) : loaded;\n const out: ChartSessions = {\n bars: new SessionBars(new TradingCalendar(timezone, loaded), timeframe),\n regular: new SessionBars(new TradingCalendar(timezone, { holidays: loaded.holidays, ...regular }), timeframe),\n unit: chart.timeUnit === 'ms' ? 1 : 1000,\n };\n cache.set(chart, out);\n return out;\n}\n\n/** Open and close (ms) of the period that contains a bar opening at a time in ms; NaN outside the session. */\nexport interface SessionPeriods {\n open: (time: number) => number;\n close: (time: number) => number;\n}\n\n/**\n * Calendar for the `session` / `timezone` arguments of `time(tf, session, timezone)`. Without both: the loaded\n * session. As in PineScript, an explicit time zone reads the symbol session hours in that zone without corrections\n * and holidays, and an explicit session follows PineScript's session string rules.\n */\nfunction calendarFor(\n bars: SessionBars,\n chart: SessionContext,\n session: string | undefined,\n timezone: string | undefined,\n dayPlacement: boolean\n): { bars: SessionBars; test: boolean; inside?: (time: number) => boolean } {\n if (!session && !timezone) return { bars, test: false };\n const tz = timezone ?? chart.timezone!;\n // a session string that is empty or does not start with a digit is the symbol session: \"regular\" the regular\n // hours, \"extended\" and any other name the loaded hours (PineScript)\n if (session !== undefined && parsePineSession(session) === null) {\n const name = session.trim();\n const symbol = name === 'regular' && chart.regularSession ? chart.regularSession : chart.session!;\n return { bars: new SessionBars(new TradingCalendar(tz, { session: toSpec(symbol).session }, 'symbol'), bars.chart.period), test: true };\n }\n const spec = session ? { session } : { session: toSpec(chart.session!).session };\n return {\n bars: new SessionBars(new TradingCalendar(tz, spec, session ? 'pine' : 'symbol', dayPlacement), bars.chart.period),\n test: true,\n // a PineScript session string: the rules of time.inSession (runs ending at 0000, days around a clock change)\n inside: session ? (time) => sessionRun(time, session, tz, in_seconds(bars.chart.period) * 1000) !== null : undefined,\n };\n}\n\n/**\n * `time(tf, session, timezone)` / `time_close(tf, session, timezone)` of a bar, as PineScript computes them (#173):\n * an intraday timeframe tests the bar with the session rules of time.inSession and aligns its periods on the start\n * of the run that contains the bar; \"D\" tests the bar against the day's session period (the calendar; the time\n * between two runs of a day is inside it, #182); a timeframe of more than one day (\"2D\", \"W\", \"M\") has no test and\n * keeps the period's time. `bars` is the calendar of the loaded session (`chartSessions(chart).bars`).\n */\nexport function sessionPeriods(\n bars: SessionBars,\n chart: SessionContext,\n timeframe: string,\n session?: string,\n timezone?: string\n): SessionPeriods {\n const tf = info(timeframe);\n const { bars: calendar, test, inside } = calendarFor(bars, chart, session, timezone, !tf.isintraday);\n const open = (t: number): number => calendar.timeOf(t, timeframe);\n const close = (t: number): number => calendar.closeOf(t, timeframe);\n if (!test) return { open, close };\n if (tf.isintraday) {\n if (session !== undefined && parsePineSession(session) !== null && !calendar.chart.isdwm) {\n const tz = timezone ?? chart.timezone!;\n const barMs = in_seconds(calendar.chart.period) * 1000;\n const ms = in_seconds(tf.period) * 1000;\n const run = (t: number) => sessionRun(t, session, tz, barMs);\n const start = (t: number, r: [number, number]) => r[0] + Math.floor((t - r[0]) / ms) * ms;\n return {\n open: (t) => { const r = run(t); return r ? start(t, r) : NaN; },\n close: (t) => { const r = run(t); return r ? Math.min(start(t, r) + ms, r[1]) : NaN; },\n };\n }\n const isIn = (t: number) => (inside ? inside(t) : calendar.inside(t));\n return { open: (t) => (isIn(t) ? open(t) : NaN), close: (t) => (isIn(t) ? close(t) : NaN) };\n }\n if (tf.isdaily && tf.multiplier === 1) {\n return { open: (t) => (calendar.inside(t) ? open(t) : NaN), close: (t) => (calendar.inside(t) ? close(t) : NaN) };\n }\n return { open, close };\n}\n\nconst periodCache = new WeakMap<object, Map<string, SessionPeriods>>();\n\nfunction periodsOfChart(chart: SessionContext, timeframe: string, session?: string, timezone?: string): { s: ChartSessions; p: SessionPeriods } {\n const s = chartSessions(chart);\n let byKey = periodCache.get(chart);\n if (!byKey) periodCache.set(chart, (byKey = new Map()));\n const key = `${timeframe}|${session ?? ''}|${timezone ?? ''}`;\n let p = byKey.get(key);\n if (!p) byKey.set(key, (p = sessionPeriods(s.bars, chart, timeframe, session, timezone)));\n return { s, p };\n}\n\n/**\n * PineScript `time(timeframe, session, timezone)` (ms) of a bar that opens at `time`: the start of its period; NaN\n * without one or outside `session` (#182). Without `session` and `timezone`, the periods of the loaded session.\n */\nexport function periodTime(time: number, timeframe: string, chart: SessionContext, session?: string, timezone?: string): number {\n const { s, p } = periodsOfChart(chart, timeframe, session, timezone);\n return p.open(time * s.unit);\n}\n\n/** PineScript `time_close(timeframe, session, timezone)` (ms) of a bar that opens at `time` (#182). */\nexport function periodClose(time: number, timeframe: string, chart: SessionContext, session?: string, timezone?: string): number {\n const { s, p } = periodsOfChart(chart, timeframe, session, timezone);\n return p.close(time * s.unit);\n}\n\n/** PineScript `time_tradingday` (ms, 00:00 UTC of the trading day) of a bar that opens at `time`. */\nexport function tradingDayTime(time: number, chart: SessionContext): number {\n const s = chartSessions(chart);\n return s.bars.tradingDayTime(time * s.unit);\n}\n\n/** PineScript `session.*` flags of bars that open at `times` (in order). */\nexport function chartSessionFlags(times: ArrayLike<number>, chart: SessionContext): SessionFlags {\n const s = chartSessions(chart);\n return sessionFlags(Array.from(times, (t) => t * s.unit), s.bars, s.regular);\n}\n\n/** Higher-timeframe bars of the chart bars and what `mapToChart` needs to bring values back to the chart. */\nexport interface SessionResample {\n /** Bars of `timeframe`, built from the chart bars */\n bars: Bar[];\n /** Period index of each chart bar */\n group: number[];\n /** Latest completed period at each chart bar */\n latest: number[];\n}\n\n/**\n * Same-symbol `request.security` on a timeframe equal to or higher than the chart's, with the session of the context:\n * D / W / M periods follow the regular hours, corrections and holidays; intraday periods the loaded session.\n * Compute on `bars`, then bring each value series back with `mapToChart(values, group, latest, lookahead, gaps)`.\n * @throws Error when `timeframe` is lower than the chart timeframe\n */\nexport function resampleSession(bars: Bar[], timeframe: string, chart: SessionContext): SessionResample {\n const s = chartSessions(chart);\n const chartTf = s.bars.chart;\n const tf = info(timeframe || chartTf.period);\n if (tf.period === chartTf.period) {\n const group = bars.map((_, i) => i);\n return { bars, group, latest: group };\n }\n if (in_seconds(tf.period) < in_seconds(chartTf.period)) {\n throw new Error(`resampleSession: timeframe \"${tf.period}\" is lower than the chart timeframe \"${chartTf.period}\".`);\n }\n const times = bars.map((b) => (b.time as number) * s.unit);\n const calendar = tf.isdwm ? s.regular : s.bars;\n const starts = times.map((t) => calendar.timeOf(t, tf.period));\n const dayPeriods = times.map((t, i) => {\n const at = s.bars.calendar.locate(t);\n const periods = at ? calendar.calendar.periods(at.date) : [];\n return periods.length ? calendar.timeOf(periods[0]![0], tf.period) : starts[i]!;\n });\n strayPeriods(starts, dayPeriods, times, s.bars, tf.isdwm ? null : in_seconds(tf.period) * 1000);\n const reaches = times.map((t) => s.bars.closeOf(t, chartTf.period) >= calendar.periodEnd(t, tf.period));\n const { group, latest } = periodsOf(starts, dayPeriods, reaches);\n // a higher-timeframe bar ends at the bar that completes it (no value from after the completion)\n const after = afterCompletion(group, latest);\n const kept = (_: unknown, i: number): boolean => !after[i];\n return { bars: resample(bars.filter(kept), starts.map((x) => x / s.unit).filter(kept)).bars, group, latest };\n}\n\n/**\n * Open time of the `count`-th bar after the bar that opens at `time`, on the trading calendar of the context: the\n * closed hours, weekends, holidays and days off are skipped. `count` 0 is the bar itself. For a drawing that ends\n * `count` bars after the last bar (PineScript `bar_index + count`).\n */\nexport function barTimeAfter(time: number, count: number, chart: SessionContext): number {\n const s = chartSessions(chart);\n let t = time * s.unit;\n for (let k = 0; k < count && !Number.isNaN(t); k++) t = s.bars.nextBarTime(t);\n return t / s.unit;\n}\n\n/**\n * Number of bars from the bar that opens at `from` to the bar that contains `to`, on the trading calendar of the\n * context (0 when `to` is in the bar of `from` or before it). For a drawing placed at a time after the last bar\n * (PineScript `time + n days` with `xloc.bar_time`): the chart shows it on the bar of that time, weekends and\n * holidays skipped. `to` is first rounded to the nearest second, a half second going up (#174: 15 ms before a bar\n * opens is on that bar, 501 ms before is on the bar before). NaN when no bar is found within 100,000 bars.\n */\nexport function barsUntil(from: number, to: number, chart: SessionContext): number {\n const s = chartSessions(chart);\n const target = Math.floor((to * s.unit) / 1000 + 0.5) * 1000;\n let t = from * s.unit;\n for (let k = 0; k < 100_000; k++) {\n const next = s.bars.nextBarTime(t);\n if (Number.isNaN(next)) return NaN;\n if (next > target) return k;\n t = next;\n }\n return NaN;\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWA,uBAAiC;AACjC,sBAAqD;AACrD,qBAA6C;AAC7C,kBAA2E;AAC3E,sBAAkD;AAwBlD,MAAM,SAAS,CAAC,MAA0C,OAAO,MAAM,WAAW,EAAE,SAAS,EAAE,IAAI;AACnG,MAAM,QAAQ,oBAAI,QAA+B;AAM1C,SAAS,cAAc,OAAsC;AAClE,QAAM,SAAS,MAAM,IAAI,KAAK;AAC9B,MAAI,OAAQ,QAAO;AACnB,QAAM,EAAE,WAAW,UAAU,QAAQ,IAAI;AACzC,MAAI,CAAC,aAAa,CAAC,YAAY,CAAC,SAAS;AACvC,UAAM,IAAI,MAAM,oFAAoF;AAAA,EACtG;AACA,QAAM,SAAS,OAAO,OAAO;AAC7B,QAAM,UAAU,MAAM,iBAAiB,OAAO,MAAM,cAAc,IAAI;AACtE,QAAM,MAAqB;AAAA,IACzB,MAAM,IAAI,wBAAY,IAAI,gCAAgB,UAAU,MAAM,GAAG,SAAS;AAAA,IACtE,SAAS,IAAI,wBAAY,IAAI,gCAAgB,UAAU,EAAE,UAAU,OAAO,UAAU,GAAG,QAAQ,CAAC,GAAG,SAAS;AAAA,IAC5G,MAAM,MAAM,aAAa,OAAO,IAAI;AAAA,EACtC;AACA,QAAM,IAAI,OAAO,GAAG;AACpB,SAAO;AACT;
|
|
4
|
+
"sourcesContent": ["/**\n * The session of a chart context, for code that does not run a whole script (a port with its own bar loop).\n *\n * The same values as the script API gives (`time(tf)`, `time_close(tf)`, `time_tradingday`, `session.*`, the periods\n * of `request.security`), from the session, corrections and holidays of the context. Bar times are in the unit of\n * the context (`timeUnit`, seconds by default, as `Bar.time`); PineScript time values are returned in ms.\n *\n * @module session/context\n */\n\nimport type { Bar } from '../types/index.js';\nimport { info, in_seconds } from '../timeframe/index.js';\nimport { afterCompletion, periodsOf, resample } from '../security/resample.js';\nimport { parsePineSession, sessionRun } from '../time/session.js';\nimport { SessionBars, sessionFlags, strayPeriods, type SessionFlags } from './bars.js';\nimport { TradingCalendar, type SessionSpec } from './calendar.js';\n\n/** The part of a chart context that the session functions read (a `ChartContext` of the script API fits). */\nexport interface SessionContext {\n /** Chart timeframe: \"5\", \"60\", \"1D\"... */\n timeframe?: string;\n /** Exchange time zone: \"America/New_York\", \"Etc/UTC\"... */\n timezone?: string;\n /** Session of the loaded bars: hours, corrections, holidays */\n session?: SessionSpec | string;\n /** Regular trading hours when the bars include extended hours (default: `session`) */\n regularSession?: SessionSpec | string;\n /** Unit of the bar times: 's' (default) or 'ms' */\n timeUnit?: 's' | 'ms';\n}\n\n/** The session calendars of a context: the loaded bars and the regular hours. */\nexport interface ChartSessions {\n bars: SessionBars;\n regular: SessionBars;\n /** ms per unit of the bar times */\n unit: number;\n}\n\nconst toSpec = (s: SessionSpec | string): SessionSpec => (typeof s === 'string' ? { session: s } : s);\nconst cache = new WeakMap<object, ChartSessions>();\n\n/**\n * Session calendars of a chart context (cached per context object).\n * @throws Error when the context has no timeframe, time zone or session\n */\nexport function chartSessions(chart: SessionContext): ChartSessions {\n const cached = cache.get(chart);\n if (cached) return cached;\n const { timeframe, timezone, session } = chart;\n if (!timeframe || !timezone || !session) {\n throw new Error('The chart context needs timeframe, timezone and session for the session functions.');\n }\n const loaded = toSpec(session);\n const regular = chart.regularSession ? toSpec(chart.regularSession) : loaded;\n const out: ChartSessions = {\n bars: new SessionBars(new TradingCalendar(timezone, loaded), timeframe),\n regular: new SessionBars(new TradingCalendar(timezone, { holidays: loaded.holidays, ...regular }), timeframe),\n unit: chart.timeUnit === 'ms' ? 1 : 1000,\n };\n cache.set(chart, out);\n return out;\n}\n\n/** Open and close (ms) of the period that contains a bar opening at a time in ms; NaN outside the session. */\nexport interface SessionPeriods {\n open: (time: number) => number;\n close: (time: number) => number;\n}\n\n/** Calendars of the `session` / `timezone` arguments before the cache restarts */\nconst MAX_ARGUMENT_CALENDARS = 64;\nconst argumentCalendars = new Map<string, TradingCalendar>();\n\n/**\n * Calendar of a session string read in a time zone, without corrections and holidays: it depends on these only, so\n * the calls with other timeframes or other chart contexts share it and its periods (a script often reads\n * `time(timeframe.period, s)` and `time(\"D\", s)` on every bar).\n */\nfunction argumentCalendar(timezone: string, session: string, rule: 'symbol' | 'pine', dayPlacement: boolean): TradingCalendar {\n const key = `${rule}|${dayPlacement}|${timezone}|${session}`;\n let calendar = argumentCalendars.get(key);\n if (!calendar) {\n calendar = new TradingCalendar(timezone, { session }, rule, dayPlacement);\n if (argumentCalendars.size >= MAX_ARGUMENT_CALENDARS) argumentCalendars.clear();\n argumentCalendars.set(key, calendar);\n }\n return calendar;\n}\n\n/**\n * Calendar for the `session` / `timezone` arguments of `time(tf, session, timezone)`. Without both: the loaded\n * session. As in PineScript, an explicit time zone reads the symbol session hours in that zone without corrections\n * and holidays, and an explicit session follows PineScript's session string rules.\n */\nfunction calendarFor(\n bars: SessionBars,\n chart: SessionContext,\n session: string | undefined,\n timezone: string | undefined,\n dayPlacement: boolean\n): { bars: SessionBars; test: boolean; inside?: (time: number) => boolean } {\n if (!session && !timezone) return { bars, test: false };\n const tz = timezone ?? chart.timezone!;\n // a session string that is empty or does not start with a digit is the symbol session: \"regular\" the regular\n // hours, \"extended\" and any other name the loaded hours (PineScript)\n if (session !== undefined && parsePineSession(session) === null) {\n const name = session.trim();\n const symbol = name === 'regular' && chart.regularSession ? chart.regularSession : chart.session!;\n return { bars: new SessionBars(argumentCalendar(tz, toSpec(symbol).session, 'symbol', false), bars.chart.period), test: true };\n }\n return {\n bars: new SessionBars(\n argumentCalendar(tz, session || toSpec(chart.session!).session, session ? 'pine' : 'symbol', dayPlacement),\n bars.chart.period\n ),\n test: true,\n // a PineScript session string: the rules of time.inSession (runs ending at 0000, days around a clock change)\n inside: session ? (time) => sessionRun(time, session, tz, in_seconds(bars.chart.period) * 1000) !== null : undefined,\n };\n}\n\n/**\n * `time(tf, session, timezone)` / `time_close(tf, session, timezone)` of a bar, as PineScript computes them (#173):\n * an intraday timeframe tests the bar with the session rules of time.inSession and aligns its periods on the start\n * of the run that contains the bar; \"D\" tests the bar against the day's session period (the calendar; the time\n * between two runs of a day is inside it, #182); a timeframe of more than one day (\"2D\", \"W\", \"M\") has no test and\n * keeps the period's time. `bars` is the calendar of the loaded session (`chartSessions(chart).bars`).\n */\nexport function sessionPeriods(\n bars: SessionBars,\n chart: SessionContext,\n timeframe: string,\n session?: string,\n timezone?: string\n): SessionPeriods {\n const tf = info(timeframe);\n const { bars: calendar, test, inside } = calendarFor(bars, chart, session, timezone, !tf.isintraday);\n const open = (t: number): number => calendar.timeOf(t, timeframe);\n const close = (t: number): number => calendar.closeOf(t, timeframe);\n if (!test) return { open, close };\n if (tf.isintraday) {\n if (session !== undefined && parsePineSession(session) !== null && !calendar.chart.isdwm) {\n const tz = timezone ?? chart.timezone!;\n const barMs = in_seconds(calendar.chart.period) * 1000;\n const ms = in_seconds(tf.period) * 1000;\n const run = (t: number) => sessionRun(t, session, tz, barMs);\n const start = (t: number, r: [number, number]) => r[0] + Math.floor((t - r[0]) / ms) * ms;\n return {\n open: (t) => { const r = run(t); return r ? start(t, r) : NaN; },\n close: (t) => { const r = run(t); return r ? Math.min(start(t, r) + ms, r[1]) : NaN; },\n };\n }\n const isIn = (t: number) => (inside ? inside(t) : calendar.inside(t));\n return { open: (t) => (isIn(t) ? open(t) : NaN), close: (t) => (isIn(t) ? close(t) : NaN) };\n }\n if (tf.isdaily && tf.multiplier === 1) {\n return { open: (t) => (calendar.inside(t) ? open(t) : NaN), close: (t) => (calendar.inside(t) ? close(t) : NaN) };\n }\n return { open, close };\n}\n\n/** Periods per chart, timeframe, session and time zone (no session / time zone is \"\"): maps of the given strings, no\n * key to build on every bar */\nconst periodCache = new WeakMap<object, Map<string, Map<string, Map<string, SessionPeriods>>>>();\n\nfunction periodsOfChart(chart: SessionContext, timeframe: string, session?: string, timezone?: string): { s: ChartSessions; p: SessionPeriods } {\n const s = chartSessions(chart);\n let byTimeframe = periodCache.get(chart);\n if (!byTimeframe) periodCache.set(chart, (byTimeframe = new Map()));\n let bySession = byTimeframe.get(timeframe);\n if (!bySession) byTimeframe.set(timeframe, (bySession = new Map()));\n let byZone = bySession.get(session ?? '');\n if (!byZone) bySession.set(session ?? '', (byZone = new Map()));\n let p = byZone.get(timezone ?? '');\n if (!p) byZone.set(timezone ?? '', (p = sessionPeriods(s.bars, chart, timeframe, session, timezone)));\n return { s, p };\n}\n\n/**\n * PineScript `time(timeframe, session, timezone)` (ms) of a bar that opens at `time`: the start of its period; NaN\n * without one or outside `session` (#182). Without `session` and `timezone`, the periods of the loaded session.\n */\nexport function periodTime(time: number, timeframe: string, chart: SessionContext, session?: string, timezone?: string): number {\n const { s, p } = periodsOfChart(chart, timeframe, session, timezone);\n return p.open(time * s.unit);\n}\n\n/** PineScript `time_close(timeframe, session, timezone)` (ms) of a bar that opens at `time` (#182). */\nexport function periodClose(time: number, timeframe: string, chart: SessionContext, session?: string, timezone?: string): number {\n const { s, p } = periodsOfChart(chart, timeframe, session, timezone);\n return p.close(time * s.unit);\n}\n\n/** PineScript `time_tradingday` (ms, 00:00 UTC of the trading day) of a bar that opens at `time`. */\nexport function tradingDayTime(time: number, chart: SessionContext): number {\n const s = chartSessions(chart);\n return s.bars.tradingDayTime(time * s.unit);\n}\n\n/** PineScript `session.*` flags of bars that open at `times` (in order). */\nexport function chartSessionFlags(times: ArrayLike<number>, chart: SessionContext): SessionFlags {\n const s = chartSessions(chart);\n return sessionFlags(Array.from(times, (t) => t * s.unit), s.bars, s.regular);\n}\n\n/** Higher-timeframe bars of the chart bars and what `mapToChart` needs to bring values back to the chart. */\nexport interface SessionResample {\n /** Bars of `timeframe`, built from the chart bars */\n bars: Bar[];\n /** Period index of each chart bar */\n group: number[];\n /** Latest completed period at each chart bar */\n latest: number[];\n}\n\n/**\n * Same-symbol `request.security` on a timeframe equal to or higher than the chart's, with the session of the context:\n * D / W / M periods follow the regular hours, corrections and holidays; intraday periods the loaded session.\n * Compute on `bars`, then bring each value series back with `mapToChart(values, group, latest, lookahead, gaps)`.\n * @throws Error when `timeframe` is lower than the chart timeframe\n */\nexport function resampleSession(bars: Bar[], timeframe: string, chart: SessionContext): SessionResample {\n const s = chartSessions(chart);\n const chartTf = s.bars.chart;\n const tf = info(timeframe || chartTf.period);\n if (tf.period === chartTf.period) {\n const group = bars.map((_, i) => i);\n return { bars, group, latest: group };\n }\n if (in_seconds(tf.period) < in_seconds(chartTf.period)) {\n throw new Error(`resampleSession: timeframe \"${tf.period}\" is lower than the chart timeframe \"${chartTf.period}\".`);\n }\n const times = bars.map((b) => (b.time as number) * s.unit);\n const calendar = tf.isdwm ? s.regular : s.bars;\n const starts = times.map((t) => calendar.timeOf(t, tf.period));\n const dayPeriods = times.map((t, i) => {\n const at = s.bars.calendar.locate(t);\n const periods = at ? calendar.calendar.periods(at.date) : [];\n return periods.length ? calendar.timeOf(periods[0]![0], tf.period) : starts[i]!;\n });\n strayPeriods(starts, dayPeriods, times, s.bars, tf.isdwm ? null : in_seconds(tf.period) * 1000);\n const reaches = times.map((t) => s.bars.closeOf(t, chartTf.period) >= calendar.periodEnd(t, tf.period));\n const { group, latest } = periodsOf(starts, dayPeriods, reaches);\n // a higher-timeframe bar ends at the bar that completes it (no value from after the completion)\n const after = afterCompletion(group, latest);\n const kept = (_: unknown, i: number): boolean => !after[i];\n return { bars: resample(bars.filter(kept), starts.map((x) => x / s.unit).filter(kept)).bars, group, latest };\n}\n\n/**\n * Open time of the `count`-th bar after the bar that opens at `time`, on the trading calendar of the context: the\n * closed hours, weekends, holidays and days off are skipped. `count` 0 is the bar itself. For a drawing that ends\n * `count` bars after the last bar (PineScript `bar_index + count`).\n */\nexport function barTimeAfter(time: number, count: number, chart: SessionContext): number {\n const s = chartSessions(chart);\n let t = time * s.unit;\n for (let k = 0; k < count && !Number.isNaN(t); k++) t = s.bars.nextBarTime(t);\n return t / s.unit;\n}\n\n/**\n * Number of bars from the bar that opens at `from` to the bar that contains `to`, on the trading calendar of the\n * context (0 when `to` is in the bar of `from` or before it). For a drawing placed at a time after the last bar\n * (PineScript `time + n days` with `xloc.bar_time`): the chart shows it on the bar of that time, weekends and\n * holidays skipped. `to` is first rounded to the nearest second, a half second going up (#174: 15 ms before a bar\n * opens is on that bar, 501 ms before is on the bar before). NaN when no bar is found within 100,000 bars.\n */\nexport function barsUntil(from: number, to: number, chart: SessionContext): number {\n const s = chartSessions(chart);\n const target = Math.floor((to * s.unit) / 1000 + 0.5) * 1000;\n let t = from * s.unit;\n for (let k = 0; k < 100_000; k++) {\n const next = s.bars.nextBarTime(t);\n if (Number.isNaN(next)) return NaN;\n if (next > target) return k;\n t = next;\n }\n return NaN;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWA,uBAAiC;AACjC,sBAAqD;AACrD,qBAA6C;AAC7C,kBAA2E;AAC3E,sBAAkD;AAwBlD,MAAM,SAAS,CAAC,MAA0C,OAAO,MAAM,WAAW,EAAE,SAAS,EAAE,IAAI;AACnG,MAAM,QAAQ,oBAAI,QAA+B;AAM1C,SAAS,cAAc,OAAsC;AAClE,QAAM,S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E;AACf;AASO,SAAS,UAAU,MAAc,IAAY,OAA+B;AACjF,QAAM,IAAI,cAAc,KAAK;AAC7B,QAAM,SAAS,KAAK,MAAO,KAAK,EAAE,OAAQ,MAAO,GAAG,IAAI;AACxD,MAAI,IAAI,OAAO,EAAE;AACjB,WAAS,IAAI,GAAG,IAAI,KAAS,KAAK;AAChC,UAAM,OAAO,EAAE,KAAK,YAAY,CAAC;AACjC,QAAI,OAAO,MAAM,IAAI,EAAG,QAAO;AAC/B,QAAI,OAAO,OAAQ,QAAO;AAC1B,QAAI;AAAA,EACN;AACA,SAAO;AACT;",
|
|
6
6
|
"names": ["group"]
|
|
7
7
|
}
|
|
@@ -17,6 +17,9 @@ export interface ConvertedDigits {
|
|
|
17
17
|
/** The digits are the exact value of the double */
|
|
18
18
|
exact: boolean;
|
|
19
19
|
}
|
|
20
|
+
export declare function pow5(k: number): bigint;
|
|
21
|
+
/** `s` without its trailing '0' characters. */
|
|
22
|
+
export declare function trimZeros(s: string): string;
|
|
20
23
|
/** Digits of a positive finite double, as the JVM converter gives them. */
|
|
21
24
|
export declare function convertDouble(x: number): ConvertedDigits;
|
|
22
25
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"floatingdecimal.d.ts","sourceRoot":"","sources":["../../../src/str/floatingdecimal.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,gGAAgG;AAChG,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;IACpB,oCAAoC;IACpC,SAAS,EAAE,OAAO,CAAC;IACnB,mDAAmD;IACnD,KAAK,EAAE,OAAO,CAAC;CAChB;
|
|
1
|
+
{"version":3,"file":"floatingdecimal.d.ts","sourceRoot":"","sources":["../../../src/str/floatingdecimal.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,gGAAgG;AAChG,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;IACpB,oCAAoC;IACpC,SAAS,EAAE,OAAO,CAAC;IACnB,mDAAmD;IACnD,KAAK,EAAE,OAAO,CAAC;CAChB;AAoBD,wBAAgB,IAAI,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAGtC;AAED,+CAA+C;AAC/C,wBAAgB,SAAS,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAI3C;AAuBD,2EAA2E;AAC3E,wBAAgB,aAAa,CAAC,CAAC,EAAE,MAAM,GAAG,eAAe,CAuJxD;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAoD9F"}
|
|
@@ -19,7 +19,9 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
19
19
|
var floatingdecimal_exports = {};
|
|
20
20
|
__export(floatingdecimal_exports, {
|
|
21
21
|
convertDouble: () => convertDouble,
|
|
22
|
-
javaFixedDigits: () => javaFixedDigits
|
|
22
|
+
javaFixedDigits: () => javaFixedDigits,
|
|
23
|
+
pow5: () => pow5,
|
|
24
|
+
trimZeros: () => trimZeros
|
|
23
25
|
});
|
|
24
26
|
module.exports = __toCommonJS(floatingdecimal_exports);
|
|
25
27
|
const EXP_SHIFT = 52;
|
|
@@ -96,10 +98,21 @@ const LONG_5_POW_LENGTH = 27;
|
|
|
96
98
|
const view = new DataView(new ArrayBuffer(8));
|
|
97
99
|
const int32 = (v) => BigInt.asIntN(32, v);
|
|
98
100
|
const int64 = (v) => BigInt.asIntN(64, v);
|
|
101
|
+
const powersOf5 = [1n];
|
|
102
|
+
function pow5(k) {
|
|
103
|
+
while (powersOf5.length <= k) powersOf5.push(powersOf5[powersOf5.length - 1] * 5n);
|
|
104
|
+
return powersOf5[k];
|
|
105
|
+
}
|
|
106
|
+
function trimZeros(s) {
|
|
107
|
+
let end = s.length;
|
|
108
|
+
while (end > 0 && s.charCodeAt(end - 1) === 48) end--;
|
|
109
|
+
return s.slice(0, end);
|
|
110
|
+
}
|
|
99
111
|
function trailingZeros(v) {
|
|
112
|
+
let x = Number(v);
|
|
100
113
|
let n = 0;
|
|
101
|
-
while (
|
|
102
|
-
|
|
114
|
+
while (x % 2 === 0) {
|
|
115
|
+
x /= 2;
|
|
103
116
|
n++;
|
|
104
117
|
}
|
|
105
118
|
return n;
|
|
@@ -143,7 +156,7 @@ function convertDouble(x) {
|
|
|
143
156
|
if (residue >= pow10 >> 1n) lvalue++;
|
|
144
157
|
}
|
|
145
158
|
const s = lvalue.toString();
|
|
146
|
-
return { digits: s
|
|
159
|
+
return { digits: trimZeros(s), decExponent: insignificant + s.length, roundedUp: false, exact: false };
|
|
147
160
|
}
|
|
148
161
|
let decExp = estimateDecExp(fractBits, binExp);
|
|
149
162
|
const B5 = Math.max(0, -decExp);
|
|
@@ -174,9 +187,9 @@ function convertDouble(x) {
|
|
|
174
187
|
const minTwo = decExp < -3 || decExp >= 8;
|
|
175
188
|
if (Bbits < 64 && tenSbits < 64) {
|
|
176
189
|
const wrap = Bbits < 32 && tenSbits < 32 ? int32 : int64;
|
|
177
|
-
let b = wrap(fractBits *
|
|
178
|
-
const s = wrap(
|
|
179
|
-
let m = wrap(
|
|
190
|
+
let b = wrap(fractBits * pow5(B5) << BigInt(B2));
|
|
191
|
+
const s = wrap(pow5(S5) << BigInt(S2));
|
|
192
|
+
let m = wrap(pow5(M5) << BigInt(M2));
|
|
180
193
|
const tens = wrap(s * 10n);
|
|
181
194
|
let q = Number(b / s);
|
|
182
195
|
b = wrap(10n * (b % s));
|
|
@@ -202,9 +215,9 @@ function convertDouble(x) {
|
|
|
202
215
|
lowDigitDifference = wrap((b << 1n) - tens);
|
|
203
216
|
exact = b === 0n;
|
|
204
217
|
} else {
|
|
205
|
-
let b = fractBits *
|
|
206
|
-
const s =
|
|
207
|
-
let m =
|
|
218
|
+
let b = fractBits * pow5(B5) << BigInt(B2);
|
|
219
|
+
const s = pow5(S5) << BigInt(S2);
|
|
220
|
+
let m = pow5(M5 + 1) << BigInt(M2 + 1);
|
|
208
221
|
const tens = s * 10n;
|
|
209
222
|
let q = Number(b / s);
|
|
210
223
|
b = b % s * 10n;
|
|
@@ -243,7 +256,7 @@ function convertDouble(x) {
|
|
|
243
256
|
if (digits[digits.length - 1] % 2 !== 0) roundup();
|
|
244
257
|
} else if (lowDigitDifference > 0n) roundup();
|
|
245
258
|
}
|
|
246
|
-
const text = digits.join("")
|
|
259
|
+
const text = trimZeros(digits.join(""));
|
|
247
260
|
return { digits: text || "0", decExponent, roundedUp, exact };
|
|
248
261
|
}
|
|
249
262
|
function javaFixedDigits(x, maxFrac) {
|
|
@@ -292,7 +305,7 @@ function javaFixedDigits(x, maxFrac) {
|
|
|
292
305
|
count = keep;
|
|
293
306
|
while (count > 1 && digits[count - 1] === 0) count--;
|
|
294
307
|
}
|
|
295
|
-
const text = digits.slice(0, count).join("")
|
|
308
|
+
const text = trimZeros(digits.slice(0, count).join(""));
|
|
296
309
|
return { digits: text, intLen: text ? decimalAt : 0 };
|
|
297
310
|
}
|
|
298
311
|
//# sourceMappingURL=floatingdecimal.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/str/floatingdecimal.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Decimal digits of a double as PineScript's plain `str.tostring` produces them.\n *\n * PineScript formats a number without a format with the digits of the classic binary to decimal conversion of the\n * JVM (the one `Double.toString` used before Java 19), then rounds them to 10 decimals half to even, with two\n * flags of the conversion deciding a tie on the last digit: digits that were rounded up are not rounded up again,\n * digits that were cut on a '5' are. These digits are not always the shortest ones: 78195689105219552 keeps all\n * its digits (the shortest form is 78195689105219550), and 1990736.000001111 has 16 digits where rounding the exact\n * value would give 1990736.0000011111 (#174).\n */\n\n/** Digits d1d2d3... of |x| = 0.d1d2d3... \u00D7 10^decExponent, with the flags of the conversion. */\nexport interface ConvertedDigits {\n digits: string;\n decExponent: number;\n /** The last digit was rounded up */\n roundedUp: boolean;\n /** The digits are the exact value of the double */\n exact: boolean;\n}\n\nconst EXP_SHIFT = 52;\nconst MAX_SMALL_BIN_EXP = 62;\nconst MIN_SMALL_BIN_EXP = -21;\n// approximately ceil(log2(5^i))\nconst N_5_BITS = [0, 3, 5, 7, 10, 12, 14, 17, 19, 21, 24, 26, 28, 31, 33, 35, 38, 40, 42, 45, 47, 49, 52, 54, 56, 59, 61];\n// number of decimal digits of 2^i minus one, for i < 64\nconst INSIGNIFICANT_DIGITS = [\n 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10,\n 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19,\n];\nconst LONG_5_POW_LENGTH = 27;\nconst view = new DataView(new ArrayBuffer(8));\n\nconst int32 = (v: bigint): bigint => BigInt.asIntN(32, v);\nconst int64 = (v: bigint): bigint => BigInt.asIntN(64, v);\n\nfunction trailingZeros(v: bigint): number {\n let n = 0;\n while ((v & 1n) === 0n) {\n v >>= 1n;\n n++;\n }\n return n;\n}\n\n/** floor(log10(x)) estimate of the conversion (it can be one too high). */\nfunction estimateDecExp(fractBits: bigint, binExp: number): number {\n view.setBigUint64(0, (1023n << 52n) | (fractBits & 0xfffffffffffffn));\n const d2 = view.getFloat64(0);\n const d = (d2 - 1.5) * 0.289529654 + 0.176091259 + binExp * 0.301029995663981;\n // the conversion truncates toward zero and corrects negative non-integers down\n const r = Math.trunc(d);\n return d < 0 && r !== d ? r - 1 : r;\n}\n\n/** Digits of a positive finite double, as the JVM converter gives them. */\nexport function convertDouble(x: number): ConvertedDigits {\n view.setFloat64(0, Math.abs(x));\n const bits = view.getBigUint64(0);\n let fractBits = bits & 0xfffffffffffffn;\n let binExp = Number((bits >> 52n) & 0x7ffn);\n if (binExp === 0 && fractBits === 0n) return { digits: '0', decExponent: 1, roundedUp: false, exact: false };\n let nSignificantBits: number;\n if (binExp === 0) {\n const leadingZeros = 64 - fractBits.toString(2).length;\n const shift = leadingZeros - (63 - EXP_SHIFT);\n fractBits <<= BigInt(shift);\n binExp = 1 - shift;\n nSignificantBits = 64 - leadingZeros;\n } else {\n fractBits |= 1n << 52n;\n nSignificantBits = EXP_SHIFT + 1;\n }\n binExp -= 1023;\n\n const tailZeros = trailingZeros(fractBits);\n const nFractBits = EXP_SHIFT + 1 - tailZeros;\n const nTinyBits = Math.max(0, nFractBits - binExp - 1);\n\n // an integer that fits in a long: its digits, the low ones rounded away when they are not significant\n if (\n binExp <= MAX_SMALL_BIN_EXP &&\n binExp >= MIN_SMALL_BIN_EXP &&\n nTinyBits < LONG_5_POW_LENGTH &&\n nFractBits + N_5_BITS[nTinyBits]! < 64 &&\n nTinyBits === 0\n ) {\n const p2 = binExp - nSignificantBits - 1;\n const insignificant = binExp > nSignificantBits && p2 > 1 && p2 < INSIGNIFICANT_DIGITS.length ? INSIGNIFICANT_DIGITS[p2]! : 0;\n let lvalue = binExp >= EXP_SHIFT ? fractBits << BigInt(binExp - EXP_SHIFT) : fractBits >> BigInt(EXP_SHIFT - binExp);\n if (insignificant !== 0) {\n const pow10 = 10n ** BigInt(insignificant);\n const residue = lvalue % pow10;\n lvalue /= pow10;\n if (residue >= pow10 >> 1n) lvalue++;\n }\n const s = lvalue.toString();\n return { digits: s.replace(/0+$/, ''), decExponent: insignificant + s.length, roundedUp: false, exact: false };\n }\n\n let decExp = estimateDecExp(fractBits, binExp);\n const B5 = Math.max(0, -decExp);\n let B2 = B5 + nTinyBits + binExp;\n const S5 = Math.max(0, decExp);\n let S2 = S5 + nTinyBits;\n const M5 = B5;\n let M2 = B2 - nSignificantBits;\n\n fractBits >>= BigInt(tailZeros);\n B2 -= nFractBits - 1;\n const common2factor = Math.min(B2, S2);\n B2 -= common2factor;\n S2 -= common2factor;\n M2 -= common2factor;\n // an exact power of two: the next smaller double is half as far\n if (nFractBits === 1) M2 -= 1;\n if (M2 < 0) {\n B2 -= M2;\n S2 -= M2;\n M2 = 0;\n }\n\n const digits: number[] = [];\n let low: boolean;\n let high: boolean;\n let lowDigitDifference: bigint;\n let exact: boolean;\n const Bbits = nFractBits + B2 + (B5 < N_5_BITS.length ? N_5_BITS[B5]! : B5 * 3);\n const tenSbits = S2 + 1 + (S5 + 1 < N_5_BITS.length ? N_5_BITS[S5 + 1]! : (S5 + 1) * 3);\n // two digits at least in the exponent form\n const minTwo = decExp < -3 || decExp >= 8;\n\n if (Bbits < 64 && tenSbits < 64) {\n // int or long arithmetic, with its overflows\n const wrap = Bbits < 32 && tenSbits < 32 ? int32 : int64;\n let b = wrap((fractBits * 5n ** BigInt(B5)) << BigInt(B2));\n const s = wrap(5n ** BigInt(S5) << BigInt(S2));\n let m = wrap(5n ** BigInt(M5) << BigInt(M2));\n const tens = wrap(s * 10n);\n let q = Number(b / s);\n b = wrap(10n * (b % s));\n m = wrap(m * 10n);\n low = b < m;\n high = wrap(b + m) > tens;\n if (q === 0 && !high) decExp--;\n else digits.push(q);\n if (minTwo) high = low = false;\n while (!low && !high) {\n q = Number(b / s);\n b = wrap(10n * (b % s));\n m = wrap(m * 10n);\n if (m > 0n) {\n low = b < m;\n high = wrap(b + m) > tens;\n } else {\n low = true;\n high = true;\n }\n digits.push(q);\n }\n lowDigitDifference = wrap((b << 1n) - tens);\n exact = b === 0n;\n } else {\n let b = (fractBits * 5n ** BigInt(B5)) << BigInt(B2);\n const s = 5n ** BigInt(S5) << BigInt(S2);\n let m = 5n ** BigInt(M5 + 1) << BigInt(M2 + 1);\n const tens = s * 10n;\n let q = Number(b / s);\n b = (b % s) * 10n;\n low = b < m;\n high = b + m >= tens;\n if (q === 0 && !high) decExp--;\n else digits.push(q);\n if (minTwo) high = low = false;\n while (!low && !high) {\n q = Number(b / s);\n b = (b % s) * 10n;\n m *= 10n;\n low = b < m;\n high = b + m >= tens;\n digits.push(q);\n }\n lowDigitDifference = high && low ? (b << 1n) - tens : 0n;\n exact = b === 0n;\n }\n\n let decExponent = decExp + 1;\n let roundedUp = false;\n const roundup = (): void => {\n let i = digits.length - 1;\n while (digits[i] === 9 && i > 0) digits[i--] = 0;\n if (digits[i] === 9) {\n decExponent += 1;\n digits[0] = 1;\n return;\n }\n digits[i]! += 1;\n roundedUp = true;\n };\n if (high) {\n if (!low) roundup();\n else if (lowDigitDifference === 0n) {\n if (digits[digits.length - 1]! % 2 !== 0) roundup();\n } else if (lowDigitDifference > 0n) roundup();\n }\n const text = digits.join('').replace(/0+$/, '');\n return { digits: text || '0', decExponent, roundedUp, exact };\n}\n\n/**\n * `|x|` with at most `maxFrac` decimals, as the JVM's decimal formatter rounds the converted digits (half to even;\n * a tie on the last converted digit is decided by the conversion flags). Returns the digits and the position of the\n * decimal point (value = 0.digits \u00D7 10^intLen); \"\" for zero.\n */\nexport function javaFixedDigits(x: number, maxFrac: number): { digits: string; intLen: number } {\n if (x === 0) return { digits: '', intLen: 0 };\n const c = convertDouble(x);\n const digits = [...c.digits].map(Number);\n let decimalAt = c.decExponent;\n // the formatter reads the conversion's text, which ends in \".0\" when no digit follows the point (\"5.0E-11\",\n // \"120.0\"): that zero is a digit for the tie test below (5e-11 to 10 decimals gives 0)\n const n = digits.length;\n if (decimalAt > 0 && decimalAt < 8) {\n if (n <= decimalAt) digits.push(...Array<number>(decimalAt - n + 1).fill(0));\n } else if (decimalAt <= -3 || decimalAt >= 8) {\n if (n === 1) digits.push(0);\n }\n let count = digits.length;\n\n const shouldRoundUp = (keep: number): boolean => {\n if (keep >= count) return false;\n if (digits[keep]! > 5) return true;\n if (digits[keep] !== 5) return false;\n if (keep === count - 1) {\n if (c.exact) return keep > 0 && digits[keep - 1]! % 2 !== 0;\n return !c.roundedUp;\n }\n for (let i = keep + 1; i < count; i++) if (digits[i] !== 0) return true;\n return false;\n };\n\n if (-decimalAt > maxFrac) return { digits: '', intLen: 0 };\n if (-decimalAt === maxFrac) {\n return shouldRoundUp(0) ? { digits: '1', intLen: decimalAt + 1 } : { digits: '', intLen: 0 };\n }\n while (count > 1 && digits[count - 1] === 0) count--;\n let keep = maxFrac + decimalAt;\n if (keep >= 0 && keep < count) {\n if (shouldRoundUp(keep)) {\n do {\n keep--;\n if (keep < 0) {\n digits[0] = 1;\n decimalAt++;\n keep = 0;\n break;\n }\n digits[keep]! += 1;\n } while (digits[keep]! > 9);\n keep++;\n }\n count = keep;\n while (count > 1 && digits[count - 1] === 0) count--;\n }\n const text = digits.slice(0, count).join('').replace(/0+$/, '');\n return { digits: text, intLen: text ? decimalAt : 0 };\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBA,MAAM,YAAY;AAClB,MAAM,oBAAoB;AAC1B,MAAM,oBAAoB;AAE1B,MAAM,WAAW,CAAC,GAAG,GAAG,GAAG,GAAG,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,EAAE;AAExH,MAAM,uBAAuB;AAAA,EAC3B;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAI;AAAA,EAAI;AAAA,EAC9G;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAAA,EAAI;AAC1G;AACA,MAAM,oBAAoB;AAC1B,MAAM,OAAO,IAAI,SAAS,IAAI,YAAY,CAAC,CAAC;AAE5C,MAAM,QAAQ,CAAC,MAAsB,OAAO,OAAO,IAAI,CAAC;AACxD,MAAM,QAAQ,CAAC,MAAsB,OAAO,OAAO,IAAI,CAAC;
|
|
4
|
+
"sourcesContent": ["/**\n * Decimal digits of a double as PineScript's plain `str.tostring` produces them.\n *\n * PineScript formats a number without a format with the digits of the classic binary to decimal conversion of the\n * JVM (the one `Double.toString` used before Java 19), then rounds them to 10 decimals half to even, with two\n * flags of the conversion deciding a tie on the last digit: digits that were rounded up are not rounded up again,\n * digits that were cut on a '5' are. These digits are not always the shortest ones: 78195689105219552 keeps all\n * its digits (the shortest form is 78195689105219550), and 1990736.000001111 has 16 digits where rounding the exact\n * value would give 1990736.0000011111 (#174).\n */\n\n/** Digits d1d2d3... of |x| = 0.d1d2d3... \u00D7 10^decExponent, with the flags of the conversion. */\nexport interface ConvertedDigits {\n digits: string;\n decExponent: number;\n /** The last digit was rounded up */\n roundedUp: boolean;\n /** The digits are the exact value of the double */\n exact: boolean;\n}\n\nconst EXP_SHIFT = 52;\nconst MAX_SMALL_BIN_EXP = 62;\nconst MIN_SMALL_BIN_EXP = -21;\n// approximately ceil(log2(5^i))\nconst N_5_BITS = [0, 3, 5, 7, 10, 12, 14, 17, 19, 21, 24, 26, 28, 31, 33, 35, 38, 40, 42, 45, 47, 49, 52, 54, 56, 59, 61];\n// number of decimal digits of 2^i minus one, for i < 64\nconst INSIGNIFICANT_DIGITS = [\n 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10,\n 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19,\n];\nconst LONG_5_POW_LENGTH = 27;\nconst view = new DataView(new ArrayBuffer(8));\n\nconst int32 = (v: bigint): bigint => BigInt.asIntN(32, v);\nconst int64 = (v: bigint): bigint => BigInt.asIntN(64, v);\n\n/** 5^k, made once (k up to 1074, the binary exponents of the doubles). */\nconst powersOf5: bigint[] = [1n];\nexport function pow5(k: number): bigint {\n while (powersOf5.length <= k) powersOf5.push(powersOf5[powersOf5.length - 1]! * 5n);\n return powersOf5[k]!;\n}\n\n/** `s` without its trailing '0' characters. */\nexport function trimZeros(s: string): string {\n let end = s.length;\n while (end > 0 && s.charCodeAt(end - 1) === 48) end--;\n return s.slice(0, end);\n}\n\n/** Trailing zero bits of a significand (not 0, below 2^53: exact as a double). */\nfunction trailingZeros(v: bigint): number {\n let x = Number(v);\n let n = 0;\n while (x % 2 === 0) {\n x /= 2;\n n++;\n }\n return n;\n}\n\n/** floor(log10(x)) estimate of the conversion (it can be one too high). */\nfunction estimateDecExp(fractBits: bigint, binExp: number): number {\n view.setBigUint64(0, (1023n << 52n) | (fractBits & 0xfffffffffffffn));\n const d2 = view.getFloat64(0);\n const d = (d2 - 1.5) * 0.289529654 + 0.176091259 + binExp * 0.301029995663981;\n // the conversion truncates toward zero and corrects negative non-integers down\n const r = Math.trunc(d);\n return d < 0 && r !== d ? r - 1 : r;\n}\n\n/** Digits of a positive finite double, as the JVM converter gives them. */\nexport function convertDouble(x: number): ConvertedDigits {\n view.setFloat64(0, Math.abs(x));\n const bits = view.getBigUint64(0);\n let fractBits = bits & 0xfffffffffffffn;\n let binExp = Number((bits >> 52n) & 0x7ffn);\n if (binExp === 0 && fractBits === 0n) return { digits: '0', decExponent: 1, roundedUp: false, exact: false };\n let nSignificantBits: number;\n if (binExp === 0) {\n const leadingZeros = 64 - fractBits.toString(2).length;\n const shift = leadingZeros - (63 - EXP_SHIFT);\n fractBits <<= BigInt(shift);\n binExp = 1 - shift;\n nSignificantBits = 64 - leadingZeros;\n } else {\n fractBits |= 1n << 52n;\n nSignificantBits = EXP_SHIFT + 1;\n }\n binExp -= 1023;\n\n const tailZeros = trailingZeros(fractBits);\n const nFractBits = EXP_SHIFT + 1 - tailZeros;\n const nTinyBits = Math.max(0, nFractBits - binExp - 1);\n\n // an integer that fits in a long: its digits, the low ones rounded away when they are not significant\n if (\n binExp <= MAX_SMALL_BIN_EXP &&\n binExp >= MIN_SMALL_BIN_EXP &&\n nTinyBits < LONG_5_POW_LENGTH &&\n nFractBits + N_5_BITS[nTinyBits]! < 64 &&\n nTinyBits === 0\n ) {\n const p2 = binExp - nSignificantBits - 1;\n const insignificant = binExp > nSignificantBits && p2 > 1 && p2 < INSIGNIFICANT_DIGITS.length ? INSIGNIFICANT_DIGITS[p2]! : 0;\n let lvalue = binExp >= EXP_SHIFT ? fractBits << BigInt(binExp - EXP_SHIFT) : fractBits >> BigInt(EXP_SHIFT - binExp);\n if (insignificant !== 0) {\n const pow10 = 10n ** BigInt(insignificant);\n const residue = lvalue % pow10;\n lvalue /= pow10;\n if (residue >= pow10 >> 1n) lvalue++;\n }\n const s = lvalue.toString();\n return { digits: trimZeros(s), decExponent: insignificant + s.length, roundedUp: false, exact: false };\n }\n\n let decExp = estimateDecExp(fractBits, binExp);\n const B5 = Math.max(0, -decExp);\n let B2 = B5 + nTinyBits + binExp;\n const S5 = Math.max(0, decExp);\n let S2 = S5 + nTinyBits;\n const M5 = B5;\n let M2 = B2 - nSignificantBits;\n\n fractBits >>= BigInt(tailZeros);\n B2 -= nFractBits - 1;\n const common2factor = Math.min(B2, S2);\n B2 -= common2factor;\n S2 -= common2factor;\n M2 -= common2factor;\n // an exact power of two: the next smaller double is half as far\n if (nFractBits === 1) M2 -= 1;\n if (M2 < 0) {\n B2 -= M2;\n S2 -= M2;\n M2 = 0;\n }\n\n const digits: number[] = [];\n let low: boolean;\n let high: boolean;\n let lowDigitDifference: bigint;\n let exact: boolean;\n const Bbits = nFractBits + B2 + (B5 < N_5_BITS.length ? N_5_BITS[B5]! : B5 * 3);\n const tenSbits = S2 + 1 + (S5 + 1 < N_5_BITS.length ? N_5_BITS[S5 + 1]! : (S5 + 1) * 3);\n // two digits at least in the exponent form\n const minTwo = decExp < -3 || decExp >= 8;\n\n if (Bbits < 64 && tenSbits < 64) {\n // int or long arithmetic, with its overflows\n const wrap = Bbits < 32 && tenSbits < 32 ? int32 : int64;\n let b = wrap((fractBits * pow5(B5)) << BigInt(B2));\n const s = wrap(pow5(S5) << BigInt(S2));\n let m = wrap(pow5(M5) << BigInt(M2));\n const tens = wrap(s * 10n);\n let q = Number(b / s);\n b = wrap(10n * (b % s));\n m = wrap(m * 10n);\n low = b < m;\n high = wrap(b + m) > tens;\n if (q === 0 && !high) decExp--;\n else digits.push(q);\n if (minTwo) high = low = false;\n while (!low && !high) {\n q = Number(b / s);\n b = wrap(10n * (b % s));\n m = wrap(m * 10n);\n if (m > 0n) {\n low = b < m;\n high = wrap(b + m) > tens;\n } else {\n low = true;\n high = true;\n }\n digits.push(q);\n }\n lowDigitDifference = wrap((b << 1n) - tens);\n exact = b === 0n;\n } else {\n let b = (fractBits * pow5(B5)) << BigInt(B2);\n const s = pow5(S5) << BigInt(S2);\n let m = pow5(M5 + 1) << BigInt(M2 + 1);\n const tens = s * 10n;\n let q = Number(b / s);\n b = (b % s) * 10n;\n low = b < m;\n high = b + m >= tens;\n if (q === 0 && !high) decExp--;\n else digits.push(q);\n if (minTwo) high = low = false;\n while (!low && !high) {\n q = Number(b / s);\n b = (b % s) * 10n;\n m *= 10n;\n low = b < m;\n high = b + m >= tens;\n digits.push(q);\n }\n lowDigitDifference = high && low ? (b << 1n) - tens : 0n;\n exact = b === 0n;\n }\n\n let decExponent = decExp + 1;\n let roundedUp = false;\n const roundup = (): void => {\n let i = digits.length - 1;\n while (digits[i] === 9 && i > 0) digits[i--] = 0;\n if (digits[i] === 9) {\n decExponent += 1;\n digits[0] = 1;\n return;\n }\n digits[i]! += 1;\n roundedUp = true;\n };\n if (high) {\n if (!low) roundup();\n else if (lowDigitDifference === 0n) {\n if (digits[digits.length - 1]! % 2 !== 0) roundup();\n } else if (lowDigitDifference > 0n) roundup();\n }\n const text = trimZeros(digits.join(''));\n return { digits: text || '0', decExponent, roundedUp, exact };\n}\n\n/**\n * `|x|` with at most `maxFrac` decimals, as the JVM's decimal formatter rounds the converted digits (half to even;\n * a tie on the last converted digit is decided by the conversion flags). Returns the digits and the position of the\n * decimal point (value = 0.digits \u00D7 10^intLen); \"\" for zero.\n */\nexport function javaFixedDigits(x: number, maxFrac: number): { digits: string; intLen: number } {\n if (x === 0) return { digits: '', intLen: 0 };\n const c = convertDouble(x);\n const digits = [...c.digits].map(Number);\n let decimalAt = c.decExponent;\n // the formatter reads the conversion's text, which ends in \".0\" when no digit follows the point (\"5.0E-11\",\n // \"120.0\"): that zero is a digit for the tie test below (5e-11 to 10 decimals gives 0)\n const n = digits.length;\n if (decimalAt > 0 && decimalAt < 8) {\n if (n <= decimalAt) digits.push(...Array<number>(decimalAt - n + 1).fill(0));\n } else if (decimalAt <= -3 || decimalAt >= 8) {\n if (n === 1) digits.push(0);\n }\n let count = digits.length;\n\n const shouldRoundUp = (keep: number): boolean => {\n if (keep >= count) return false;\n if (digits[keep]! > 5) return true;\n if (digits[keep] !== 5) return false;\n if (keep === count - 1) {\n if (c.exact) return keep > 0 && digits[keep - 1]! % 2 !== 0;\n return !c.roundedUp;\n }\n for (let i = keep + 1; i < count; i++) if (digits[i] !== 0) return true;\n return false;\n };\n\n if (-decimalAt > maxFrac) return { digits: '', intLen: 0 };\n if (-decimalAt === maxFrac) {\n return shouldRoundUp(0) ? { digits: '1', intLen: decimalAt + 1 } : { digits: '', intLen: 0 };\n }\n while (count > 1 && digits[count - 1] === 0) count--;\n let keep = maxFrac + decimalAt;\n if (keep >= 0 && keep < count) {\n if (shouldRoundUp(keep)) {\n do {\n keep--;\n if (keep < 0) {\n digits[0] = 1;\n decimalAt++;\n keep = 0;\n break;\n }\n digits[keep]! += 1;\n } while (digits[keep]! > 9);\n keep++;\n }\n count = keep;\n while (count > 1 && digits[count - 1] === 0) count--;\n }\n const text = trimZeros(digits.slice(0, count).join(''));\n return { digits: text, intLen: text ? decimalAt : 0 };\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBA,MAAM,YAAY;AAClB,MAAM,oBAAoB;AAC1B,MAAM,oBAAoB;AAE1B,MAAM,WAAW,CAAC,GAAG,GAAG,GAAG,GAAG,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,EAAE;AAExH,MAAM,uBAAuB;AAAA,EAC3B;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG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AAK,MAAM;AAC1D,aAAO,CAAC,EAAE;AAAA,IACZ;AACA,aAAS,IAAIA,QAAO,GAAG,IAAI,OAAO,IAAK,KAAI,OAAO,CAAC,MAAM,EAAG,QAAO;AACnE,WAAO;AAAA,EACT;AAEA,MAAI,CAAC,YAAY,QAAS,QAAO,EAAE,QAAQ,IAAI,QAAQ,EAAE;AACzD,MAAI,CAAC,cAAc,SAAS;AAC1B,WAAO,cAAc,CAAC,IAAI,EAAE,QAAQ,KAAK,QAAQ,YAAY,EAAE,IAAI,EAAE,QAAQ,IAAI,QAAQ,EAAE;AAAA,EAC7F;AACA,SAAO,QAAQ,KAAK,OAAO,QAAQ,CAAC,MAAM,EAAG;AAC7C,MAAI,OAAO,UAAU;AACrB,MAAI,QAAQ,KAAK,OAAO,OAAO;AAC7B,QAAI,cAAc,IAAI,GAAG;AACvB,SAAG;AACD;AACA,YAAI,OAAO,GAAG;AACZ,iBAAO,CAAC,IAAI;AACZ;AACA,iBAAO;AACP;AAAA,QACF;AACA,eAAO,IAAI,KAAM;AAAA,MACnB,SAAS,OAAO,IAAI,IAAK;AACzB;AAAA,IACF;AACA,YAAQ;AACR,WAAO,QAAQ,KAAK,OAAO,QAAQ,CAAC,MAAM,EAAG;AAAA,EAC/C;AACA,QAAM,OAAO,UAAU,OAAO,MAAM,GAAG,KAAK,EAAE,KAAK,EAAE,CAAC;AACtD,SAAO,EAAE,QAAQ,MAAM,QAAQ,OAAO,YAAY,EAAE;AACtD;",
|
|
6
6
|
"names": ["keep"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messageformat.d.ts","sourceRoot":"","sources":["../../../src/str/messageformat.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;
|
|
1
|
+
{"version":3,"file":"messageformat.d.ts","sourceRoot":"","sources":["../../../src/str/messageformat.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AA0HH,6HAA6H;AAC7H,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,QAAQ,EAAE,MAAM,GAAG,CAAC,MAAM,MAAM,CAAC,GAAG,MAAM,CAUzG"}
|
|
@@ -76,23 +76,28 @@ function formatArgument(value, type, style, timezone) {
|
|
|
76
76
|
throw new SyntaxError(`Unknown format type "${type}"`);
|
|
77
77
|
}
|
|
78
78
|
}
|
|
79
|
-
|
|
80
|
-
|
|
79
|
+
const templates = /* @__PURE__ */ new Map();
|
|
80
|
+
const MAX_TEMPLATES = 1e3;
|
|
81
|
+
function parseTemplate(pattern) {
|
|
82
|
+
const cached = templates.get(pattern);
|
|
83
|
+
if (cached) return cached;
|
|
84
|
+
const parts = [];
|
|
85
|
+
let text = "";
|
|
81
86
|
for (let i = 0; i < pattern.length; ) {
|
|
82
87
|
const ch = pattern[i];
|
|
83
88
|
if (ch === "'") {
|
|
84
89
|
if (pattern[i + 1] === "'") {
|
|
85
|
-
|
|
90
|
+
text += "'";
|
|
86
91
|
i += 2;
|
|
87
92
|
continue;
|
|
88
93
|
}
|
|
89
94
|
const end = pattern.indexOf("'", i + 1);
|
|
90
|
-
|
|
95
|
+
text += pattern.slice(i + 1, end === -1 ? void 0 : end);
|
|
91
96
|
i = end === -1 ? pattern.length : end + 1;
|
|
92
97
|
continue;
|
|
93
98
|
}
|
|
94
99
|
if (ch !== "{") {
|
|
95
|
-
|
|
100
|
+
text += ch;
|
|
96
101
|
i++;
|
|
97
102
|
continue;
|
|
98
103
|
}
|
|
@@ -107,11 +112,25 @@ function formatMessage(pattern, args, timezone) {
|
|
|
107
112
|
}
|
|
108
113
|
const inner = pattern.slice(i + 1, j - 1);
|
|
109
114
|
const [index = "", type, ...rest] = inner.split(",");
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
115
|
+
if (text) parts.push(text);
|
|
116
|
+
text = "";
|
|
117
|
+
parts.push({ inner, index: Number(index.trim()), type, style: rest.length ? rest.join(",") : void 0 });
|
|
113
118
|
i = j;
|
|
114
119
|
}
|
|
120
|
+
if (text) parts.push(text);
|
|
121
|
+
if (templates.size >= MAX_TEMPLATES) templates.clear();
|
|
122
|
+
templates.set(pattern, parts);
|
|
123
|
+
return parts;
|
|
124
|
+
}
|
|
125
|
+
function formatMessage(pattern, args, timezone) {
|
|
126
|
+
let out = "";
|
|
127
|
+
for (const part of parseTemplate(pattern)) {
|
|
128
|
+
if (typeof part === "string") out += part;
|
|
129
|
+
else {
|
|
130
|
+
const n = part.index;
|
|
131
|
+
out += n < args.length ? formatArgument(args[n], part.type, part.style, timezone) : `{${part.inner}}`;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
115
134
|
return out;
|
|
116
135
|
}
|
|
117
136
|
//# sourceMappingURL=messageformat.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/str/messageformat.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * `str.format` patterns as PineScript formats them (Java MessageFormat):\n *\n * - `{n}` inserts argument n; numbers use \"#,##0.###\" (1234.5678 gives \"1,234.568\"); an array gives\n * \"[Hello, World!]\"\n * - `{n,number}`, `{n,number,integer}` (\"#,##0\"), `{n,number,percent}` (\"#,##0%\"),\n * `{n,number,currency}` (\"$1,234.57\", \"-$7.00\"), `{n,number,<pattern>}`\n * - `{n,date}`, `{n,time}`, `{n,date,<pattern>}`, `{n,time,<pattern>}` (styles short, medium, long, full)\n * - `{n,choice,0#zero|1#one|1<many}`\n * - numbers round half to even on the exact binary value (0.5 as integer gives \"0\")\n * - `'...'` is literal text and `''` is a quote; a missing argument leaves `{n}` in the text\n */\n\nimport { formatNumber } from './numberformat.js';\nimport { formatDate } from './dateformat.js';\n\nconst DATE_STYLES: Record<string, string> = {\n short: 'M/d/yy', medium: 'MMM d, yyyy', long: 'MMMM d, yyyy', full: 'EEEE, MMMM d, yyyy',\n};\n// PineScript writes a narrow no-break space (U+202F) before AM/PM in the time styles\nconst TIME_STYLES: Record<string, string> = {\n short: 'h:mm\u202Fa', medium: 'h:mm:ss\u202Fa', long: 'h:mm:ss\u202Fa z', full: 'h:mm:ss\u202Fa z',\n};\n\nfunction number(value: unknown, pattern: string): string {\n return typeof value === 'number' ? formatNumber(value, pattern, 'halfEvenExact') : String(value);\n}\n\nfunction choice(value: number, spec: string): string {\n const options = spec.split('|').map((part) => {\n const m = /^\\s*(-?[\\d.]+|-?\u221E)\\s*([#<\u2264])(.*)$/.exec(part);\n if (!m) throw new SyntaxError(`Invalid choice format \"${spec}\"`);\n const limit = m[1]!.includes('\u221E') ? (m[1]!.startsWith('-') ? -Infinity : Infinity) : Number(m[1]);\n return { limit: m[2] === '<' ? limit + Number.EPSILON * Math.max(1, Math.abs(limit)) : limit, text: m[3]! };\n });\n let chosen = options[0]!;\n for (const o of options) if (value >= o.limit) chosen = o;\n return chosen.text;\n}\n\nfunction formatArgument(\n value: unknown,\n type: string | undefined,\n style: string | undefined,\n timezone: string | (() => string)\n): string {\n if (value === undefined) return '';\n if (!type) {\n // an array gives \"[a, b]\" (PineScript); the element format of numbers is not measured: plain JS text\n if (Array.isArray(value)) return '[' + value.map((v) => (v == null ? 'NaN' : String(v))).join(', ') + ']';\n return typeof value === 'number' ? number(value, '#,##0.###') : String(value);\n }\n switch (type.trim()) {\n case 'number': {\n const s = style?.trim();\n if (!s) return number(value, '#,##0.###');\n if (s === 'integer') return number(value, '#,##0');\n if (s === 'percent') return number(value, '#,##0%');\n if (s === 'currency') return number(value, \"'$'#,##0.00\");\n return number(value, style!);\n }\n case 'date':\n case 'time': {\n const styles = type.trim() === 'date' ? DATE_STYLES : TIME_STYLES;\n const s = style?.trim() ?? 'medium';\n return formatDate(Number(value), styles[s] ?? style!, typeof timezone === 'function' ? timezone() : timezone);\n }\n case 'choice':\n return choice(Number(value), style ?? '');\n default:\n throw new SyntaxError(`Unknown format type \"${type}\"`);\n }\n}\n\n/**
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;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AAO,WAAW,IAAI,OAAO,KAAK;AAAA,EAC9E;AACA,UAAQ,KAAK,KAAK,GAAG;AAAA,IACnB,KAAK,UAAU;AACb,YAAM,IAAI,OAAO,KAAK;AACtB,UAAI,CAAC,EAAG,QAAO,OAAO,OAAO,WAAW;AACxC,UAAI,MAAM,UAAW,QAAO,OAAO,OAAO,OAAO;AACjD,UAAI,MAAM,UAAW,QAAO,OAAO,OAAO,QAAQ;AAClD,UAAI,MAAM,WAAY,QAAO,OAAO,OAAO,aAAa;AACxD,aAAO,OAAO,OAAO,KAAM;AAAA,IAC7B;AAAA,IACA,KAAK;AAAA,IACL,KAAK,QAAQ;AACX,YAAM,SAAS,KAAK,KAAK,MAAM,SAAS,cAAc;AACtD,YAAM,IAAI,OAAO,KAAK,KAAK;AAC3B,iBAAO,8BAAW,OAAO,KAAK,GAAG,OAAO,CAAC,KAAK,OAAQ,OAAO,aAAa,aAAa,SAAS,IAAI,QAAQ;AAAA,IAC9G;AAAA,IACA,KAAK;AACH,aAAO,OAAO,OAAO,KAAK,GAAG,SAAS,EAAE;AAAA,IAC1C;AACE,YAAM,IAAI,YAAY,wBAAwB,IAAI,GAAG;AAAA,EACzD;AACF;
|
|
4
|
+
"sourcesContent": ["/**\n * `str.format` patterns as PineScript formats them (Java MessageFormat):\n *\n * - `{n}` inserts argument n; numbers use \"#,##0.###\" (1234.5678 gives \"1,234.568\"); an array gives\n * \"[Hello, World!]\"\n * - `{n,number}`, `{n,number,integer}` (\"#,##0\"), `{n,number,percent}` (\"#,##0%\"),\n * `{n,number,currency}` (\"$1,234.57\", \"-$7.00\"), `{n,number,<pattern>}`\n * - `{n,date}`, `{n,time}`, `{n,date,<pattern>}`, `{n,time,<pattern>}` (styles short, medium, long, full)\n * - `{n,choice,0#zero|1#one|1<many}`\n * - numbers round half to even on the exact binary value (0.5 as integer gives \"0\")\n * - `'...'` is literal text and `''` is a quote; a missing argument leaves `{n}` in the text\n */\n\nimport { formatNumber } from './numberformat.js';\nimport { formatDate } from './dateformat.js';\n\nconst DATE_STYLES: Record<string, string> = {\n short: 'M/d/yy', medium: 'MMM d, yyyy', long: 'MMMM d, yyyy', full: 'EEEE, MMMM d, yyyy',\n};\n// PineScript writes a narrow no-break space (U+202F) before AM/PM in the time styles\nconst TIME_STYLES: Record<string, string> = {\n short: 'h:mm\u202Fa', medium: 'h:mm:ss\u202Fa', long: 'h:mm:ss\u202Fa z', full: 'h:mm:ss\u202Fa z',\n};\n\nfunction number(value: unknown, pattern: string): string {\n return typeof value === 'number' ? formatNumber(value, pattern, 'halfEvenExact') : String(value);\n}\n\nfunction choice(value: number, spec: string): string {\n const options = spec.split('|').map((part) => {\n const m = /^\\s*(-?[\\d.]+|-?\u221E)\\s*([#<\u2264])(.*)$/.exec(part);\n if (!m) throw new SyntaxError(`Invalid choice format \"${spec}\"`);\n const limit = m[1]!.includes('\u221E') ? (m[1]!.startsWith('-') ? -Infinity : Infinity) : Number(m[1]);\n return { limit: m[2] === '<' ? limit + Number.EPSILON * Math.max(1, Math.abs(limit)) : limit, text: m[3]! };\n });\n let chosen = options[0]!;\n for (const o of options) if (value >= o.limit) chosen = o;\n return chosen.text;\n}\n\nfunction formatArgument(\n value: unknown,\n type: string | undefined,\n style: string | undefined,\n timezone: string | (() => string)\n): string {\n if (value === undefined) return '';\n if (!type) {\n // an array gives \"[a, b]\" (PineScript); the element format of numbers is not measured: plain JS text\n if (Array.isArray(value)) return '[' + value.map((v) => (v == null ? 'NaN' : String(v))).join(', ') + ']';\n return typeof value === 'number' ? number(value, '#,##0.###') : String(value);\n }\n switch (type.trim()) {\n case 'number': {\n const s = style?.trim();\n if (!s) return number(value, '#,##0.###');\n if (s === 'integer') return number(value, '#,##0');\n if (s === 'percent') return number(value, '#,##0%');\n if (s === 'currency') return number(value, \"'$'#,##0.00\");\n return number(value, style!);\n }\n case 'date':\n case 'time': {\n const styles = type.trim() === 'date' ? DATE_STYLES : TIME_STYLES;\n const s = style?.trim() ?? 'medium';\n return formatDate(Number(value), styles[s] ?? style!, typeof timezone === 'function' ? timezone() : timezone);\n }\n case 'choice':\n return choice(Number(value), style ?? '');\n default:\n throw new SyntaxError(`Unknown format type \"${type}\"`);\n }\n}\n\n/** A `{index[,type[,style]]}` element of a pattern; `inner` is the text between the braces. */\ninterface Placeholder {\n inner: string;\n index: number;\n type: string | undefined;\n style: string | undefined;\n}\n\n/** Parsed patterns (literal text and placeholders): a script formats the same pattern on every bar. */\nconst templates = new Map<string, Array<string | Placeholder>>();\n/** Cached patterns before the cache restarts. */\nconst MAX_TEMPLATES = 1000;\n\nfunction parseTemplate(pattern: string): Array<string | Placeholder> {\n const cached = templates.get(pattern);\n if (cached) return cached;\n const parts: Array<string | Placeholder> = [];\n let text = '';\n for (let i = 0; i < pattern.length; ) {\n const ch = pattern[i]!;\n if (ch === \"'\") {\n if (pattern[i + 1] === \"'\") {\n text += \"'\";\n i += 2;\n continue;\n }\n const end = pattern.indexOf(\"'\", i + 1);\n text += pattern.slice(i + 1, end === -1 ? undefined : end);\n i = end === -1 ? pattern.length : end + 1;\n continue;\n }\n if (ch !== '{') {\n text += ch;\n i++;\n continue;\n }\n // {index[,type[,style]]}; the style may contain quoted text and nested braces\n let depth = 1;\n let j = i + 1;\n let inQuote = false;\n for (; j < pattern.length && depth > 0; j++) {\n const c = pattern[j];\n if (c === \"'\") inQuote = !inQuote;\n else if (!inQuote && c === '{') depth++;\n else if (!inQuote && c === '}') depth--;\n }\n const inner = pattern.slice(i + 1, j - 1);\n const [index = '', type, ...rest] = inner.split(',');\n if (text) parts.push(text);\n text = '';\n parts.push({ inner, index: Number(index.trim()), type, style: rest.length ? rest.join(',') : undefined });\n i = j;\n }\n if (text) parts.push(text);\n if (templates.size >= MAX_TEMPLATES) templates.clear();\n templates.set(pattern, parts);\n return parts;\n}\n\n/** Formats `pattern` with `args` like PineScript `str.format`; dates use `timezone` (read only when a date is formatted). */\nexport function formatMessage(pattern: string, args: unknown[], timezone: string | (() => string)): string {\n let out = '';\n for (const part of parseTemplate(pattern)) {\n if (typeof part === 'string') out += part;\n else {\n const n = part.index;\n out += n < args.length ? formatArgument(args[n], part.type, part.style, timezone) : `{${part.inner}}`;\n }\n }\n return out;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAaA,0BAA6B;AAC7B,wBAA2B;AAE3B,MAAM,cAAsC;AAAA,EAC1C,OAAO;AAAA,EAAU,QAAQ;AAAA,EAAe,MAAM;AAAA,EAAgB,MAAM;AACtE;AAEA,MAAM,cAAsC;AAAA,EAC1C,OAAO;AAAA,EAAU,QAAQ;AAAA,EAAa,MAAM;AAAA,EAAe,MAAM;AACnE;AAEA,SAAS,OAAO,OAAgB,SAAyB;AACvD,SAAO,OAAO,UAAU,eAAW,kCAAa,OAAO,SAAS,eAAe,IAAI,OAAO,KAAK;AACjG;AAEA,SAAS,OAAO,OAAe,MAAsB;AACnD,QAAM,UAAU,KAAK,MAAM,GAAG,EAAE,IAAI,CAAC,SAAS;AAC5C,UAAM,IAAI,oCAAoC,KAAK,IAAI;AACvD,QAAI,CAAC,EAAG,OAAM,IAAI,YAAY,0BAA0B,IAAI,GAAG;AAC/D,UAAM,QAAQ,EAAE,CAAC,EAAG,SAAS,QAAG,IAAK,EAAE,CAAC,EAAG,WAAW,GAAG,IAAI,YAAY,WAAY,OAAO,EAAE,CAAC,CAAC;AAChG,WAAO,EAAE,OAAO,EAAE,CAAC,MAAM,MAAM,QAAQ,OAAO,UAAU,KAAK,IAAI,GAAG,KAAK,IAAI,KAAK,CAAC,IAAI,OAAO,MAAM,EAAE,CAAC,EAAG;AAAA,EAC5G,CAAC;AACD,MAAI,SAAS,QAAQ,CAAC;AACtB,aAAW,KAAK,QAAS,KAAI,SAAS,EAAE,MAAO,UAAS;AACxD,SAAO,OAAO;AAChB;AAEA,SAAS,eACP,OACA,MACA,OACA,UACQ;AACR,MAAI,UAAU,OAAW,QAAO;AAChC,MAAI,CAAC,MAAM;AAET,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,IAAI,IAAI,KAAK,KAAK;AAAA,IACpG;AAAA,EACF;AACA,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"numberformat.d.ts","sourceRoot":"","sources":["../../../src/str/numberformat.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAIH,MAAM,MAAM,QAAQ,GAAG,gBAAgB,GAAG,aAAa,GAAG,eAAe,GAAG,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"numberformat.d.ts","sourceRoot":"","sources":["../../../src/str/numberformat.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAIH,MAAM,MAAM,QAAQ,GAAG,gBAAgB,GAAG,aAAa,GAAG,eAAe,GAAG,mBAAmB,CAAC;AA0KhG,qDAAqD;AACrD,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,GAAG,MAAM,CA8BnF;AASD;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAMhF"}
|
|
@@ -100,29 +100,22 @@ function shortestDigits(x) {
|
|
|
100
100
|
const digits = all.slice(lead).replace(/0+$/, "");
|
|
101
101
|
return { digits, intLen: digits ? intLen : 0 };
|
|
102
102
|
}
|
|
103
|
+
const bitsView = new DataView(new ArrayBuffer(8));
|
|
103
104
|
function exactDigits(x) {
|
|
104
105
|
const abs = Math.abs(x);
|
|
105
106
|
if (abs === 0) return { digits: "", intLen: 0 };
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
107
|
+
if (Number.isSafeInteger(abs)) {
|
|
108
|
+
const str2 = String(abs);
|
|
109
|
+
return { digits: (0, import_floatingdecimal.trimZeros)(str2), intLen: str2.length };
|
|
110
|
+
}
|
|
111
|
+
bitsView.setFloat64(0, abs);
|
|
112
|
+
const bits = bitsView.getBigUint64(0);
|
|
109
113
|
const expBits = Number(bits >> 52n & 0x7ffn);
|
|
110
114
|
let mant = bits & 0xfffffffffffffn;
|
|
111
115
|
const e2 = expBits === 0 ? -1074 : expBits - 1075;
|
|
112
116
|
if (expBits !== 0) mant |= 1n << 52n;
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
if (e2 >= 0) {
|
|
116
|
-
str = (mant << BigInt(e2)).toString();
|
|
117
|
-
fracDigits = 0;
|
|
118
|
-
} else {
|
|
119
|
-
str = (mant * 5n ** BigInt(-e2)).toString();
|
|
120
|
-
fracDigits = -e2;
|
|
121
|
-
}
|
|
122
|
-
const intLen = str.length - fracDigits;
|
|
123
|
-
const lead = str.length - str.replace(/^0+/, "").length;
|
|
124
|
-
const digits = str.slice(lead).replace(/0+$/, "");
|
|
125
|
-
return { digits, intLen: intLen - lead };
|
|
117
|
+
const str = (e2 >= 0 ? mant << BigInt(e2) : mant * (0, import_floatingdecimal.pow5)(-e2)).toString();
|
|
118
|
+
return { digits: (0, import_floatingdecimal.trimZeros)(str), intLen: str.length - Math.max(0, -e2) };
|
|
126
119
|
}
|
|
127
120
|
function roundDigits(d, frac, mode) {
|
|
128
121
|
const keep = d.intLen + frac;
|