5 ms·
Here's a 1-1 port in JavaScript https://github.com/benjamingr/js-restructure https://github.com/benjamingr/js-restructure function matcher(obj) { "use stri
by inglor 11y ago
Here's a 1-1 port in JavaScript https://github.com/benjamingr/js-restructure https://github.com/benjamingr/js-restructure
function matcher(obj) { "use strict";
let props = Object.getOwnPropertyNames(obj);
const re = new RegExp(props.reduce((p, c) => p + (c.startsWith("_") ? obj[c] : `(${obj[c]})`), ""));
props = props.filter(x => !x.startsWith("_"));
return function(pattern) {
let o = {};
const res = re.exec(pattern);
for(let i = 0; i < res.length; i++) o[props[i]] = res[i+1];
return o;
};
}
And example usage:
```js
matcher({
_ : "^",
user : "\\w+",
_2 : "@",
host : "[^@]+",
_3 : "$"
})("user@ycombinator.com")
```
- phillmv 11y agoIn js, are obj field names stable on insertion? Normally I wouldn't expect getOwnPropertyNames to return them in the same order.
- dagw 11y agoAccording to the spec, no guarantee of order is made. The latest spec even adds separate a Map object that does make that guarentee: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- inglor 11y agothe order is guaranteed. https://esdiscuss.org/topic/property-ordering-of-enumerate-getownpropertynames https://esdiscuss.org/topic/property-ordering-of-enumerate-g...
- ajanuary 11y agoJavaScript doesn't guarantee the order of keys. [edit] Also, the API makes less sense because JavaScript isn't statically typed so you can make up the result object on the fly. match('^(?<user>\w+)@(?<host>[^@]+)$', 'joe@example.com') => {'user': 'joe', 'host': 'example.com'}
- inglor 11y agoYes it does - it does for getOwnPropertyNames but not for Object.keys.
- ajanuary 11y agoSeems I might be outdated, and ES6 does define an order.
- masklinn 11y ago> [edit] Also, the API makes less sense because JavaScript isn't statically typed so you can make up the result object on the fly. But now you need to parse the string and correctly extract named groups before flogging that to the regex engine, whereas the other way around you do some string concatenation then match back on the groups by index.
- inglor 11y agoJavaScript has no named capturing groups.