A library that helps you replace multiple variables and statements into a single type-safe & functional expression.
- Chaining
- Great Type Inference
- Async / Await Support
# pnpm
pnpm add --save scope-utilities
# npm
npm install --save scope-utilities
import { scope } from 'scope-utilities';
- Passes
VALUE
into first argument ofFUNC
- Returns
VALUE
Contain changes to mutable objects:
const nearest_date = false;
const dateForNextWeek: Date = scope(new Date())
.also((date) => {
date.setDate(date.getDate() + 7)
}).also(date => {
if (nearest_date) {
date.setHours(0)
date.setMinutes(0)
date.setSeconds(0)
date.setMilliseconds(0)
}
}).value();
- Passes
VALUE
into first argument ofFUNC
- Returns the result of
FUNC
Conditionally building queries:
const query = await scope(
startQuery()
).let((query) =>
shuoldIncludeContactDetails()
? query.select(['id', 'email', 'COUNT(*) as post_count'])
: query.select(['id', 'COUNT(*) as post_count'])
).let(async (query) =>
await shouldReturnActiveOnly()
? query.where({ active: true })
: query
).let((query) =>
query.groupBy('id') // no need to await `query` here.
).let(query =>
shouldSortBy() === 'post_count'
? query.orderBy('post_count')
: shouldSortBy() === 'signup_time'
? query.orderBy('created_at')
: query
)
.value();
const results = query.execute();
- Runs
FUNC
and returns the result - You can chain it with other scope functions if you like.
const newUser = await run(async () => {
return await queryUser();
}).let((user) => {
return user.clone();
}).also((user) => {
user.setName('John Doe');
}).let(async () => {
return await user.save();
}).value();
MIT