Skip to content

Instantly share code, notes, and snippets.

@mvaldesdeleon
Last active February 8, 2018 21:59
Show Gist options
  • Save mvaldesdeleon/0cfb51e6c757038430795c36322f003b to your computer and use it in GitHub Desktop.
Save mvaldesdeleon/0cfb51e6c757038430795c36322f003b to your computer and use it in GitHub Desktop.
Conditional deep mapping & deep resolving of Objects.
const isObject =
obj =>
obj instanceof Object;
const isPromise =
obj =>
typeof obj.then === 'function';
const mapDeepIf =
(pr, fn, obj) =>
Object.entries(obj).reduce(
(copy, [key, value]) =>
({
...copy
, [key]: isObject(value)
? mapDeepIf(pr, fn, value)
: (pr(value)
? fn(value)
: value)
})
, {}
);
const resolveAllDeep =
obj =>
Object.entries(obj).reduce(
(copy, [key, value]) =>
Promise.all([
copy
, isPromise(value)
? value
: (isObject(value)
? resolveAllDeep(value)
: Promise.resolve(value))
]).then(([copy, value]) =>
({
...copy
, [key]: value
})
)
, Promise.resolve({})
);
let testObj = {
a: 1
, b: 2
, c: {
d: 3
, e: 4
, f: {
g: 5
, h: 6
}
}
};
let promiseObj = mapDeepIf(
x => x > 2 && x < 6
, x => Promise.resolve(x * 10)
, testObj
);
resolveAllDeep(promiseObj)
.then(console.dir.bind(console));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment