UNPKG

locutus

Version:

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

66 lines (65 loc) 1.87 kB
import { ensurePhpRuntimeState } from "./_phpRuntimeState.js"; import { entriesOfPhpAssoc } from "./_phpTypes.js"; const findPointerIndex = (pointers, target) => { for (let index = 0; index < pointers.length; index += 1) { if (pointers[index] === target) { return index; } } return -1; }; export function getPointerState(target, initialize = true) { const runtime = 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; }, }; } export function getArrayLikeLength(target) { if (Array.isArray(target)) { return target.length; } let count = 0; for (const _key in target) { count += 1; } return count; } export 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 entriesOfPhpAssoc(target)) { if (index === cursor) { return [key, value]; } index += 1; } return null; }