UNPKG

locutus

Version:

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

38 lines (37 loc) 1.87 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.array_replace_recursive = array_replace_recursive; const _phpTypes_ts_1 = require("../_helpers/_phpTypes.js"); const cloneReplaceTarget = (value) => { if (Array.isArray(value)) { return [...value]; } return { ...value }; }; function array_replace_recursive(arr, ...replacements) { // discuss at: https://locutus.io/php/array_replace_recursive/ // parity verified: PHP 8.3 // original by: Brett Zamir (https://brett-zamir.me) // example 1: array_replace_recursive({'citrus' : ['orange'], 'berries' : ['blackberry', 'raspberry']}, {'citrus' : ['pineapple'], 'berries' : ['blueberry']}) // returns 1: {citrus : ['pineapple'], berries : ['blueberry', 'raspberry']} if (replacements.length < 1) { throw new Error('There should be at least 2 arguments passed to array_replace_recursive()'); } // Although docs state that the arguments are passed in by reference, // it seems they are not altered, but rather the copy that is returned // So we make a copy here, instead of acting on arr itself const retObj = cloneReplaceTarget(arr); const retObjLike = (0, _phpTypes_ts_1.toPhpArrayObject)(retObj); for (const replacement of replacements) { const replacementObj = (0, _phpTypes_ts_1.toPhpArrayObject)(replacement); for (const p in replacementObj) { if ((0, _phpTypes_ts_1.isObjectLike)(retObjLike[p]) && (0, _phpTypes_ts_1.isObjectLike)(replacementObj[p])) { retObjLike[p] = array_replace_recursive((0, _phpTypes_ts_1.toPhpArrayObject)(retObjLike[p]), (0, _phpTypes_ts_1.toPhpArrayObject)(replacementObj[p])); } else { retObjLike[p] = replacementObj[p]; } } } return retObj; }