UNPKG

locutus

Version:

Locutus other languages' standard libraries to JavaScript for fun and educational purposes

71 lines (70 loc) 2.11 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getPointerState = getPointerState; exports.getArrayLikeLength = getArrayLikeLength; exports.getEntryAtCursor = getEntryAtCursor; const _phpRuntimeState_ts_1 = require("./_phpRuntimeState.js"); const _phpTypes_ts_1 = require("./_phpTypes.js"); const findPointerIndex = (pointers, target) => { for (let index = 0; index < pointers.length; index += 1) { if (pointers[index] === target) { return index; } } return -1; }; function getPointerState(target, initialize = true) { const runtime = (0, _phpRuntimeState_ts_1.ensurePhpRuntimeState)(); const pointers = runtime.pointers; // Store [target, cursor] pairs in one flat runtime list so pointer state stays bound to each array-like input. const pointerTarget = target; let index = findPointerIndex(pointers, pointerTarget); if (index === -1) { if (!initialize) { return null; } pointers.push(pointerTarget, 0); index = pointers.length - 2; } const cursorValue = pointers[index + 1]; const cursor = typeof cursorValue === 'number' ? cursorValue : 0; return { cursor, setCursor: (nextCursor) => { pointers[index + 1] = nextCursor; }, }; } function getArrayLikeLength(target) { if (Array.isArray(target)) { return target.length; } let count = 0; for (const _key in target) { count += 1; } return count; } function getEntryAtCursor(target, cursor) { if (cursor < 0) { return null; } if (Array.isArray(target)) { if (cursor >= target.length) { return null; } const value = target[cursor]; if (typeof value === 'undefined') { return null; } return [cursor, value]; } let index = 0; for (const [key, value] of (0, _phpTypes_ts_1.entriesOfPhpAssoc)(target)) { if (index === cursor) { return [key, value]; } index += 1; } return null; }