Monday, September 25, 2017
Thursday, September 21, 2017
splice
// x/../y=>/y
var a = ["x", "..", "y"]
trimDots(a)
console.log(a);
// x/y/../z/1 => x/z/1
a = ["x", "y", "..", "z", "1"]
trimDots(a)
console.log(a)
// x/./y=> x/y
a = ["x", ".", "y"]
trimDots(a)
console.log(a)
// x/../../y/z=>
function trimDots(ary) {
var i, part;
for (i = 0; i < ary.length; i++) {
part = ary[i];
if (part === '.') {
ary.splice(i, 1);
i -= 1;
} else if (part === '..') {
// If at the start, or previous value is still ..,
// keep them so that when converted to a path it may
// still work when converted to a path, even though
// as an ID it is less than ideal. In larger point
// releases, may be better to just kick out an error.
if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') {
continue;
} else if (i > 0) {
ary.splice(i - 1, 2);
i -= 2;
}
}
}
}
Output:
[ 'y' ] [ 'x', 'z', '1' ] [ 'x', 'y' ]
Iterate thru an array and call function for each element
function each(ary, func) {
if (ary) {
var i;
for (i = 0; i < ary.length; i += 1) {
if (ary[i] && func(ary[i], i, ary)) {
break;
}
}
}
}
var global = {
x: {
y: {
z: "this is z"
}
}
}
function getGlobal(value) {
if (!value) {
return value;
}
var g = global;
each(value.split('.'), function (part) {
g = g[part];
});
return g;
}
console.log(getGlobal("x.y.z"));
Output:
this is z
Subscribe to:
Posts (Atom)