locutus
Version:
Locutus other languages' standard libraries to JavaScript for fun and educational purposes
68 lines (67 loc) • 2.19 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.array_walk_recursive = array_walk_recursive;
const _phpTypes_ts_1 = require("../_helpers/_phpTypes.js");
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 (!(0, _phpTypes_ts_1.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((0, _phpTypes_ts_1.toPhpArrayObject)(array));
}