@tokens-studio/graph-engine
Version:
An execution engine to handle Token Studios generators and resolvers
54 lines • 1.6 kB
JavaScript
import { setProperty } from 'dot-prop';
/**
* Takes in a nested object of tokens and returns a flattened array of tokens
* @param nested
* @param keyPath Optional key path to prefix the name of the token
* @returns
*/
export const flatten = (nested, keyPath = []) => {
return Object.entries(nested).reduce((acc, [key, val]) => {
//Check if leaf node
if (val && typeof val.value !== 'undefined') {
const leaf = val;
acc.push({
name: [...keyPath, key].join('.'),
value: leaf.value,
type: leaf.type,
description: leaf.description
});
return acc;
}
//else continue recursing
const flattened = flatten(val, [...keyPath, key]);
acc = acc.concat(flattened);
return acc;
}, []);
};
/**
* Takes in an array of tokens and returns a map of tokens.
* This only works if the tokens are flat, meaning they do not have nested tokens
* @param tokens
* @returns
*/
export const flatTokensToMap = (tokens) => {
return tokens.reduce((acc, token) => {
acc[token.name] = token;
return acc;
}, {});
};
/**
* Takes an array of tokens and returns a map of tokens. This does result in nested tokens
* @param tokens
* @returns
*/
export const flatTokensRestoreToMap = (tokens) => {
const returning = {};
tokens.forEach(token => {
const { name, ...rest } = token;
setProperty(returning, name, {
...rest
});
});
return returning;
};
//# sourceMappingURL=index.js.map