Last active
March 30, 2017 13:35
-
-
Save yllieth/5131389bb37d376bc3a1c46d13b34100 to your computer and use it in GitHub Desktop.
standard operations on arrays/objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// returns elements not ends | |
function elementsNotEndsBy(ending, array) { | |
var regex = new RegExp(ending + '$'); | |
return array.filter(entry => !regex.test(entry)); | |
} | |
elementsNotEndsBy('berry', ['strawberry', 'apple', 'blueberry']); // => ['apple'] | |
elementsNotEndsBy('allEntries', ['strawberry', 'apple', 'blueberry']); // => ['strawberry', 'apple', 'blueberry'] | |
elementsNotEndsBy('allEntries', []); // => [] | |
// ------------------------------------------------------------------------------------------------------------------------------------- |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function deepSetter(obj, path, value) { | |
var i = 0; | |
for (i = 0; i < path.length - 1; i++) { | |
if (obj.hasOwnProperty(path[i]) === false) { | |
obj[path[i]] = {}; | |
} | |
obj = obj[path[i]]; | |
} | |
obj[path[i]] = value; | |
} | |
var obj = {a: 'foo', b: {c: 'foo2'}}; | |
deepSetter(obj, ['b', 'c'], 'bar'); // => obj = {a: 'foo', b: {c: 'bar'}} | |
deepSetter(obj, ['d'], 'newEntry'); // => obj = {a: 'foo', b: {c: 'foo2'}, d: 'newEntry'} | |
deepSetter(obj, ['e', 'f'], 'newObject'); // => obj = {a: 'foo', b: {c: 'foo2'}, e: {f: 'newObject'}} | |
deepSetter(obj, ['g', 'h', 'i', 'j'], 'deepObject'); // => obj = {a: 'foo', b: {c: 'foo2'}, g: {h: {i: {j: 'deepObject'}}}} | |
deepSetter(obj, ['b'], 'bar'); // ERROR : an existing obj cannot be replace by a string | |
// ------------------------------------------------------------------------------------------------------------------------------------- | |
function deepGetter(obj, path) { | |
var i = 0; | |
for (i = 0; i < path.length - 1; i++) { | |
if (obj.hasOwnProperty(path[i])) { | |
obj = obj[path[i]]; | |
} else { | |
return undefined; | |
} | |
} | |
return obj[path[i]]; | |
} | |
var obj = {a: 'foo', b: {c: 'foo2'}}; | |
deepGetter(obj, ['a']); // => 'foo' | |
deepGetter(obj, ['b']); // => { c: 'foo2' } | |
deepGetter(obj, ['b', 'c']); // => 'foo2' | |
deepGetter(obj, ['b', 'c', 'd']); // => undefined | |
deepGetter(obj, ['d', 'e', 'f']); // => undefined | |
// ------------------------------------------------------------------------------------------------------------------------------------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment