Stateful API
by Artem
JavaScript
'use strict';
const INI_FILE = `
[Host]
address=127.0.0.1
name=localhost
[Connections]
timeout=10000
`;
const INI = {
parse(source) {
let key;
const data = source
.split('\n')
.filter(Boolean)
.reduce((acc, next) => {
if (/\[.+\]/.test(next)) {
key = next.match(/\[(.+)\]/)[1];
acc[key] = {};
} else {
const [k, v] = next.split('=');
acc[key][k] = v;
}
return acc;
}, {});
return (function(source) {
let section = null;
return {
setSection(sectionName) {
section = source[sectionName];
},
get(fieldName) {
return section[fieldName];
}
};
})(data);
}
};
var ini = INI.parse(INI_FILE);
ini.setSection('Host');
const addr = ini.get('address');
const hostname = ini.get('name');
console.log(addr, hostname);
ini.setSection('Connections');
const timeout = ini.get('timeout');
console.log(timeout);