Skip to content

Instantly share code, notes, and snippets.

@moonthug
Last active September 20, 2017 14:10
Show Gist options
  • Save moonthug/a3f20d10fd48a77d84a49902c4b6ab5b to your computer and use it in GitHub Desktop.
Save moonthug/a3f20d10fd48a77d84a49902c4b6ab5b to your computer and use it in GitHub Desktop.
Takes a D3/CSS transform string value and decomposes to an object
/**
* Decomposes transform attribute in an object
* @param {string} input Transform string to decompose
* @param {boolean=true} asString Return the values as arrays (false) or transform strings (true)
* @returns {}
*/
const getTransform = (input, asString = true) => {
const typeRegex = /(\w+\([\w+., -]*\))/g;
const valuesRegex = /([-\d.]+)[, ]?/g;
let transform = {};
if(!input || input === '') return transform;
let t = null;
while (t = typeRegex.exec(input)) {
const typeValuesRegex = /(\w+)\(([^\)]+)\)/g;
let tv = typeValuesRegex.exec(t[1]);
const key = tv[1];
const valueString = tv[2];
let values = [];
let v = null;
while (v = valuesRegex.exec(valueString)) {
values.push(v[1]);
}
transform[key] = asString === true ? `${key}(${values.join(',')})` : values;
}
return transform;
}
/**
* Example
*/
// Simple
console.dir(getTransform('translate(1, -1.5)'));
// { translate: 'translate(1,-1.5)' }
// Return values as array
console.dir(getTransform('translate(1, -1.5, 3.0002)', false));
// { translate: ['1', '-1.5', '3.0002'] }
console.dir(getTransform('translate(1, -1.5) scale(5)'));
// { translate: 'translate(1,-1.5)', scale: 'scale(5)' }
console.dir(getTransform('translate(1, -1.5) rotate(4) scale(5.5, -0.00542)'));
// { translate: 'translate(1,-1.5)', rotate: 'rotate(4)', scale: 'scale(5.5,-0.00542)' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment