UNPKG

locutus

Version:

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

65 lines (64 loc) 2.05 kB
import { isObjectLike, toPhpArrayObject, } from "../_helpers/_phpTypes.js"; export function array_walk_recursive(array, funcname, userdata) { // original by: Hugues Peccatte // note 1: Only works with user-defined functions, not built-in functions like void() // example 1: array_walk_recursive([3, 4], function () {}, 'userdata') // returns 1: true // example 2: array_walk_recursive([3, [4]], function () {}, 'userdata') // returns 2: true // example 3: array_walk_recursive([3, []], function () {}, 'userdata') // returns 3: true if (!isObjectLike(array)) { return false; } if (typeof funcname !== 'function') { return false; } const hasUserdata = typeof userdata !== 'undefined'; const callCallback = (value, key) => { try { if (hasUserdata) { Reflect.apply(funcname, undefined, [value, key, userdata]); } else { Reflect.apply(funcname, undefined, [value, key]); } return true; } catch (_e) { return false; } }; const walkList = (list) => { for (const [index, value] of list.entries()) { if (Array.isArray(value)) { if (!walkList(value)) { return false; } continue; } if (!callCallback(value, index)) { return false; } } return true; }; const walkAssoc = (assoc) => { for (const [key, value] of Object.entries(assoc)) { if (Array.isArray(value)) { if (!walkList(value)) { return false; } continue; } if (!callCallback(value, key)) { return false; } } return true; }; if (Array.isArray(array)) { return walkList(array); } return walkAssoc(toPhpArrayObject(array)); }