UNPKG

@wordpress/editor

Version:
68 lines (61 loc) 1.86 kB
/** * External dependencies */ import { groupBy, map, unescape as lodashUnescapeString } from 'lodash'; /** * Returns terms in a tree form. * * @param {Array} flatTerms Array of terms in flat format. * * @return {Array} Array of terms in tree format. */ export function buildTermsTree(flatTerms) { const flatTermsWithParentAndChildren = flatTerms.map(term => { return { children: [], parent: null, ...term }; }); const termsByParent = groupBy(flatTermsWithParentAndChildren, 'parent'); if (termsByParent.null && termsByParent.null.length) { return flatTermsWithParentAndChildren; } const fillWithChildren = terms => { return terms.map(term => { const children = termsByParent[term.id]; return { ...term, children: children && children.length ? fillWithChildren(children) : [] }; }); }; return fillWithChildren(termsByParent['0'] || []); } // Lodash unescape function handles ' but not ' which may be return in some API requests. export const unescapeString = arg => { return lodashUnescapeString(arg.replace(''', "'")); }; /** * Returns a term object with name unescaped. * The unescape of the name property is done using lodash unescape function. * * @param {Object} term The term object to unescape. * * @return {Object} Term object with name property unescaped. */ export const unescapeTerm = term => { return { ...term, name: unescapeString(term.name) }; }; /** * Returns an array of term objects with names unescaped. * The unescape of each term is performed using the unescapeTerm function. * * @param {Object[]} terms Array of term objects to unescape. * * @return {Object[]} Array of term objects unescaped. */ export const unescapeTerms = terms => { return map(terms, unescapeTerm); }; //# sourceMappingURL=terms.js.map