repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
bianjieai/iobscan-ibc-explorer-backend
|
src/monitor/metrics/ibc_tx_processing_cnt.metric.ts
|
import {InjectMetric, makeGaugeProvider} from "@willsoto/nestjs-prometheus";
import {Gauge} from "prom-client";
import {Injectable} from "@nestjs/common";
@Injectable()
export class IbcTxProcessingMetric {
constructor(@InjectMetric("ibc_explorer_backend_processing_cnt") public gauge: Gauge<string>) {}
async collect(value) {
this.gauge.set(value)
}
}
export function IbcTxProcessingProvider() {
return makeGaugeProvider({
name: "ibc_explorer_backend_processing_cnt",
help: "ibc explorer backend processing cnt every scrape times",
})
}
|
bianjieai/iobscan-ibc-explorer-backend
|
src/module/ibc_statistics.module.ts
|
<reponame>bianjieai/iobscan-ibc-explorer-backend<gh_stars>1-10
import { Module } from '@nestjs/common';
import { IbcStatisticsService } from '../service/ibc_statistics.service';
import { IbcStatisticsController } from '../controller/ibc_statistics.controller';
@Module({
providers: [IbcStatisticsService],
controllers: [IbcStatisticsController],
})
export class IbcStatisticsModule {}
|
bianjieai/iobscan-ibc-explorer-backend
|
src/controller/ibc_chain.controller.ts
|
import { Controller, Get, Query } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Result } from '../api/ApiResult';
import { IbcChainService } from '../service/ibc_chain.service';
import { IbcChainResultResDto } from '../dto/ibc_chain.dto';
@ApiTags('IbcChains')
@Controller('ibc')
export class IbcChainController {
constructor(private readonly ibcChainService: IbcChainService) {}
@Get('chains')
async queryChains(): Promise<Result<IbcChainResultResDto>> {
const result: IbcChainResultResDto | null = await this.ibcChainService.queryChainsByDatetime();
return new Result<IbcChainResultResDto | null>(result);
}
}
|
bianjieai/iobscan-ibc-explorer-backend
|
src/task/ibc_denom_update.task.service.ts
|
import {Connection} from 'mongoose';
import {Injectable} from "@nestjs/common";
import {InjectConnection} from "@nestjs/mongoose";
import {RecordLimit, TaskEnum} from "../constant";
import { cfg } from '../config/config';
import {IbcDenomSchema} from "../schema/ibc_denom.schema";
import {IbcBaseDenomSchema} from "../schema/ibc_base_denom.schema";
import {IbcDenomCaculateSchema} from "../schema/ibc_denom_caculate.schema";
@Injectable()
export class IbcDenomUpdateTaskService {
private ibcDenomCaculateModel;
private ibcDenomModel;
private ibcBaseDenomModel;
constructor(@InjectConnection() private connection: Connection) {
this.getModels();
this.doTask = this.doTask.bind(this);
}
async doTask(taskName?: TaskEnum): Promise<void> {
this.handleChainDenoms();
}
async getModels(): Promise<void> {
this.ibcDenomModel = await this.connection.model(
'ibcDenomModel',
IbcDenomSchema,
'ibc_denom',
);
this.ibcBaseDenomModel = await this.connection.model(
'ibcBaseDenomModel',
IbcBaseDenomSchema,
'ibc_base_denom',
);
this.ibcDenomCaculateModel = await this.connection.model(
'ibcDenomCaculateModel',
IbcDenomCaculateSchema,
'ibc_denom_caculate',
);
}
async collectChainDenomsMap(ibcDenomData) {
let chainDenomsMap = new Map,baseDenoms = []
ibcDenomData.forEach(item => {
if (item?.chain_id) {
if (item?.denom?.indexOf("ibc/") < 0 ) {
baseDenoms.push(item.denom)
}else{
if (!chainDenomsMap.has(item.chain_id)) {
let denoms = []
denoms.push(item.denom)
chainDenomsMap.set(item.chain_id, denoms)
} else {
let arrayDenoms = chainDenomsMap.get(item.chain_id)
arrayDenoms.push(item.denom)
chainDenomsMap.set(item.chain_id, arrayDenoms)
}
}
}
})
return {chainDenomsMap,baseDenoms}
}
async getNeedhandleIbcDenoms(page_num,page_size) {
return await this.ibcDenomModel.findUnAuthDenom(page_num,page_size)
}
async getIbcDenoms(chainId, denoms) {
return await this.ibcDenomCaculateModel.findIbcDenoms(chainId, denoms)
}
async getBaseDenomMap() : Promise<any>{
let baseDenomMap = new Map
const baseDenom = await this.ibcBaseDenomModel.findAllRecord()
if (baseDenom?.length) {
for (const item of baseDenom) {
baseDenomMap.set(`${item?.denom}`,item?.symbol)
}
}
return baseDenomMap
}
async handleChainDenoms() {
let pageNum = 1,supportDenoms = []
const baseDenomMap = await this.getBaseDenomMap()
//judge supportDenoms size for handle batch limit
while(supportDenoms?.length < cfg.serverCfg.updateDenomBatchLimit) {
const ibcDenoms = await this.getNeedhandleIbcDenoms(pageNum, RecordLimit)
ibcDenoms.forEach(item => {
const paths = item?.denom_path?.split("/")
//only support one skip path
if (paths?.length <= 2){
//only support denom which base_denom in ibc_base_denom
if (baseDenomMap && baseDenomMap?.has(`${item?.base_denom}`)) {
supportDenoms.push(item)
}
}
});
// break when finish scan all the ibc denom which symbol is empty.
if (ibcDenoms?.length < RecordLimit) {
break;
}
pageNum++
}
const {chainDenomsMap,baseDenoms} = await this.collectChainDenomsMap(supportDenoms)
let denomData = []
if (baseDenoms) {
const baseDenomDatas = await this.ibcBaseDenomModel.findByDenoms(baseDenoms)
for (const item of baseDenomDatas) {
await this.ibcDenomModel.updateDenomRecord({
chain_id: item.chain_id,
denom: item.denom,
symbol: item.symbol,
})
}
}
if (chainDenomsMap) {
chainDenomsMap.forEach((value, key) => {
denomData.push({chain_id: key, denoms: value})
})
for (const one of denomData) {
const items = await this.getIbcDenoms(one.chain_id, one.denoms)
for (const item of items) {
await this.ibcDenomModel.updateDenomRecord({
chain_id: one.chain_id,
denom: item.denom,
symbol: item.symbol,
})
}
}
}
}
}
|
bianjieai/iobscan-ibc-explorer-backend
|
src/service/config.service.ts
|
<gh_stars>1-10
import { Injectable } from '@nestjs/common';
import { Connection } from 'mongoose';
import { InjectConnection } from '@nestjs/mongoose';
import { ConfigSchema } from '../schema/config.schema';
import { ConfigResDto } from '../dto/config.dto';
@Injectable()
export class ConfigService {
private configModel;
constructor(@InjectConnection() private connection: Connection) {
this.getModels();
}
async getModels(): Promise<void> {
this.configModel = await this.connection.model(
'configModel',
ConfigSchema,
'ibc_config',
);
}
// findOne
async findOne(): Promise<ConfigResDto> {
const result: ConfigResDto = new ConfigResDto(await this.configModel.findRecord())
return result;
}
}
|
gulpetl/gulp-email-adapter
|
dist/types/plugin.d.ts
|
export declare function emailAdapter(configObj?: any): any;
//# sourceMappingURL=plugin.d.ts.map
|
gulpetl/gulp-email-adapter
|
debug/gulpfile.ts
|
let gulp = require('gulp')
import { emailAdapter } from '../src/plugin'
import * as loglevel from 'loglevel'
//import { strict } from 'assert';
const log = loglevel.getLogger('gulpfile')
log.setLevel((process.env.DEBUG_LEVEL || 'warn') as loglevel.LogLevelDesc)
const pkginfo = require('pkginfo')(module); // project package.json info into module.exports
const PLUGIN_NAME = module.exports.name;
let mailOption: any = null//{ "accessKeyId": "Enter your access key", "secretAccessKey": "ENter your access secret", "region": "enter region" };
if (!mailOption)
mailOption = require('./mailoption.local.json') // adapt mailoption.demo.json with correct options
//the plugin will be called here
export function sendMail (callback:any) {
gulp.src('../testdata/mail.eml')
.pipe(emailAdapter(mailOption))
}
//the roundtrip back to
exports.default = gulp.series(sendMail)
|
gulpetl/gulp-email-adapter
|
src/plugin.ts
|
<filename>src/plugin.ts
var map = require('map-stream');
const getStream = require('get-stream')
var fs = require('fs');
import Vinyl = require('vinyl')
import PluginError = require('plugin-error');
require('pkginfo')(module); // project package.json info into module.exports
const PLUGIN_NAME = module.exports.name;
import nodemailer = require('nodemailer');
var aws = require('aws-sdk');
import merge from 'merge'
import camelcase from 'camelcase';
export function emailAdapter(configObj?: any) {
function modifyContents(file: Vinyl, cb: Function) {
if (file.isNull()) return cb(null, file);
if (file.isStream()) return cb(new PluginError(PLUGIN_NAME, "Streaming not supported")); // pass error if streaming is not supported
// create a config object for this file taking configObj and overriding with any gulp-data-compatible settings from this specific file
// we don't use file.data directly; we look for our config object as a property UNDER file.data (so other plugins can do the same);
// tries for both full and shortened-camelcased versions of THIS plugin's name, e.g. "gulp-plugin-name" and "pluginName"
aws.config = merge.recursive(true, configObj, file?.data?.[PLUGIN_NAME], file.data?.[camelcase(PLUGIN_NAME.replace(/^gulp-/, ''))])
/*Buffer Mode*/
if (file.isBuffer()) {
let fileBuf: Buffer = (file.contents as Buffer)
let rawMessage2 = fileBuf.toString('utf8')
let transporter = nodemailer.createTransport({
SES: new aws.SES({
apiVersion: '2010-12-01'
})
});
var mailOptions2 = {
envelope: {
},
raw: rawMessage2
};
transporter.sendMail(mailOptions2, function (error, info) {
if (error) {
return console.log(error);
}
console.log('Message sent: ' + info.response);
})
}
return cb(null, file);
}
return map(modifyContents);
};
|
InSeong-So/Frontend-Architecture
|
src/Application.ts
|
<filename>src/Application.ts
export default class Application {
public sampleDataGenerator: SampleDataGenerator;
constructor(...rest: any[]) {
this.init();
}
public init() {
this.sampleDataGenerator.generate();
}
public run(application: Application, args: any[]) {
console.log('execute');
}
public start(...args: any[]): void {
try {
this.run(this, args);
} catch (error) {
console.log(error);
}
}
}
|
InSeong-So/Frontend-Architecture
|
src/index.ts
|
import App from './Application';
const app = new App().start();
|
zwliew/flash-kards
|
src/store/index.ts
|
import Vue from 'vue';
import Vuex from 'vuex';
import { vuexfireMutations } from 'vuexfire';
import getters from './getters';
import mutations from './mutations';
import actions from './actions';
import { State } from './types';
export * from './types';
Vue.use(Vuex);
export default new Vuex.Store<State>({
state: {
decks: [],
user: null,
},
mutations: {
...mutations,
...vuexfireMutations,
},
actions,
getters,
});
|
zwliew/flash-kards
|
src/router.ts
|
<reponame>zwliew/flash-kards
import Vue from 'vue';
import Router from 'vue-router';
Vue.use(Router);
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/decks',
name: 'decks',
component: () =>
import(/* webpackChunkName: "decks" */ './views/Decks.vue'),
},
{
path: '/decks/new',
name: 'newDeck',
component: () =>
import(/* webpackChunkName: "newDeck" */ './views/NewDeck.vue'),
},
{
path: '/decks/:deckId',
name: 'manageDeck',
component: () =>
import(/* webpackChunkName: "manageDeck" */ './views/ManageDeck.vue'),
},
{
path: '/decks/:deckId/study',
name: 'studyDeck',
component: () =>
import(/* webpackChunkName: "studyDeck" */ './views/StudyDeck.vue'),
},
{
path: '/decks/:deckId/new',
name: 'newCard',
component: () =>
import(/* webpackChunkName: "newCard" */ './views/NewCard.vue'),
},
{
path: '/decks/:deckId/:cardIdx/edit',
name: 'editCard',
component: () =>
import(/* webpackChunkName: "editCard" */ './views/EditCard.vue'),
},
{
path: '/account',
name: 'account',
component: () =>
import(/* webpackChunkName: "account" */ './views/Account.vue'),
},
{
path: '/',
redirect: '/decks',
},
],
});
|
zwliew/flash-kards
|
src/store/types.ts
|
export interface User {
id: string;
name: string;
photoUrl: string;
isAdmin: boolean;
}
export interface Card {
front: string;
back: string;
}
export interface Deck {
id: string;
title: string;
tags: string[];
cards: Card[];
}
export interface State {
user: User | null;
decks: Deck[];
}
export interface Getters {
getDeckById: (id: string) => Deck;
getDeckTitleById: (id: string) => string;
}
|
zwliew/flash-kards
|
src/main.ts
|
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store, { User } from './store';
import firebase from 'firebase/app';
import 'firebase/auth';
import './registerServiceWorker';
Vue.config.productionTip = false;
new Vue({
router,
store,
created() {
firebase.initializeApp({
apiKey: '<KEY>',
authDomain: 'flash-kards.firebaseapp.com',
databaseURL: 'https://flash-kards.firebaseio.com',
projectId: 'flash-kards',
storageBucket: 'flash-kards.appspot.com',
messagingSenderId: '664546075542',
appId: '1:664546075542:web:171d8e625f0defdb',
});
firebase.firestore().settings({});
firebase.auth().onAuthStateChanged((user) => {
if (user === null) {
this.$store.dispatch('LOG_OUT');
} else {
this.$store.dispatch('LOG_IN', {
id: user.uid,
name: user.displayName,
photoUrl: user.photoURL,
});
}
});
this.$store.dispatch('BIND_DECKS');
},
render: (h) => h(App),
}).$mount('#app');
|
zwliew/flash-kards
|
src/store/getters.ts
|
import { Deck, State, Getters } from './types';
export default {
getDeckById: ({ decks }: State, _: Getters) => (id: string) =>
decks.find((deck: Deck) => deck.id === id),
getDeckTitleById: (_: State, getters: Getters) => (id: string) => {
const deck = getters.getDeckById(id);
if (!deck) {
return null;
}
return deck.title;
},
};
|
zwliew/flash-kards
|
src/store/actions.ts
|
<filename>src/store/actions.ts
import { firestoreAction } from 'vuexfire';
import firebase from 'firebase/app';
import 'firebase/firestore';
import { State, Getters, User } from './types';
export default {
BIND_DECKS: firestoreAction<State, State>(({ bindFirestoreRef }) =>
bindFirestoreRef('decks', firebase.firestore().collection('decks')),
),
LOG_IN: firestoreAction<State, State>(({ bindFirestoreRef }, user: User) => {
const doc = firebase
.firestore()
.collection('users')
.doc(user.id);
// Create a new doc for the user if it's his/her first time
doc.get().then((snapshot) => {
if (!snapshot.exists) {
doc.set({ name: user.name, photoUrl: user.photoUrl, isAdmin: false });
}
});
return bindFirestoreRef('user', doc);
}),
LOG_OUT: firestoreAction<State, State>(({ unbindFirestoreRef }) =>
unbindFirestoreRef('user'),
),
async ADD_CARD(
{ getters }: { getters: Getters },
{ deckId, front, back }: { deckId: string; front: string; back: string },
) {
await firebase
.firestore()
.collection('decks')
.doc(deckId)
.update({
cards: [
...getters.getDeckById(deckId).cards,
{
front,
back,
},
],
});
},
async UPDATE_CARD(
{ getters }: { getters: Getters },
{
deckId,
cardIdx,
front,
back,
}: { deckId: string; cardIdx: number; front: string; back: string },
) {
const cards = getters.getDeckById(deckId).cards;
cards[cardIdx] = { front, back };
await firebase
.firestore()
.collection('decks')
.doc(deckId)
.update({
cards,
});
},
async ADD_DECK(_: any, { title, tags }: { title: string; tags: string[] }) {
const doc = firebase
.firestore()
.collection('decks')
.doc();
await doc.set({
title,
tags,
cards: [],
});
return doc.id;
},
};
|
ZappRx/material-ui-pickers
|
lib/src/DateTimePicker/components/DateTimePickerHeader.tsx
|
import { Theme } from '@material-ui/core';
import createStyles from '@material-ui/core/styles/createStyles';
import withStyles, { WithStyles } from '@material-ui/core/styles/withStyles';
import * as PropTypes from 'prop-types';
import * as React from 'react';
import PickerToolbar from '../../_shared/PickerToolbar';
import ToolbarButton from '../../_shared/ToolbarButton';
import { withUtils, WithUtilsProps } from '../../_shared/WithUtils';
import DateTimePickerView, { DateTimePickerViewType } from '../../constants/DateTimePickerView';
import { MaterialUiPickersDate } from '../../typings/date';
export const styles = (theme: Theme) =>
createStyles({
toolbar: {
flexDirection: 'row',
alignItems: 'center',
paddingLeft: 16,
paddingRight: 16,
justifyContent: 'space-around',
},
separator: {
margin: '0 4px 0 2px',
cursor: 'default',
},
ampmSelection: {
top: 9,
position: 'relative',
marginLeft: 10,
marginRight: -10,
},
ampmLabel: {
fontSize: 18,
},
hourMinuteLabel: {
top: 5,
position: 'relative',
display: 'flex',
justifyContent: 'flex-end',
alignItems: 'flex-end',
flexDirection: theme.direction === 'rtl' ? 'row-reverse' : 'row',
},
dateHeader: {
height: 60,
},
timeHeader: {
height: 65,
display: 'flex',
justifyContent: 'flex-end',
alignItems: 'flex-end',
},
});
export type MeridiemMode = 'am' | 'pm';
export interface DateTimePickerHeaderProps extends WithUtilsProps, WithStyles<typeof styles> {
date: MaterialUiPickersDate;
meridiemMode: MeridiemMode;
openView: DateTimePickerViewType;
onOpenViewChange: (view: DateTimePickerView) => void;
setMeridiemMode: (mode: MeridiemMode) => () => void;
ampm?: boolean;
}
export const DateTimePickerHeader: React.SFC<DateTimePickerHeaderProps> = ({
date,
classes,
openView,
meridiemMode,
onOpenViewChange,
setMeridiemMode,
utils,
ampm,
}) => {
return (
<PickerToolbar className={classes.toolbar}>
<div className={classes.dateHeader}>
<ToolbarButton
variant="subtitle1"
onClick={() => onOpenViewChange(DateTimePickerView.YEAR)}
selected={openView === DateTimePickerView.YEAR}
label={utils.getYearText(date)}
/>
<ToolbarButton
variant="h4"
onClick={() => onOpenViewChange(DateTimePickerView.DATE)}
selected={openView === DateTimePickerView.DATE}
label={utils.getDateTimePickerHeaderText(date)}
/>
</div>
<div className={classes.timeHeader}>
<div className={classes.hourMinuteLabel}>
<ToolbarButton
variant="h3"
onClick={() => onOpenViewChange(DateTimePickerView.HOUR)}
selected={openView === DateTimePickerView.HOUR}
label={utils.getHourText(date, ampm!)}
/>
<ToolbarButton variant="h3" label=":" selected={false} className={classes.separator} />
<ToolbarButton
variant="h3"
onClick={() => onOpenViewChange(DateTimePickerView.MINUTES)}
selected={openView === DateTimePickerView.MINUTES}
label={utils.getMinuteText(date)}
/>
</div>
{ampm && (
<div className={classes.ampmSelection}>
<ToolbarButton
className={classes.ampmLabel}
selected={meridiemMode === 'am'}
variant="subtitle1"
label={utils.getMeridiemText('am')}
onClick={setMeridiemMode('am')}
/>
<ToolbarButton
className={classes.ampmLabel}
selected={meridiemMode === 'pm'}
variant="subtitle1"
label={utils.getMeridiemText('pm')}
onClick={setMeridiemMode('pm')}
/>
</div>
)}
</div>
</PickerToolbar>
);
};
(DateTimePickerHeader as any).propTypes = {
date: PropTypes.object.isRequired,
classes: PropTypes.object.isRequired,
meridiemMode: PropTypes.string.isRequired,
openView: PropTypes.string.isRequired,
onOpenViewChange: PropTypes.func.isRequired,
setMeridiemMode: PropTypes.func.isRequired,
utils: PropTypes.object.isRequired,
ampm: PropTypes.bool,
innerRef: PropTypes.any,
};
DateTimePickerHeader.defaultProps = {
ampm: true,
};
export default withStyles(styles, { name: 'MuiPickerDTHeader' })(withUtils()(DateTimePickerHeader));
|
ZappRx/material-ui-pickers
|
lib/src/_shared/DateTextField.tsx
|
<filename>lib/src/_shared/DateTextField.tsx
import Icon from '@material-ui/core/Icon';
import IconButton from '@material-ui/core/IconButton';
import InputAdornment from '@material-ui/core/InputAdornment';
import TextField, { BaseTextFieldProps, StandardTextFieldProps } from '@material-ui/core/TextField';
import * as PropTypes from 'prop-types';
import * as React from 'react';
import { FilledInputProps } from '@material-ui/core/FilledInput';
import { InputProps as InputPropsType } from '@material-ui/core/Input';
import { OutlinedInputProps } from '@material-ui/core/OutlinedInput';
import DomainPropTypes, { DateType } from '../constants/prop-types';
import { MaterialUiPickersDate } from '../typings/date';
import { ExtendMui } from '../typings/extendMui';
import MaskedInput from './MaskedInput';
import { withUtils, WithUtilsProps } from './WithUtils';
const getDisplayDate = ({
utils,
value,
format,
invalidLabel,
emptyLabel,
labelFunc,
}: DateTextFieldProps) => {
const isEmpty = value === null;
const date = utils.date(value);
if (labelFunc) {
return labelFunc(isEmpty ? null : date, invalidLabel!);
}
if (isEmpty) {
return emptyLabel;
}
return utils.isValid(date) ? utils.format(date, format) : invalidLabel;
};
const getError = (value: MaterialUiPickersDate, props: DateTextFieldProps): React.ReactNode => {
const {
utils,
maxDate,
minDate,
disablePast,
disableFuture,
maxDateMessage,
minDateMessage,
invalidDateMessage,
} = props;
if (!utils.isValid(value)) {
// if null - do not show error
if (utils.isNull(value)) {
return '';
}
return invalidDateMessage;
}
if (
(maxDate && utils.isAfter(value, utils.endOfDay(utils.date(maxDate)))) ||
(disableFuture && utils.isAfter(value, utils.endOfDay(utils.date())))
) {
return maxDateMessage;
}
if (
(minDate && utils.isBefore(value, utils.startOfDay(utils.date(minDate)))) ||
(disablePast && utils.isBefore(value, utils.startOfDay(utils.date())))
) {
return minDateMessage;
}
return '';
};
export interface DateTextFieldProps
extends WithUtilsProps,
ExtendMui<BaseTextFieldProps, 'onError' | 'onChange' | 'value'> {
// Properly extend different variants from mui textfield
variant?: 'outlined' | 'standard' | 'filled';
InputProps?: Partial<InputPropsType | OutlinedInputProps | FilledInputProps>;
inputProps?:
| InputPropsType['inputProps']
| OutlinedInputProps['inputProps']
| FilledInputProps['inputProps'];
value: DateType;
minDate?: DateType;
/** Error message, shown if date is less then minimal date */
minDateMessage?: React.ReactNode;
disablePast?: boolean;
disableFuture?: boolean;
maxDate?: DateType;
/** Error message, shown if date is more then maximal date */
maxDateMessage?: React.ReactNode;
/** Input mask, used in keyboard mode read more <a href="https://github.com/text-mask/text-mask/blob/master/componentDocumentation.md#readme">here</a> */
mask?: any;
pipe?: any;
keepCharPositions?: boolean;
onChange: (date: MaterialUiPickersDate) => void;
onClear?: () => void;
/** On/off manual keyboard input mode */
keyboard?: boolean;
/** Format string */
format: string;
/** Message displaying in text field, if date is invalid (doesn't work in keyboard mode) */
invalidLabel?: string;
/** Message displaying in text field, if null passed (doesn't work in keyboard mode) */
emptyLabel?: string;
/** Do not open picker on enter keypress */
disableOpenOnEnter?: boolean;
/** Dynamic label generation function [(date: Date, invalidLabel: string) => string] */
labelFunc?: (date: MaterialUiPickersDate, invalidLabel: string) => string;
/** Icon displayed for open picker button in keyboard mode */
keyboardIcon?: React.ReactNode;
/** Message, appearing when date cannot be parsed */
invalidDateMessage?: React.ReactNode;
/** If true clear button will be displayed */
clearable?: boolean;
/** Component that should replace the default Material-UI TextField */
TextFieldComponent?:
| React.ComponentType<StandardTextFieldProps>
| React.ReactType<React.HTMLAttributes<any>>;
/** Props to pass to keyboard input adornment */
InputAdornmentProps?: object;
/** Specifies position of keyboard button adornment */
adornmentPosition?: 'start' | 'end';
onClick: (e: React.SyntheticEvent) => void;
/* Callback firing when date that applied in the keyboard is invalid **/
onError?: (newValue: MaterialUiPickersDate, error: React.ReactNode) => void;
/* Callback firing on change input in keyboard mode **/
onInputChange?: (e: React.FormEvent<HTMLInputElement>) => void;
}
export class DateTextField extends React.PureComponent<DateTextFieldProps> {
public static propTypes: any = {
value: PropTypes.oneOfType([
PropTypes.object,
PropTypes.string,
PropTypes.number,
PropTypes.instanceOf(Date),
]),
minDate: DomainPropTypes.date,
maxDate: DomainPropTypes.date,
disablePast: PropTypes.bool,
disableFuture: PropTypes.bool,
format: PropTypes.string,
onBlur: PropTypes.func,
onChange: PropTypes.func.isRequired,
onClear: PropTypes.func,
onClick: PropTypes.func.isRequired,
clearable: PropTypes.bool,
utils: PropTypes.object.isRequired,
disabled: PropTypes.bool,
InputProps: PropTypes.shape({}),
mask: PropTypes.any,
minDateMessage: PropTypes.node,
maxDateMessage: PropTypes.node,
invalidLabel: PropTypes.string,
emptyLabel: PropTypes.string,
labelFunc: PropTypes.func,
keyboard: PropTypes.bool,
keyboardIcon: PropTypes.node,
disableOpenOnEnter: PropTypes.bool,
invalidDateMessage: PropTypes.node,
TextFieldComponent: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
InputAdornmentProps: PropTypes.object,
adornmentPosition: PropTypes.oneOf(['start', 'end']),
onError: PropTypes.func,
onInputChange: PropTypes.func,
pipe: PropTypes.func,
keepCharPositions: PropTypes.bool,
};
public static defaultProps = {
disabled: false,
invalidLabel: 'Unknown',
emptyLabel: '',
value: new Date(),
labelFunc: undefined,
format: undefined,
InputProps: undefined,
keyboard: false,
mask: undefined,
keyboardIcon: 'event',
disableOpenOnEnter: false,
invalidDateMessage: 'Invalid Date Format',
clearable: false,
onBlur: undefined,
onClear: undefined,
disablePast: false,
disableFuture: false,
onError: undefined,
onInputChange: undefined,
minDate: '1900-01-01',
maxDate: '2100-01-01',
minDateMessage: 'Date should not be before minimal date',
maxDateMessage: 'Date should not be after maximal date',
TextFieldComponent: TextField,
InputAdornmentProps: {},
adornmentPosition: 'end',
pipe: undefined,
keepCharPositions: false,
};
public static updateState = (props: DateTextFieldProps) => ({
value: props.value,
displayValue: getDisplayDate(props),
error: getError(props.utils.date(props.value), props),
});
public state = DateTextField.updateState(this.props);
public componentDidUpdate(prevProps: DateTextFieldProps) {
if (
!this.props.utils.isEqual(this.props.value, prevProps.value) ||
prevProps.format !== this.props.format ||
prevProps.maxDate !== this.props.maxDate ||
prevProps.minDate !== this.props.minDate ||
prevProps.emptyLabel !== this.props.emptyLabel ||
prevProps.utils !== this.props.utils
) {
this.setState(DateTextField.updateState(this.props));
}
}
public commitUpdates = (value: string) => {
const { onChange, clearable, onClear, utils, format, onError } = this.props;
if (value === '') {
if (this.props.value === null) {
this.setState(DateTextField.updateState(this.props));
} else if (clearable && onClear) {
onClear();
}
return;
}
const oldValue = utils.date(this.state.value);
const newValue = utils.parse(value, format);
const error = getError(newValue, this.props);
this.setState(
{
error,
displayValue: value,
value: error ? newValue : oldValue,
},
() => {
if (!error && !utils.isEqual(newValue, oldValue)) {
onChange(newValue);
}
if (error && onError) {
onError(newValue, error);
}
}
);
};
public handleBlur = (e: React.ChangeEvent<HTMLInputElement>) => {
if (this.props.keyboard) {
e.preventDefault();
e.stopPropagation();
this.commitUpdates(e.target.value);
if (this.props.onBlur) {
this.props.onBlur(e);
}
}
};
public handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { utils, format, onInputChange } = this.props;
const parsedValue = utils.parse(e.target.value, format);
if (onInputChange) {
onInputChange(e);
}
this.setState({
displayValue: e.target.value,
error: getError(parsedValue, this.props),
});
};
public handleFocus = (e: React.SyntheticEvent) => {
e.stopPropagation();
e.preventDefault();
if (!this.props.keyboard) {
this.openPicker(e);
}
};
public handleKeyPress = (e: React.KeyboardEvent<HTMLDivElement>) => {
if (e.key === 'Enter') {
if (!this.props.disableOpenOnEnter) {
this.openPicker(e);
} else {
// @ts-ignore TODO check me
this.commitUpdates(e.target.value);
}
}
};
public openPicker = (e: React.SyntheticEvent) => {
const { disabled, onClick } = this.props;
if (!disabled) {
onClick!(e);
}
};
public render() {
const {
adornmentPosition,
clearable,
disabled,
disableFuture,
disableOpenOnEnter,
disablePast,
emptyLabel,
format,
InputAdornmentProps,
InputProps,
invalidDateMessage,
invalidLabel,
keyboard,
keyboardIcon,
labelFunc,
mask,
maxDate,
maxDateMessage,
minDate,
minDateMessage,
onBlur,
onClear,
onClick,
pipe,
keepCharPositions,
TextFieldComponent,
utils,
value,
onInputChange,
...other
} = this.props;
const { displayValue, error } = this.state;
const localInputProps = {
inputComponent: MaskedInput,
inputProps: {
mask: !keyboard ? null : mask,
pipe: !keyboard ? null : pipe,
keepCharPositions: !keyboard ? undefined : keepCharPositions,
readOnly: !keyboard,
},
};
if (keyboard) {
localInputProps[`${adornmentPosition}Adornment`] = (
<InputAdornment position={adornmentPosition!} {...InputAdornmentProps}>
<IconButton disabled={disabled} onClick={this.openPicker}>
<Icon> {keyboardIcon} </Icon>
</IconButton>
</InputAdornment>
);
}
const Component = TextFieldComponent!;
const inputProps = {
...localInputProps,
...InputProps,
} as Partial<InputPropsType>;
return (
<Component
onClick={this.handleFocus}
error={!!error}
helperText={error}
onKeyPress={this.handleKeyPress}
onBlur={this.handleBlur}
disabled={disabled}
value={displayValue}
{...other}
onError={undefined}
onChange={this.handleChange}
InputProps={inputProps}
/>
);
}
}
// @ts-ignore ts requires to duplicate proptypes of textfield
export default withUtils()(DateTextField);
|
ZappRx/material-ui-pickers
|
docs/src/App.tsx
|
import * as React from 'react';
import Layout from './layout/Layout';
import Router from './Pages/Router';
import { createMuiTheme, MuiThemeProvider } from '@material-ui/core';
interface AppState {
direction: 'rtl' | 'ltr';
theme: 'light' | 'dark';
}
class App extends React.Component<{}, AppState> {
state: AppState = {
direction: 'ltr',
theme: 'light',
};
toggleDirection = () => {
const newDirection = this.state.direction === 'ltr' ? 'rtl' : 'ltr';
document.body.dir = newDirection;
this.setState({ direction: newDirection });
};
toggleTheme = () => {
this.setState({
theme: this.state.theme === 'light' ? 'dark' : 'light',
});
};
createMuiTheme = () => {
const { theme, direction } = this.state;
return createMuiTheme({
direction,
palette: {
type: theme,
},
});
};
render() {
return (
<MuiThemeProvider theme={this.createMuiTheme()}>
<Layout toggleDirection={this.toggleDirection} toggleThemeType={this.toggleTheme}>
<Router />
</Layout>
</MuiThemeProvider>
);
}
}
export default App;
|
ZappRx/material-ui-pickers
|
lib/src/DatePicker/DatePickerModal.tsx
|
<gh_stars>0
import * as PropTypes from 'prop-types';
import * as React from 'react';
import { Omit } from '@material-ui/core';
import BasePicker, { BasePickerProps } from '../_shared/BasePicker';
import DomainPropTypes from '../constants/prop-types';
import ModalWrapper, { ModalWrapperProps } from '../wrappers/ModalWrapper';
import DatePicker, { BaseDatePickerProps } from './DatePicker';
export interface DatePickerModalProps
extends BasePickerProps,
BaseDatePickerProps,
Omit<ModalWrapperProps, 'onChange' | 'value'> {}
export const DatePickerModal: React.SFC<DatePickerModalProps> = props => {
const {
allowKeyboardControl,
animateYearScrolling,
autoOk,
disableFuture,
disablePast,
format,
forwardedRef,
labelFunc,
leftArrowIcon,
maxDate,
minDate,
initialFocusedDate,
onChange,
openToYearSelection,
renderDay,
rightArrowIcon,
shouldDisableDate,
value,
...other
} = props;
return (
<BasePicker {...props}>
{({
date,
utils,
handleAccept,
handleChange,
handleClear,
handleDismiss,
handleSetTodayDate,
handleTextFieldChange,
isAccepted,
}) => (
<ModalWrapper
disableFuture={disableFuture}
disablePast={disablePast}
format={format || utils.dateFormat}
labelFunc={labelFunc}
maxDate={maxDate}
minDate={minDate}
onAccept={handleAccept}
onChange={handleTextFieldChange}
onClear={handleClear}
onDismiss={handleDismiss}
onSetToday={handleSetTodayDate}
ref={forwardedRef}
value={value}
isAccepted={isAccepted}
{...other}
>
<DatePicker
date={date}
allowKeyboardControl={allowKeyboardControl}
animateYearScrolling={animateYearScrolling}
disableFuture={disableFuture}
disablePast={disablePast}
leftArrowIcon={leftArrowIcon}
maxDate={maxDate}
minDate={minDate}
onChange={handleChange}
openToYearSelection={openToYearSelection}
renderDay={renderDay}
rightArrowIcon={rightArrowIcon}
shouldDisableDate={shouldDisableDate}
/>
</ModalWrapper>
)}
</BasePicker>
);
};
(DatePickerModal as any).propTypes = {
value: DomainPropTypes.date,
minDate: DomainPropTypes.date,
maxDate: DomainPropTypes.date,
initialFocusedDate: DomainPropTypes.date,
format: PropTypes.string,
onChange: PropTypes.func.isRequired,
autoOk: PropTypes.bool,
disablePast: PropTypes.bool,
disableFuture: PropTypes.bool,
animateYearScrolling: PropTypes.bool,
openToYearSelection: PropTypes.bool,
labelFunc: PropTypes.func,
leftArrowIcon: PropTypes.node,
rightArrowIcon: PropTypes.node,
renderDay: PropTypes.func,
shouldDisableDate: PropTypes.func,
allowKeyboardControl: PropTypes.bool,
forwardedRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
};
DatePickerModal.defaultProps = {
value: new Date(),
format: undefined,
autoOk: false,
minDate: '1900-01-01',
maxDate: '2100-01-01',
initialFocusedDate: undefined,
disableFuture: false,
disablePast: false,
animateYearScrolling: false,
openToYearSelection: false,
allowKeyboardControl: true,
leftArrowIcon: 'keyboard_arrow_left',
rightArrowIcon: 'keyboard_arrow_right',
renderDay: undefined,
labelFunc: undefined,
shouldDisableDate: undefined,
forwardedRef: undefined,
};
export default React.forwardRef((props: DatePickerModalProps, ref) => (
<DatePickerModal {...props} forwardedRef={ref} />
));
|
ZappRx/material-ui-pickers
|
lib/src/__tests__/e2e/DateTimePickerInline.test.tsx
|
import { PopoverProps } from '@material-ui/core/Popover';
import { ReactWrapper } from 'enzyme';
import * as React from 'react';
import DateTimePickerInline, {
DateTimePickerInlineProps,
} from '../../DateTimePicker/DateTimePickerInline';
import { mount, utilsToUse } from '../test-utils';
describe('e2e - DateTimePickerInline', () => {
let component: ReactWrapper<DateTimePickerInlineProps>;
const onChangeMock = jest.fn();
const onCloseMock = jest.fn();
const onOpenMock = jest.fn();
beforeEach(() => {
jest.clearAllMocks();
component = mount(
<DateTimePickerInline
onChange={onChangeMock}
onClose={onCloseMock}
onOpen={onOpenMock}
value={utilsToUse.date('2018-01-01T00:00:00.000Z')}
/>
);
});
it('Should renders', () => {
expect(component).toBeTruthy();
});
it('Should open modal with picker on click', () => {
component.find('input').simulate('click');
expect(component.find('WithStyles(Popover)').props().open).toBeTruthy();
expect(onOpenMock).toHaveBeenCalled();
});
it('Should close on popover close request', () => {
const popoverOnClose = (component.find('WithStyles(Popover)').props() as PopoverProps).onClose;
if (!popoverOnClose) {
throw new Error('expected popoverOnClose');
}
popoverOnClose({} as any);
expect(component.find('WithStyles(Popover)').props().open).toBeFalsy();
expect(onCloseMock).toHaveBeenCalled();
});
it('Should get the full workflow for datetime picker', () => {
// Date
component.find('input').simulate('click');
component
.find('Day button')
.at(10)
.simulate('click');
expect(component.find('Clock').prop('type')).toBe('hours');
// Hour
component
.find('Clock div[role="menu"]')
.simulate('mouseUp', { nativeEvent: { offsetX: 10, offsetY: 20 } });
expect(component.find('Clock').prop('type')).toBe('minutes');
// Minutes
component
.find('Clock div[role="menu"]')
.simulate('mouseUp', { nativeEvent: { offsetX: 10, offsetY: 20 } });
expect(onChangeMock).toHaveBeenCalled();
});
});
|
ZappRx/material-ui-pickers
|
lib/src/index.ts
|
<reponame>ZappRx/material-ui-pickers
export { default as DatePicker, InlineDatePicker } from './DatePicker';
export { default as TimePicker, InlineTimePicker } from './TimePicker';
export { default as DateTimePicker, InlineDateTimePicker } from './DateTimePicker';
export { default as BasePicker } from './_shared/BasePicker';
export { default as Calendar } from './DatePicker/components/Calendar';
export { default as Day } from './DatePicker/components/Day';
export { default as TimePickerView } from './TimePicker/components/TimePickerView';
export { default as Clock } from './TimePicker/components/Clock';
export { default as MuiPickersUtilsProvider } from './MuiPickersUtilsProvider';
|
ZappRx/material-ui-pickers
|
docs/src/index.tsx
|
<gh_stars>0
import * as React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { MuiPickersUtilsProvider } from 'material-ui-pickers';
import Utils from '@date-io/date-fns';
import { BrowserRouter } from 'react-router-dom';
import { create } from 'jss';
import rtl from 'jss-rtl';
import JssProvider from 'react-jss/lib/JssProvider';
import { createGenerateClassName, jssPreset } from '@material-ui/core/styles';
// @ts-ignore
window.__MUI_USE_NEXT_TYPOGRAPHY_VARIANTS__ = true;
// @ts-ignore Configure JSS
const jss = create({ plugins: [...jssPreset().plugins, rtl()] });
// Custom Material-UI class name generator.
const generateClassName = createGenerateClassName();
ReactDOM.render(
<BrowserRouter>
<JssProvider jss={jss} generateClassName={generateClassName}>
<MuiPickersUtilsProvider utils={Utils}>
<App />
</MuiPickersUtilsProvider>
</JssProvider>
</BrowserRouter>,
document.getElementById('root')
);
// do not cache the docs
serviceWorker.unregister();
|
jatinpaliwal/webrtc
|
node_modules/webcrypto-core/build/types/ec/ecdh.d.ts
|
import { CryptoKey } from "../key";
import { ProviderKeyUsages } from "../types";
import { EllipticProvider } from "./base";
export declare abstract class EcdhProvider extends EllipticProvider {
readonly name = "ECDH";
usages: ProviderKeyUsages;
namedCurves: string[];
checkAlgorithmParams(algorithm: EcdhKeyDeriveParams): void;
abstract onDeriveBits(algorithm: EcdhKeyDeriveParams, baseKey: CryptoKey, length: number): Promise<ArrayBuffer>;
}
|
jatinpaliwal/webrtc
|
node_modules/webcrypto-core/build/types/aes/ecb.d.ts
|
<filename>node_modules/webcrypto-core/build/types/aes/ecb.d.ts<gh_stars>1-10
import { KeyUsages } from "../types";
import { AesProvider } from "./base";
export declare abstract class AesEcbProvider extends AesProvider {
readonly name = "AES-ECB";
usages: KeyUsages;
abstract onEncrypt(algorithm: Algorithm, key: CryptoKey, data: ArrayBuffer): Promise<ArrayBuffer>;
abstract onDecrypt(algorithm: Algorithm, key: CryptoKey, data: ArrayBuffer): Promise<ArrayBuffer>;
}
|
jatinpaliwal/webrtc
|
node_modules/@peculiar/asn1-schema/build/types/converters.d.ts
|
import { AnyConverterType, IAsnConverter, IntegerConverterType } from "./types";
/**
* NOTE: Converter MUST have name Asn<Asn1PropType.name>Converter.
* Asn1Prop decorator link custom converters by name of the Asn1PropType
*/
/**
* ASN.1 ANY converter
*/
export declare const AsnAnyConverter: IAsnConverter<AnyConverterType>;
/**
* ASN.1 INTEGER to Number/String converter
*/
export declare const AsnIntegerConverter: IAsnConverter<IntegerConverterType>;
/**
* ASN.1 ENUMERATED converter
*/
export declare const AsnEnumeratedConverter: IAsnConverter<number>;
/**
* ASN.1 INTEGER to ArrayBuffer converter
*/
export declare const AsnIntegerArrayBufferConverter: IAsnConverter<ArrayBuffer>;
/**
* ASN.1 BIT STRING converter
*/
export declare const AsnBitStringConverter: IAsnConverter<ArrayBuffer>;
/**
* ASN.1 OBJECT IDENTIFIER converter
*/
export declare const AsnObjectIdentifierConverter: IAsnConverter<string>;
/**
* ASN.1 BOOLEAN converter
*/
export declare const AsnBooleanConverter: IAsnConverter<boolean>;
/**
* ASN.1 OCTET_STRING converter
*/
export declare const AsnOctetStringConverter: IAsnConverter<ArrayBuffer>;
/**
* ASN.1 UTF8_STRING converter
*/
export declare const AsnUtf8StringConverter: IAsnConverter<string, any>;
/**
* ASN.1 BPM STRING converter
*/
export declare const AsnBmpStringConverter: IAsnConverter<string, any>;
/**
* ASN.1 UNIVERSAL STRING converter
*/
export declare const AsnUniversalStringConverter: IAsnConverter<string, any>;
/**
* ASN.1 NUMERIC STRING converter
*/
export declare const AsnNumericStringConverter: IAsnConverter<string, any>;
/**
* ASN.1 PRINTABLE STRING converter
*/
export declare const AsnPrintableStringConverter: IAsnConverter<string, any>;
/**
* ASN.1 TELETEX STRING converter
*/
export declare const AsnTeletexStringConverter: IAsnConverter<string, any>;
/**
* ASN.1 VIDEOTEX STRING converter
*/
export declare const AsnVideotexStringConverter: IAsnConverter<string, any>;
/**
* ASN.1 IA5 STRING converter
*/
export declare const AsnIA5StringConverter: IAsnConverter<string, any>;
/**
* ASN.1 GRAPHIC STRING converter
*/
export declare const AsnGraphicStringConverter: IAsnConverter<string, any>;
/**
* ASN.1 VISIBLE STRING converter
*/
export declare const AsnVisibleStringConverter: IAsnConverter<string, any>;
/**
* ASN.1 GENERAL STRING converter
*/
export declare const AsnGeneralStringConverter: IAsnConverter<string, any>;
/**
* ASN.1 CHARACTER STRING converter
*/
export declare const AsnCharacterStringConverter: IAsnConverter<string, any>;
/**
* ASN.1 UTCTime converter
*/
export declare const AsnUTCTimeConverter: IAsnConverter<Date>;
/**
* ASN.1 GeneralizedTime converter
*/
export declare const AsnGeneralizedTimeConverter: IAsnConverter<Date>;
/**
* ASN.1 ANY converter
*/
export declare const AsnNullConverter: IAsnConverter<null>;
|
jatinpaliwal/webrtc
|
node_modules/@peculiar/asn1-schema/build/types/enums.d.ts
|
/**
* ASN.1 types for classes
*/
export declare enum AsnTypeTypes {
Sequence = 0,
Set = 1,
Choice = 2
}
/**
* ASN.1 types for properties
*/
export declare enum AsnPropTypes {
Any = 0,
Boolean = 1,
OctetString = 2,
BitString = 3,
Integer = 4,
Enumerated = 5,
ObjectIdentifier = 6,
Utf8String = 7,
BmpString = 8,
UniversalString = 9,
NumericString = 10,
PrintableString = 11,
TeletexString = 12,
VideotexString = 13,
IA5String = 14,
GraphicString = 15,
VisibleString = 16,
GeneralString = 17,
CharacterString = 18,
UTCTime = 19,
GeneralizedTime = 20,
DATE = 21,
TimeOfDay = 22,
DateTime = 23,
Duration = 24,
TIME = 25,
Null = 26
}
|
jatinpaliwal/webrtc
|
node_modules/webcrypto-core/build/types/asn1/ec_signature.d.ts
|
<reponame>jatinpaliwal/webrtc
export declare class EcDsaSignature {
static fromWebCryptoSignature(value: BufferSource): EcDsaSignature;
r: ArrayBuffer;
s: ArrayBuffer;
toWebCryptoSignature(pointSize?: number): ArrayBuffer | SharedArrayBuffer;
private getPointSize;
private addPadding;
private removePadding;
}
|
jatinpaliwal/webrtc
|
node_modules/@peculiar/asn1-schema/build/types/schema.d.ts
|
import { AsnRepeatType } from "./decorators";
import { AsnPropTypes, AsnTypeTypes } from "./enums";
import { IAsnConverter, IEmptyConstructor } from "./types";
export interface IAsnSchemaItem {
type: AsnPropTypes | IEmptyConstructor<any>;
optional?: boolean;
defaultValue?: any;
context?: number;
implicit?: boolean;
converter?: IAsnConverter;
repeated?: AsnRepeatType;
}
export interface IAsnSchema {
type: AsnTypeTypes;
items: {
[key: string]: IAsnSchemaItem;
};
schema?: any;
}
export declare class AsnSchemaStorage {
protected items: Map<object, IAsnSchema>;
has(target: object): boolean;
get(target: object): IAsnSchema;
cache(target: object): void;
createDefault(target: object): IAsnSchema;
create(target: object, useNames: boolean): any;
set(target: object, schema: IAsnSchema): this;
protected findParentSchema(target: object): IAsnSchema | null;
}
|
jatinpaliwal/webrtc
|
node_modules/webcrypto-core/build/types/rsa/pss.d.ts
|
import { ProviderKeyUsages } from "../types";
import { RsaProvider } from "./base";
export declare abstract class RsaPssProvider extends RsaProvider {
readonly name = "RSA-PSS";
usages: ProviderKeyUsages;
checkAlgorithmParams(algorithm: RsaPssParams): void;
abstract onSign(algorithm: RsaPssParams, key: CryptoKey, data: ArrayBuffer): Promise<ArrayBuffer>;
abstract onVerify(algorithm: RsaPssParams, key: CryptoKey, signature: ArrayBuffer, data: ArrayBuffer): Promise<boolean>;
}
|
jatinpaliwal/webrtc
|
node_modules/@peculiar/asn1-schema/build/types/types.d.ts
|
<gh_stars>1-10
/**
* ASN1 type
*/
export interface IEmptyConstructor<T> {
new (): T;
}
/**
* Allows to convert ASN.1 object to JS value and back
*/
export interface IAsnConverter<T = any, AsnType = any> {
/**
* Returns JS value from ASN.1 object
* @param value ASN.1 object from asn1js module
*/
fromASN(value: AsnType): T;
/**
* Returns ASN.1 object from JS value
* @param value JS value
*/
toASN(value: T): AsnType;
}
export declare type IntegerConverterType = string | number;
export declare type AnyConverterType = ArrayBuffer | null;
/**
* Allows an object to control its own ASN.1 serialization and deserialization
*/
export interface IAsnConvertible<T = any> {
fromASN(asn: T): this;
toASN(): T;
}
|
jatinpaliwal/webrtc
|
node_modules/@peculiar/asn1-schema/build/types/helper.d.ts
|
import { IAsnConvertible } from "./types";
export declare function isConvertible(target: any): target is IAsnConvertible<any>;
|
jatinpaliwal/webrtc
|
node_modules/webcrypto-core/build/types/aes/gsm.d.ts
|
import { KeyUsages } from "../types";
import { AesProvider } from "./base";
export declare abstract class AesGcmProvider extends AesProvider {
readonly name = "AES-GCM";
usages: KeyUsages;
checkAlgorithmParams(algorithm: AesGcmParams): void;
abstract onEncrypt(algorithm: AesGcmParams, key: CryptoKey, data: ArrayBuffer): Promise<ArrayBuffer>;
abstract onDecrypt(algorithm: AesGcmParams, key: CryptoKey, data: ArrayBuffer): Promise<ArrayBuffer>;
}
|
jatinpaliwal/webrtc
|
node_modules/@peculiar/asn1-schema/build/types/serializer.d.ts
|
/**
* Serializes objects into ASN.1 encoded data
*/
export declare class AsnSerializer {
/**
* Serializes an object to the ASN.1 encoded buffer
* @param obj The object to serialize
*/
static serialize(obj: any): ArrayBuffer;
/**
* Serialize an object to the asn1js object
* @param obj The object to serialize
*/
static toASN(obj: any): any;
}
|
jatinpaliwal/webrtc
|
node_modules/webcrypto-core/build/types/aes/cmac.d.ts
|
<filename>node_modules/webcrypto-core/build/types/aes/cmac.d.ts
import { KeyUsages } from "../types";
import { AesProvider } from "./base";
export declare abstract class AesCmacProvider extends AesProvider {
readonly name = "AES-CMAC";
usages: KeyUsages;
checkAlgorithmParams(algorithm: AesCmacParams): void;
abstract onSign(algorithm: AesCmacParams, key: CryptoKey, data: ArrayBuffer): Promise<ArrayBuffer>;
abstract onVerify(algorithm: AesCmacParams, key: CryptoKey, signature: ArrayBuffer, data: ArrayBuffer): Promise<boolean>;
}
|
jatinpaliwal/webrtc
|
node_modules/pvtsutils/build/types/helper.d.ts
|
<reponame>jatinpaliwal/webrtc<gh_stars>1-10
export declare function assign(target: any, ...sources: any[]): any;
export declare function combine(...buf: ArrayBuffer[]): ArrayBuffer | SharedArrayBuffer;
export declare function isEqual(bytes1: ArrayBuffer, bytes2: ArrayBuffer): boolean;
|
jatinpaliwal/webrtc
|
node_modules/webcrypto-core/build/types/provider.d.ts
|
<gh_stars>1-10
import { CryptoKey } from "./key";
import { KeyUsages, ProviderKeyUsages } from "./types";
export interface IProviderCheckOptions {
keyUsage?: boolean;
}
export declare abstract class ProviderCrypto {
/**
* Name of the algorithm
*/
abstract readonly name: string;
/**
* Key usages for secret key or key pair
*/
abstract readonly usages: ProviderKeyUsages;
digest(algorithm: Algorithm, data: ArrayBuffer): Promise<ArrayBuffer>;
checkDigest(algorithm: Algorithm, data: ArrayBuffer): void;
onDigest(algorithm: Algorithm, data: ArrayBuffer): Promise<ArrayBuffer>;
generateKey(algorithm: Algorithm, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKeyPair | CryptoKey>;
checkGenerateKey(algorithm: Algorithm, extractable: boolean, keyUsages: KeyUsage[]): void;
checkGenerateKeyParams(algorithm: Algorithm): void;
onGenerateKey(algorithm: Algorithm, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKeyPair | CryptoKey>;
sign(algorithm: Algorithm, key: CryptoKey, data: ArrayBuffer): Promise<ArrayBuffer>;
checkSign(algorithm: Algorithm, key: CryptoKey, data: ArrayBuffer): void;
onSign(algorithm: Algorithm, key: CryptoKey, data: ArrayBuffer): Promise<ArrayBuffer>;
verify(algorithm: Algorithm, key: CryptoKey, signature: ArrayBuffer, data: ArrayBuffer): Promise<boolean>;
checkVerify(algorithm: Algorithm, key: CryptoKey, signature: ArrayBuffer, data: ArrayBuffer): void;
onVerify(algorithm: Algorithm, key: CryptoKey, signature: ArrayBuffer, data: ArrayBuffer): Promise<boolean>;
encrypt(algorithm: Algorithm, key: CryptoKey, data: ArrayBuffer, options?: IProviderCheckOptions): Promise<ArrayBuffer>;
checkEncrypt(algorithm: Algorithm, key: CryptoKey, data: ArrayBuffer, options?: IProviderCheckOptions): void;
onEncrypt(algorithm: Algorithm, key: CryptoKey, data: ArrayBuffer): Promise<ArrayBuffer>;
decrypt(algorithm: Algorithm, key: CryptoKey, data: ArrayBuffer, options?: IProviderCheckOptions): Promise<ArrayBuffer>;
checkDecrypt(algorithm: Algorithm, key: CryptoKey, data: ArrayBuffer, options?: IProviderCheckOptions): void;
onDecrypt(algorithm: Algorithm, key: CryptoKey, data: ArrayBuffer): Promise<ArrayBuffer>;
deriveBits(algorithm: Algorithm, baseKey: CryptoKey, length: number, options?: IProviderCheckOptions): Promise<ArrayBuffer>;
checkDeriveBits(algorithm: Algorithm, baseKey: CryptoKey, length: number, options?: IProviderCheckOptions): void;
onDeriveBits(algorithm: Algorithm, baseKey: CryptoKey, length: number): Promise<ArrayBuffer>;
exportKey(format: KeyFormat, key: CryptoKey): Promise<JsonWebKey | ArrayBuffer>;
checkExportKey(format: KeyFormat, key: CryptoKey): void;
onExportKey(format: KeyFormat, key: CryptoKey): Promise<JsonWebKey | ArrayBuffer>;
importKey(format: KeyFormat, keyData: JsonWebKey | ArrayBuffer, algorithm: Algorithm, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>;
checkImportKey(format: KeyFormat, keyData: JsonWebKey | ArrayBuffer, algorithm: Algorithm, extractable: boolean, keyUsages: KeyUsage[]): void;
onImportKey(format: KeyFormat, keyData: JsonWebKey | ArrayBuffer, algorithm: Algorithm, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>;
checkAlgorithmName(algorithm: Algorithm): void;
checkAlgorithmParams(algorithm: Algorithm): void;
checkDerivedKeyParams(algorithm: Algorithm): void;
checkKeyUsages(usages: KeyUsages, allowed: KeyUsages): void;
checkCryptoKey(key: CryptoKey, keyUsage?: KeyUsage): void;
checkRequiredProperty(data: object, propName: string): void;
checkHashAlgorithm(algorithm: Algorithm, hashAlgorithms: string[]): void;
checkImportParams(algorithm: Algorithm): void;
checkKeyFormat(format: any): void;
checkKeyData(format: KeyFormat, keyData: any): void;
protected prepareData(data: any): ArrayBuffer;
}
|
jatinpaliwal/webrtc
|
node_modules/webcrypto-core/build/types/ec/index.d.ts
|
export * from "./base";
export * from "./ecdsa";
export * from "./ecdh";
|
jatinpaliwal/webrtc
|
node_modules/@peculiar/asn1-schema/build/types/index.d.ts
|
export * from "./converters";
export { AsnProp, AsnType } from "./decorators";
export { AsnTypeTypes, AsnPropTypes } from "./enums";
export { AsnParser } from "./parser";
export { AsnSerializer } from "./serializer";
export { IAsnConverter, IAsnConvertible } from "./types";
export * as errors from "./errors";
|
styladev/bcrypt-wasm
|
pkg/bcrypt_fast.d.ts
|
/* tslint:disable */
/**
* @param {string} input
* @param {number} cost
* @returns {string}
*/
export function hash(input: string, cost: number): string;
/**
* @param {string} input
* @param {string} hash
* @returns {boolean}
*/
export function verify(input: string, hash: string): boolean;
|
1010Technologies/pxt-makerbit-motor
|
motor.ts
|
// MakerBit motor driver blocks
const enum MakerBitMotor {
//% block="A"
A = 0,
//% block="B"
B = 1,
//% block="A + B"
All = 2,
}
const enum MakerBitMotorRotation {
//% block="forward"
Forward = 1,
//% block="backward"
Backward = -1,
}
//% color=#0fbc11 icon="\u272a" block="MakerBit"
//% category="MakerBit"
namespace makerbit {
const motorRotations = [
MakerBitMotorRotation.Forward,
MakerBitMotorRotation.Forward,
];
/**
* Sets the speed of a motor.
* @param motor motor, eg: MakerBitMotor.A
* @param speed percentage in the range of -100 to 100, eg: 80
*/
//% subcategory=Motors
//% blockId="makerbit_motor_run" block="run motor %motor | at speed %speed \\%"
//% speed.min=-100
//% speed.max=100
//% weight=90
export function runMotor(motor: MakerBitMotor, speed: number): void {
if (speed === 0) {
stopMotor(motor);
return;
}
const absSpeedPercentage = Math.min(Math.abs(speed), 100);
const analogSpeed = pins.map(absSpeedPercentage, 0, 100, 0, 1023);
if (motor === MakerBitMotor.A || motor === MakerBitMotor.All) {
const isClockwise = speed * motorRotations[MakerBitMotor.A] > 0;
pins.digitalWritePin(DigitalPin.P11, isClockwise ? 1 : 0);
pins.digitalWritePin(DigitalPin.P12, isClockwise ? 0 : 1);
if (speed === 100) {
// Avoid PWM whenever possible as only 3 concurrent PWM outputs are available on the microbit
pins.digitalWritePin(DigitalPin.P13, 1);
} else {
pins.analogWritePin(AnalogPin.P13, analogSpeed);
}
}
if (motor === MakerBitMotor.B || motor === MakerBitMotor.All) {
const isClockwise = speed * motorRotations[MakerBitMotor.B] > 0;
pins.digitalWritePin(DigitalPin.P15, isClockwise ? 1 : 0);
pins.digitalWritePin(DigitalPin.P16, isClockwise ? 0 : 1);
if (speed === 100) {
// Avoid PWM whenever possible as only 3 concurrent PWM outputs are available on the microbit
pins.digitalWritePin(DigitalPin.P14, 1);
} else {
pins.analogWritePin(AnalogPin.P14, analogSpeed);
}
}
}
/**
* Stops a motor.
* @param motor motor, eg: MakerBitMotor.A
*/
//% subcategory=Motors
//% blockId="makerbit_motor_stop" block="stop motor %motor"
//% weight=89
export function stopMotor(motor: MakerBitMotor): void {
if (motor === MakerBitMotor.A || motor === MakerBitMotor.All) {
pins.digitalWritePin(DigitalPin.P11, 0);
pins.digitalWritePin(DigitalPin.P12, 0);
pins.digitalWritePin(DigitalPin.P13, 0);
}
if (motor === MakerBitMotor.B || motor === MakerBitMotor.All) {
pins.digitalWritePin(DigitalPin.P15, 0);
pins.digitalWritePin(DigitalPin.P16, 0);
pins.digitalWritePin(DigitalPin.P14, 0);
}
}
/**
* Sets the rotation direction of a motor. Use this function at start time to configure your motors without the need to rewire.
* @param motor motor, eg: MakerBitMotor.A
* @param rotation rotation of the motor, eg: MakerBitMotorRotation.Forward
*/
//% subcategory=Motors
//% blockId=makerbit_motor_set_rotation block="set motor %motor rotation | to %rotation"
//% weight=88
export function setMotorRotation(
motor: MakerBitMotor,
rotation: MakerBitMotorRotation
) {
if (motor === MakerBitMotor.A || motor === MakerBitMotor.All) {
motorRotations[MakerBitMotor.A] = rotation;
}
if (motor === MakerBitMotor.B || motor === MakerBitMotor.All) {
motorRotations[MakerBitMotor.B] = rotation;
}
}
}
|
clov3r/datum
|
test/OneShot.ts
|
<filename>test/OneShot.ts
import * as assert from 'assert';
import { left, right } from 'fp-ts/es6/Either';
import { eqNumber } from 'fp-ts/es6/Eq';
import { identity } from 'fp-ts/es6/function';
import { monoidString, monoidSum } from 'fp-ts/es6/Monoid';
import { none, some, option } from 'fp-ts/es6/Option';
import { ordString } from 'fp-ts/es6/Ord';
import { pipe } from 'fp-ts/es6/pipeable';
import { semigroupSum } from 'fp-ts/es6/Semigroup';
import { showString } from 'fp-ts/es6/Show';
import * as I from 'fp-ts/es6/Identity';
import { array } from 'fp-ts/es6/Array';
import * as D from '../src/OneShot';
const predicate = (n: number): boolean => n > 2;
describe('OneShot', () => {
it('URI', () => {
assert.strictEqual(D.URI, '@nll/datum/OneShot');
});
it('creates', () => {
assert.deepStrictEqual(D.initial, { _tag: 'Initial' });
assert.deepStrictEqual(D.pending, { _tag: 'Pending' });
assert.deepStrictEqual(D.constInitial(), { _tag: 'Initial' });
assert.deepStrictEqual(D.constPending(), { _tag: 'Pending' });
assert.deepStrictEqual(D.complete(1), { _tag: 'Complete', value: 1 });
});
it('fold', () => {
const onInitial = () => 'initial';
const onPending = () => `pending`;
const onComplete = (s: string) => `Complete${s.length}`;
const fold = D.fold(onInitial, onPending, onComplete);
assert.strictEqual(fold(D.initial), 'initial');
assert.strictEqual(fold(D.pending), 'pending');
assert.strictEqual(fold(D.complete('abc')), 'Complete3');
});
it('getOrElse', () => {
assert.strictEqual(
pipe(
D.initial,
D.getOrElse(
() => 0,
() => 1
)
),
0
);
assert.strictEqual(
pipe(
D.pending,
D.getOrElse(
() => 0,
() => 1
)
),
1
);
assert.strictEqual(
pipe(
D.complete(3),
D.getOrElse(
() => 0,
() => 1
)
),
3
);
});
it('getEq', () => {
const { equals } = D.getEq(eqNumber);
assert.strictEqual(equals(D.initial, D.initial), true);
assert.strictEqual(equals(D.initial, D.pending), false);
assert.strictEqual(equals(D.initial, D.complete(1)), false);
assert.strictEqual(equals(D.pending, D.initial), false);
assert.strictEqual(equals(D.pending, D.pending), true);
assert.strictEqual(equals(D.pending, D.complete(2)), false);
assert.strictEqual(equals(D.complete(1), D.initial), false);
assert.strictEqual(equals(D.complete(1), D.pending), false);
assert.strictEqual(equals(D.complete(1), D.complete(1)), true);
});
it('map', () => {
const f = (n: number) => n * 2;
assert.deepStrictEqual(D.OneShot.map(D.initial, f), D.initial);
assert.deepStrictEqual(D.OneShot.map(D.pending, f), D.pending);
assert.deepStrictEqual(D.OneShot.map(D.complete(2), f), D.complete(4));
});
it('getOrd', () => {
const { compare } = D.getOrd(ordString);
assert.deepStrictEqual(compare(D.initial, D.initial), 0);
assert.deepStrictEqual(compare(D.initial, D.pending), -1);
assert.deepStrictEqual(compare(D.initial, D.complete('a')), -1);
assert.deepStrictEqual(compare(D.pending, D.initial), 1);
assert.deepStrictEqual(compare(D.pending, D.pending), 0);
assert.deepStrictEqual(compare(D.pending, D.complete('a')), -1);
assert.deepStrictEqual(compare(D.complete('a'), D.initial), 1);
assert.deepStrictEqual(compare(D.complete('a'), D.pending), 1);
assert.deepStrictEqual(compare(D.complete('a'), D.complete('a')), 0);
assert.deepStrictEqual(compare(D.complete('a'), D.complete('b')), -1);
});
/**
* 1. Identity: `A.ap(A.of(a => a), fa) = fa`
* 2. Homomorphism: `A.ap(A.of(ab), A.of(a)) = A.of(ab(a))`
* 3. Interchange: `A.ap(fab, A.of(a)) = A.ap(A.of(ab => ab(a)), fab)`
*/
it('ap', () => {
const f = (n: number) => n * 2;
assert.deepStrictEqual(D.OneShot.ap(D.initial, D.initial), D.initial);
assert.deepStrictEqual(D.OneShot.ap(D.initial, D.pending), D.initial);
assert.deepStrictEqual(D.OneShot.ap(D.initial, D.complete(1)), D.initial);
assert.deepStrictEqual(D.OneShot.ap(D.pending, D.initial), D.initial);
assert.deepStrictEqual(D.OneShot.ap(D.pending, D.pending), D.pending);
assert.deepStrictEqual(D.OneShot.ap(D.pending, D.complete(1)), D.pending);
assert.deepStrictEqual(D.OneShot.ap(D.complete(f), D.initial), D.initial);
assert.deepStrictEqual(D.OneShot.ap(D.complete(f), D.pending), D.pending);
assert.deepStrictEqual(
D.OneShot.ap(D.complete(f), D.complete(1)),
D.complete(2)
);
});
it('chain', () => {
const f = (n: number) => D.complete(n * 2);
const g = () => D.initial;
assert.deepStrictEqual(D.OneShot.chain(D.initial, f), D.initial);
assert.deepStrictEqual(D.OneShot.chain(D.initial, g), D.initial);
assert.deepStrictEqual(D.OneShot.chain(D.pending, f), D.pending);
assert.deepStrictEqual(D.OneShot.chain(D.pending, g), D.pending);
assert.deepStrictEqual(D.OneShot.chain(D.complete(1), f), D.complete(2));
assert.deepStrictEqual(D.OneShot.chain(D.complete(1), g), D.initial);
});
/**
* `Alt` instances are required to satisfy the following laws:
*
* 1. Associativity: `A.alt(A.alt(fa, ga), ha) = A.alt(fa, A.alt(ga, ha))`
* 2. Distributivity: `A.map(A.alt(fa, ga), ab) = A.alt(A.map(fa, ab), A.map(ga, ab))`
*/
it('alt', () => {
const f = (n: number) => n * 2;
const alt = D.OneShot.alt;
const map = D.OneShot.map;
assert.deepStrictEqual(
alt(
alt(D.initial, () => D.pending),
() => D.pending
),
alt(D.initial, () => alt(D.pending, () => D.pending))
);
assert.deepStrictEqual(
alt(
alt(D.pending, () => D.initial),
() => D.pending
),
alt(D.pending, () => alt(D.initial, () => D.pending))
);
assert.deepStrictEqual(
alt(
alt(D.pending, () => D.complete(1)),
() => D.pending
),
alt(D.pending, () => alt(D.complete(1), () => D.pending))
);
assert.deepStrictEqual(
map(
alt(D.initial, () => D.pending),
f
),
alt(map(D.initial, f), () => map(D.pending, f))
);
assert.deepStrictEqual(
map(
alt(D.pending, () => D.initial),
f
),
alt(map(D.pending, f), () => map(D.initial, f))
);
assert.deepStrictEqual(
map(
alt(D.initial, () => D.complete(1)),
f
),
alt(map(D.initial, f), () => map(D.complete(1), f))
);
});
it('extend', () => {
const f = D.getOrElse(
() => 0,
() => 1
);
assert.deepStrictEqual(D.OneShot.extend(D.complete(2), f), D.complete(2));
assert.deepStrictEqual(D.OneShot.extend(D.initial, f), D.complete(0));
});
it('fromNullable', () => {
assert.deepStrictEqual(D.fromNullable(2), D.complete(2));
assert.deepStrictEqual(D.fromNullable(null), D.initial);
assert.deepStrictEqual(D.fromNullable(undefined), D.initial);
});
// TODO Fix these tests!
it('traverse', () => {
assert.deepStrictEqual(
D.OneShot.traverse(option)(D.initial, () => none),
some(D.initial)
);
assert.deepStrictEqual(
D.OneShot.traverse(option)(D.pending, () => none),
some(D.pending)
);
assert.deepStrictEqual(
D.OneShot.traverse(option)(D.complete('foo'), (a) =>
a.length >= 2 ? some(a) : none
),
some(D.complete('foo'))
);
assert.deepStrictEqual(
D.OneShot.traverse(option)(D.complete(1), (a) =>
a >= 2 ? some(a) : none
),
none
);
assert.deepStrictEqual(
D.OneShot.traverse(option)(D.complete(3), (a) =>
a >= 2 ? some(a) : none
),
some(D.complete(3))
);
});
// TODO Fix these tests!
it('sequence', () => {
assert.deepStrictEqual(D.OneShot.sequence(array)(D.initial), [D.initial]);
assert.deepStrictEqual(D.OneShot.sequence(array)(D.pending), [D.pending]);
assert.deepStrictEqual(D.OneShot.sequence(array)(D.complete([1, 2])), [
D.complete(1),
D.complete(2),
]);
});
it('reduce', () => {
assert.strictEqual(
D.OneShot.reduce(D.initial, 2, (b, a) => b + a),
2
);
assert.strictEqual(
D.OneShot.reduce(D.pending, 2, (b, a) => b + a),
2
);
assert.strictEqual(
D.OneShot.reduce(D.complete(3), 2, (b, a) => b + a),
5
);
});
it('foldMap', () => {
const foldMap = D.OneShot.foldMap(monoidString);
assert.strictEqual(foldMap(D.initial, identity), '');
assert.strictEqual(foldMap(D.pending, identity), '');
assert.strictEqual(foldMap(D.complete('a'), identity), 'a');
});
it('reduceRight', () => {
const reduceRight = D.OneShot.reduceRight;
const concat = (a: string, acc: string) => acc + a;
assert.strictEqual(reduceRight(D.initial, 'init', concat), 'init');
assert.strictEqual(reduceRight(D.pending, 'init', concat), 'init');
assert.strictEqual(reduceRight(D.complete('a'), 'init', concat), 'inita');
});
it('getSemigroup', () => {
const S = D.getSemigroup(semigroupSum);
assert.deepStrictEqual(S.concat(D.initial, D.initial), D.initial);
assert.deepStrictEqual(S.concat(D.pending, D.pending), D.pending);
assert.deepStrictEqual(S.concat(D.complete(1), D.initial), D.initial);
assert.deepStrictEqual(S.concat(D.initial, D.complete(1)), D.initial);
assert.deepStrictEqual(
S.concat(D.complete(1), D.complete(2)),
D.complete(3)
);
});
it('getApplySemigroup', () => {
const S = D.getApplySemigroup(semigroupSum);
assert.deepStrictEqual(S.concat(D.initial, D.initial), D.initial);
assert.deepStrictEqual(S.concat(D.pending, D.pending), D.pending);
assert.deepStrictEqual(S.concat(D.complete(1), D.initial), D.initial);
assert.deepStrictEqual(S.concat(D.initial, D.complete(1)), D.initial);
assert.deepStrictEqual(
S.concat(D.complete(1), D.complete(2)),
D.complete(3)
);
});
it('getApplyMonoid', () => {
const M = D.getApplyMonoid(monoidSum);
assert.deepStrictEqual(M.concat(M.empty, D.initial), D.initial);
assert.deepStrictEqual(M.concat(D.initial, M.empty), D.initial);
assert.deepStrictEqual(M.concat(M.empty, D.pending), D.pending);
assert.deepStrictEqual(M.concat(D.pending, M.empty), D.pending);
assert.deepStrictEqual(M.concat(M.empty, D.complete(1)), D.complete(1));
assert.deepStrictEqual(M.concat(D.complete(1), M.empty), D.complete(1));
});
it('elem', () => {
assert.deepStrictEqual(D.elem(eqNumber)(2, D.initial), false);
assert.deepStrictEqual(D.elem(eqNumber)(2, D.pending), false);
assert.deepStrictEqual(D.elem(eqNumber)(2, D.complete(2)), true);
assert.deepStrictEqual(D.elem(eqNumber)(1, D.complete(2)), false);
});
it('isInitial', () => {
assert.deepStrictEqual(D.isInitial(D.initial), true);
assert.deepStrictEqual(D.isInitial(D.pending), false);
assert.deepStrictEqual(D.isInitial(D.complete(1)), false);
});
it('isPending', () => {
assert.deepStrictEqual(D.isPending(D.initial), false);
assert.deepStrictEqual(D.isPending(D.pending), true);
assert.deepStrictEqual(D.isPending(D.complete(1)), false);
});
it('isComplete', () => {
assert.deepStrictEqual(D.isComplete(D.initial), false);
assert.deepStrictEqual(D.isComplete(D.pending), false);
assert.deepStrictEqual(D.isComplete(D.complete(1)), true);
});
it('exists', () => {
const predicate = (a: number) => a === 2;
assert.deepStrictEqual(pipe(D.initial, D.exists(predicate)), false);
assert.deepStrictEqual(pipe(D.complete(1), D.exists(predicate)), false);
assert.deepStrictEqual(pipe(D.complete(2), D.exists(predicate)), true);
});
it('compact', () => {
assert.deepStrictEqual(D.OneShot.compact(D.initial), D.initial);
assert.deepStrictEqual(D.OneShot.compact(D.pending), D.pending);
assert.deepStrictEqual(D.OneShot.compact(D.complete(none)), D.initial);
assert.deepStrictEqual(
D.OneShot.compact(D.complete(some('123'))),
D.complete('123')
);
});
it('separate', () => {
assert.deepStrictEqual(D.OneShot.separate(D.initial), {
left: D.initial,
right: D.initial,
});
assert.deepStrictEqual(D.OneShot.separate(D.pending), {
left: D.initial,
right: D.initial,
});
assert.deepStrictEqual(D.OneShot.separate(D.complete(right('123'))), {
left: D.initial,
right: D.complete('123'),
});
});
it('filter', () => {
const predicate = (a: number) => a === 2;
assert.deepStrictEqual(D.OneShot.filter(D.initial, predicate), D.initial);
assert.deepStrictEqual(
D.OneShot.filter(D.complete(1), predicate),
D.initial
);
assert.deepStrictEqual(
D.OneShot.filter(D.complete(2), predicate),
D.complete(2)
);
});
it('filterMap', () => {
const f = (n: number) => (predicate(n) ? some(n + 1) : none);
assert.deepStrictEqual(D.OneShot.filterMap(D.initial, f), D.initial);
assert.deepStrictEqual(D.OneShot.filterMap(D.complete(1), f), D.initial);
assert.deepStrictEqual(
D.OneShot.filterMap(D.complete(3), f),
D.complete(4)
);
});
it('partition', () => {
assert.deepStrictEqual(D.OneShot.partition(D.initial, predicate), {
left: D.initial,
right: D.initial,
});
assert.deepStrictEqual(D.OneShot.partition(D.complete(1), predicate), {
left: D.complete(1),
right: D.initial,
});
assert.deepStrictEqual(D.OneShot.partition(D.complete(3), predicate), {
left: D.initial,
right: D.complete(3),
});
});
it('partitionMap', () => {
const f = (n: number) => (predicate(n) ? right(n + 1) : left(n - 1));
assert.deepStrictEqual(D.OneShot.partitionMap(D.initial, f), {
left: D.initial,
right: D.initial,
});
assert.deepStrictEqual(D.OneShot.partitionMap(D.complete(1), f), {
left: D.complete(0),
right: D.initial,
});
assert.deepStrictEqual(D.OneShot.partitionMap(D.complete(3), f), {
left: D.initial,
right: D.complete(4),
});
});
// TODO Fix these tests
it('wither', () => {
const witherIdentity = D.OneShot.wither(I.identity);
const f = (n: number) => I.identity.of(predicate(n) ? some(n + 1) : none);
assert.deepStrictEqual(
witherIdentity(D.initial, f),
I.identity.of(D.initial)
);
assert.deepStrictEqual(
witherIdentity(D.pending, f),
I.identity.of(D.pending)
);
assert.deepStrictEqual(
witherIdentity(D.complete(1), f),
I.identity.of(D.initial)
);
assert.deepStrictEqual(
witherIdentity(D.complete(3), f),
I.identity.of(D.complete(4))
);
});
// TODO Fix these tests
it('wilt', () => {
const wiltIdentity = D.OneShot.wilt(I.identity);
const f = (n: number) =>
I.identity.of(predicate(n) ? right(n + 1) : left(n - 1));
assert.deepStrictEqual(
wiltIdentity(D.initial, f),
I.identity.of({ left: D.initial, right: D.initial })
);
assert.deepStrictEqual(
wiltIdentity(D.complete(1), f),
I.identity.of({ left: D.complete(0), right: D.initial })
);
assert.deepStrictEqual(
wiltIdentity(D.complete(3), f),
I.identity.of({ left: D.initial, right: D.complete(4) })
);
});
it('getShow', () => {
const S = D.getShow(showString);
assert.strictEqual(S.show(D.initial), `Initial`);
assert.strictEqual(S.show(D.pending), `Pending`);
assert.strictEqual(S.show(D.complete('a')), `Complete("a")`);
});
it('fromEither', () => {
assert.strictEqual(D.fromEither(left('a')), D.initial);
assert.deepStrictEqual(D.fromEither(right(1)), D.complete(1));
});
});
|
clov3r/datum
|
src/Datum.ts
|
/**
* @since 2.0.0
*
* Represents a value of one of four possible types (a disjoint union).
*
* An instance of `Datum` is either an instance of `Initial`, `Pending`, `Refresh` or `Replete`.
*
* A common use of `Datum` is as a container for dealing with refreshable data values. In this usage,
* the initial value is `Initial`. `Pending` represents in flight activity. `Refresh` indicates
* that data exists but is being refreshed, and `Replete` meands data exists and is not being
* refreshed.
*/
import { Alternative1 } from 'fp-ts/es6/Alternative';
import { Applicative as ApplicativeHKT, Applicative1 } from 'fp-ts/es6/Applicative';
import { Apply1 } from 'fp-ts/es6/Apply';
import { Chain1 } from 'fp-ts/es6/Chain';
import { Compactable1, Separated } from 'fp-ts/es6/Compactable';
import { Either, isLeft, isRight } from 'fp-ts/es6/Either';
import { Eq } from 'fp-ts/es6/Eq';
import { Extend1 } from 'fp-ts/es6/Extend';
import { Filterable1 } from 'fp-ts/es6/Filterable';
import { Foldable1 } from 'fp-ts/es6/Foldable';
import { constFalse, identity, Predicate, constant } from 'fp-ts/es6/function';
import { Functor1 } from 'fp-ts/es6/Functor';
import { HKT } from 'fp-ts/es6/HKT';
import { Monad1 } from 'fp-ts/es6/Monad';
import { MonadThrow1 } from 'fp-ts/es6/MonadThrow';
import { Monoid } from 'fp-ts/es6/Monoid';
import { isSome, Option } from 'fp-ts/es6/Option';
import { Ord } from 'fp-ts/es6/Ord';
import { Ordering } from 'fp-ts/es6/Ordering';
import { pipeable } from 'fp-ts/es6/pipeable';
import { Semigroup } from 'fp-ts/es6/Semigroup';
import { Show } from 'fp-ts/es6/Show';
import { Traversable1 } from 'fp-ts/es6/Traversable';
import { Witherable1 } from 'fp-ts/es6/Witherable';
import { Alt1 } from 'fp-ts/es6/Alt';
/**
* @since 1.0.0
*/
declare module 'fp-ts/es6/HKT' {
interface URItoKind<A> {
'@nll/datum/Datum': Datum<A>;
}
}
/**
* @since 2.0.0
*/
export const URI = '@nll/datum/Datum';
/**
* @since 2.0.0
*/
export type URI = typeof URI;
/**
* @since 2.0.0
*/
export interface Initial {
readonly _tag: 'Initial';
}
/**
* @since 2.0.0
*/
export interface Pending {
readonly _tag: 'Pending';
}
/**
* @since 2.0.0
*/
export interface Refresh<D> {
readonly _tag: 'Refresh';
readonly value: D;
}
/**
* @since 2.0.0
*/
export interface Replete<D> {
readonly _tag: 'Replete';
readonly value: D;
}
/**
* @since 2.0.0
*/
export type Datum<D> = Initial | Pending | Refresh<D> | Replete<D>;
/**
* Constructs an initial `Datum` holding no value.
*
* @since 2.0.0
*/
export const initial: Datum<never> = {
_tag: 'Initial'
};
/**
* Constructs a pending `Datum` holding no value.
*
* @since 2.0.0
*/
export const pending: Datum<never> = {
_tag: 'Pending'
};
/**
* Constructs a new refresh `Datum` holding a value.
*
* @since 2.0.0
*/
export const refresh = <A = never>(value: A): Datum<A> => ({
_tag: 'Refresh',
value
});
/**
* Constructs a new replete `Datum` holding a value.
*
* @since 2.0.0
*/
export const replete = <A = never>(value: A): Datum<A> => ({
_tag: 'Replete',
value
});
/**
* @since 2.0.0
*/
export const constInitial = constant(initial);
/**
* @since 2.0.0
*/
export const constPending = constant(pending);
/**
* Takes a nullable value, if the value is not nully, turn it into a `Replete`, otherwise `Initial`.
*
* @since 2.0.0
*/
export const fromNullable = <A>(a: A | null | undefined): Datum<A> =>
a === null || a === undefined ? initial : replete(a);
/**
* @since 2.0.0
*/
export const fold = <A, B>(
onInitial: () => B,
onPending: () => B,
onRefresh: (v: A) => B,
onReplete: (a: A) => B
) => (ma: Datum<A>): B => {
switch (ma._tag) {
case 'Initial':
return onInitial();
case 'Pending':
return onPending();
case 'Refresh':
return onRefresh(ma.value);
case 'Replete':
return onReplete(ma.value);
}
};
/**
* @since 2.0.0
*/
export const getShow = <A>(S: Show<A>): Show<Datum<A>> => ({
show: fold(
constant('initial'),
constant('pending'),
v => `refresh(${S.show(v)})`,
v => `replete(${S.show(v)})`
)
});
/**
* @since 2.0.0
*/
export const getEq = <A>(E: Eq<A>): Eq<Datum<A>> => ({
equals: (x, y) =>
x === y ||
(isReplete(x) && isReplete(y) && E.equals(x.value, y.value)) ||
(isRefresh(x) && isRefresh(y) && E.equals(x.value, y.value)) ||
(isInitial(x) && isInitial(y)) ||
(isPending(x) && isPending(y))
});
/**
* Viewing Datum as the following progess of state changes:
*
* Initial -> Pending -> Replete -> Refresh [-> Replete -> ...]
*
* This semigroup has a bias towards datums with values and a bias towards Pending/Refresh.
* Notably, concat(Pending, Replete) gives Refresh.
* If both datums have a value, they're combined with the given Semigroup instance.
*
* @since 4.0.0
*/
export const getSemigroup = <A>(S: Semigroup<A>): Semigroup<Datum<A>> => ({
concat: (firstD: Datum<A>, secondD: Datum<A>) =>
fold<A, Datum<A>>(
constant(secondD), // Empty value
() => fold<A, Datum<A>>(
constant(firstD),
constant(secondD),
constant(secondD),
refresh
)(secondD),
first => fold<A, Datum<A>>(
constant(firstD),
constant(firstD),
second => refresh(S.concat(first, second)),
second => refresh(S.concat(first, second))
)(secondD),
first => fold<A, Datum<A>>(
constant(firstD),
constant(refresh(first)),
second => refresh(S.concat(first, second)),
second => replete(S.concat(first, second))
)(secondD)
)(firstD)
});
/**
* See getSemigroup. Empty value of initial.
*
* @since 4.0.0
*/
export const getMonoid = <A>(S: Semigroup<A>): Monoid<Datum<A>> => ({
...getSemigroup(S),
empty: initial
})
const constZero = constant<0>(0);
const constNegOne = constant<-1>(-1);
const constOne = constant<1>(1);
/**
* The `Ord` instance allows `Datum` values to be compared with
* `compare`, whenever there is an `Ord` instance for
* the type the `Datum` contains.
*
* `Initial` < `Pending` < `Refresh` | `Replete`
*
* @since 2.0.0
*/
export function getOrd<A>(O: Ord<A>): Ord<Datum<A>> {
return {
equals: getEq(O).equals,
compare: (xa, ya): Ordering =>
fold<A, Ordering>(
// x Initial
constant(
fold<A, Ordering>(
constZero,
constNegOne,
constNegOne,
constNegOne
)(ya)
),
// x Pending
constant(
fold<A, Ordering>(constOne, constZero, constNegOne, constNegOne)(ya)
),
// x Refresh
x =>
fold<A, Ordering>(
constOne,
constOne,
y => O.compare(x, y),
constNegOne
)(ya),
// x Replete
x =>
fold<A, Ordering>(constOne, constOne, constOne, y => O.compare(x, y))(
ya
)
)(xa)
};
}
/**
* `Apply` semigroup
*
* @since 4.0.0
*
*/
export const getApplySemigroup = <A>(S: Semigroup<A>): Semigroup<Datum<A>> => ({
// TODO: replace with apply.getApplySemigroup if we bump the min supported version of fp-ts >= 2.10
// Or just remove in place of that factory instance
concat: (first: Datum<A>, second: Datum<A>) =>
Apply.ap(
Apply.map(first, (x: A) => (y: A) => S.concat(x, y)),
second
)
})
/**
* Returns `true` if the Async is an instance of `Initial`, `false` otherwise
*
* @since 2.0.0
*/
export const isInitial = <A>(ma: Datum<A>): ma is Initial =>
ma._tag === 'Initial';
/**
* Returns `true` if the Async is an instance of `Pending`, `false` otherwise
*
* @since 2.0.0
*/
export const isPending = <A>(ma: Datum<A>): ma is Pending =>
ma._tag === 'Pending';
/**
* Returns `true` if the Async is an instance of `Refresh`, `false` otherwise
*
* @since 2.0.0
*/
export const isRefresh = <A>(ma: Datum<A>): ma is Refresh<A> =>
ma._tag === 'Refresh';
/**
* Returns `true` if the Async is an instance of `Replete`, `false` otherwise
*
* @since 2.0.0
*/
export const isReplete = <A>(ma: Datum<A>): ma is Replete<A> =>
ma._tag === 'Replete';
/**
* @since 2.0.0
*/
export const isValued = <A>(ma: Datum<A>): ma is Replete<A> | Refresh<A> =>
isReplete(ma) || isRefresh(ma);
/**
* @since 2.0.0
*/
export const getOrElse = <A>(onInitial: () => A, onPending: () => A) => (
ma: Datum<A>
): A => fold<A, A>(onInitial, onPending, identity, identity)(ma);
/**
* @since 2.0.0
*/
export const elem = <A>(E: Eq<A>) => <E>(a: A, ma: Datum<A>): boolean =>
fold<A, boolean>(
constFalse,
constFalse,
b => E.equals(a, b),
b => E.equals(a, b)
)(ma);
/**
* Returns `false` if `Refresh` or returns the result of the application of the given predicate to the `Replete` value.
*
* @since 2.0.0
*/
export const exists = <A>(predicate: Predicate<A>) => <E>(
ma: Datum<A>
): boolean =>
fold<A, boolean>(constFalse, constFalse, predicate, predicate)(ma);
/**
* @since 2.0.0
*/
const mapC = <A, B>(fa: Datum<A>, f: (a: A) => B): Datum<B> =>
fold<A, Datum<B>>(
constInitial,
constPending,
a => refresh(f(a)),
a => replete(f(a))
)(fa);
/**
* @since 3.5.0
*/
const apC = <A, B>(fab: Datum<(a: A) => B>, fa: Datum<A>): Datum<B> => chainC(fab, f => mapC(fa, f))
/**
* @since 2.0.0
*/
const chainC = <A, B>(fa: Datum<A>, f: (a: A) => Datum<B>): Datum<B> =>
fold<A, Datum<B>>(constInitial, constPending, f, f)(fa);
/**
* @since 2.0.0
*/
const reduceC = <A, B>(fa: Datum<A>, b: B, f: (b: B, a: A) => B): B =>
fold<A, B>(
() => b,
() => b,
a => f(b, a),
a => f(b, a)
)(fa);
/**
* @since 2.0.0
*/
const foldMapC = <M>(M: Monoid<M>) => <A>(fa: Datum<A>, f: (a: A) => M): M =>
fold<A, M>(
() => M.empty,
() => M.empty,
f,
f
)(fa);
/**
* @since 2.0.0
*/
const reduceRightC = <A, B>(fa: Datum<A>, b: B, f: (a: A, b: B) => B): B =>
fold<A, B>(
() => b,
() => b,
a => f(a, b),
a => f(a, b)
)(fa);
/**
* @since 2.0.0
*/
const traverseC = <F>(F: ApplicativeHKT<F>) => <A, B>(
ta: Datum<A>,
f: (a: A) => HKT<F, B>
): HKT<F, Datum<B>> =>
fold<A, HKT<F, Datum<B>>>(
() => F.of(initial),
() => F.of(pending),
a => F.map(f(a), refresh),
a => F.map(f(a), replete)
)(ta);
/**
* @since 2.0.0
*/
const sequenceC = <F>(F: ApplicativeHKT<F>) => <A>(
ta: Datum<HKT<F, A>>
): HKT<F, Datum<A>> =>
fold<HKT<F, A>, HKT<F, Datum<A>>>(
() => F.of(initial),
() => F.of(pending),
a => F.map(a, refresh),
a => F.map(a, replete)
)(ta);
/**
* @since 2.0.0
*/
const altC = <A>(fx: Datum<A>, fy: () => Datum<A>): Datum<A> =>
fold<A, Datum<A>>(fy, fy, refresh, replete)(fx);
/**
* @since 2.0.0
*/
const extendC = <A, B>(wa: Datum<A>, f: (wa: Datum<A>) => B): Datum<B> =>
replete(f(wa));
/**
* @since 2.0.0
*/
const compactC = <A>(fa: Datum<Option<A>>): Datum<A> =>
fold<Option<A>, Datum<A>>(
constInitial,
constPending,
a => (isSome(a) ? refresh(a.value) : initial),
a => (isSome(a) ? replete(a.value) : initial)
)(fa);
const defaultSeparate = {
left: initial as Datum<any>,
right: initial as Datum<any>
};
/**
* @since 2.0.0
*/
const separateC = <A, B>(
fa: Datum<Either<A, B>>
): Separated<Datum<A>, Datum<B>> => {
const s = mapC(fa, e => ({
left: isLeft(e) ? replete(e.left) : initial,
right: isRight(e) ? replete(e.right) : initial
}));
return getOrElse(
() => defaultSeparate,
() => defaultSeparate
)(s);
};
/**
* @since 2.0.0
*/
const filterC = <A>(fa: Datum<A>, predicate: Predicate<A>): Datum<A> =>
fold<A, Datum<A>>(
constInitial,
constPending,
a => (predicate(a) ? fa : initial),
a => (predicate(a) ? fa : initial)
)(fa);
/**
* @since 2.0.0
*/
const filterMapC = <A, B>(ma: Datum<A>, f: (a: A) => Option<B>): Datum<B> =>
compactC(mapC(ma, f));
/**
* @since 2.0.0
*/
const partitionC = <A>(
fa: Datum<A>,
predicate: Predicate<A>
): Separated<Datum<A>, Datum<A>> => ({
left: filterC(fa, a => !predicate(a)),
right: filterC(fa, predicate)
});
/**
* @since 2.0.0
*/
const partitionMapC = <A, B, C>(fa: Datum<A>, f: (a: A) => Either<B, C>) =>
separateC(mapC(fa, f));
/**
* @since 2.0.0
*/
const witherC = <F>(F: ApplicativeHKT<F>) => <A, B>(
fa: Datum<A>,
f: (a: A) => HKT<F, Option<B>>
): HKT<F, Datum<B>> =>
fold<A, HKT<F, Datum<B>>>(
constant(F.of(initial)),
constant(F.of(pending)),
a => F.map(f(a), o => (isSome(o) ? refresh(o.value) : initial)),
a => F.map(f(a), o => (isSome(o) ? replete(o.value) : initial))
)(fa);
/**
* @since 2.0.0
*/
const wiltC = <F>(F: ApplicativeHKT<F>) => <A, B, C>(
fa: Datum<A>,
f: (a: A) => HKT<F, Either<B, C>>
): HKT<F, Separated<Datum<B>, Datum<C>>> => {
const s = mapC(fa, a =>
F.map(f(a), e => ({
left: isLeft(e) ? replete(e.left) : initial,
right: isRight(e) ? replete(e.right) : initial
}))
);
return isValued(s) ? s.value : F.of(defaultSeparate);
};
/**
* @since 2.0.0
*/
const throwErrorC = <E, A>(e: E): Datum<A> => initial;
/**
* @since 3.5.0
*/
export const Functor: Functor1<URI> = {
URI,
map: mapC
}
/**
* @since 3.5.0
*
* Note: This instance agrees with the standalone Applicative/Chain/Monad instances but _disagrees_ with the deprecated `datum` mega-instance.
*/
export const Apply: Apply1<URI> = {
...Functor,
ap: apC
}
/**
* @since 3.5.0
*/
export const Chain: Chain1<URI> = {
...Apply,
chain: chainC
}
/**
* @since 3.5.0
*/
export const Applicative: Applicative1<URI> = {
...Apply,
of: replete
}
/**
* @since 3.5.0
*/
export const Alt: Alt1<URI> = {
...Functor,
alt: altC
}
/**
* @since 3.5.0
*/
export const Alternative: Alternative1<URI> = {
...Alt,
...Applicative,
zero: constInitial
}
/**
* @since 3.5.0
*/
export const Monad: Monad1<URI> = {
...Chain,
of: replete
}
/**
* @since 3.5.0
*/
export const MonadThrow: MonadThrow1<URI> = {
...Monad,
throwError: throwErrorC
}
/**
* @since 3.5.0
*/
export const Foldable: Foldable1<URI> = {
URI,
reduce: reduceC,
reduceRight: reduceRightC,
foldMap: foldMapC
}
/**
* @since 3.5.0
*/
export const Traversable: Traversable1<URI> = {
...Functor,
...Foldable,
sequence: sequenceC,
traverse: traverseC
}
/**
* @since 3.5.0
*/
export const Extend: Extend1<URI> = {
...Functor,
extend: extendC
}
/**
* @since 3.5.0
*/
export const Compactable: Compactable1<URI> = {
URI,
compact: compactC,
separate: separateC
}
/**
* @since 3.5.0
*/
export const Filterable: Filterable1<URI> = {
...Functor,
...Compactable,
partition: partitionC,
partitionMap: partitionMapC,
filter: filterC,
filterMap: filterMapC
}
/**
* @since 3.5.0
*/
export const Witherable: Witherable1<URI> = {
...Traversable,
...Filterable,
wilt: wiltC,
wither: witherC
}
const {
ap,
apFirst,
apSecond,
chain,
chainFirst,
flatten,
map,
fromEither,
filterOrElse,
fromOption,
fromPredicate
} = pipeable(MonadThrow);
const {
alt,
} = pipeable(Alt)
const {
foldMap,
reduce,
reduceRight,
} = pipeable(Foldable)
const {
partition,
partitionMap,
compact,
separate,
filter,
filterMap,
} = pipeable(Witherable)
const {
duplicate,
extend,
} = pipeable(Extend)
export {
/**
* @since 2.0.0
*/
alt,
/**
* @since 4.0.0
*/
ap,
/**
* @since 2.0.0
*/
apFirst,
/**
* @since 2.0.0
*/
apSecond,
/**
* @since 2.0.0
*/
chain,
/**
* @since 2.0.0
*/
chainFirst,
/**
* @since 2.0.0
*/
duplicate,
/**
* @since 2.0.0
*/
extend,
/**
* @since 2.0.0
*/
filter,
/**
* @since 2.0.0
*/
filterMap,
/**
* @since 2.0.0
*/
flatten,
/**
* @since 2.0.0
*/
foldMap,
/**
* @since 2.0.0
*/
map,
/**
* @since 2.0.0
*/
partition,
/**
* @since 2.0.0
*/
partitionMap,
/**
* @since 2.0.0
*/
reduce,
/**
* @since 2.0.0
*/
reduceRight,
/**
* @since 2.0.0
*/
compact,
/**
* @since 2.0.0
*/
separate,
/**
* @since 2.0.0
*/
fromEither,
/**
* @since 2.6.0
*/
filterOrElse,
/**
* @since 2.6.0
*/
fromOption,
/**
* @since 2.6.0
*/
fromPredicate
};
|
clov3r/datum
|
examples/sequence.ts
|
<gh_stars>10-100
import { sequenceT } from 'fp-ts/es6/Apply';
import { pipe } from 'fp-ts/es6/pipeable';
import {
DatumEither,
Apply,
failure,
initial,
map,
pending,
success,
toRefresh
} from '../src/DatumEither';
const sequence = sequenceT(Apply);
// Here are some DatumEithers
const someInitial: DatumEither<string, string> = initial; // Type: Initial
const somePending: DatumEither<string, string> = pending; // Type: Pending
const someSuccess: DatumEither<string, string> = success('DATA!'); // Type: Replete<Right<string>>
const someFailure: DatumEither<string, string> = failure('ERROR!'); // Type: Replete<Left<string>>
// Here are some Refreshing Datume
const someRefreshingSuccess = toRefresh(someSuccess); // Type: Refresh<Right<string>>
const someRefreshingFailure = toRefresh(someFailure); // Type: Refresh<Left<string>>
const result1 = pipe(
sequence(someInitial, somePending, someSuccess),
map(([a, b, c]) => a + b + c)
);
console.log(result1);
/**
* The initial short circuits the sequence
* result1 === initial
*/
const result2 = pipe(
sequence(someRefreshingSuccess, someRefreshingFailure),
map(([a, b]) => a + b)
);
console.log(result2);
/**
* The failure shortcircuits the sequence.
* result2 === refresh(left('ERROR!'))
*/
const result3 = pipe(
sequence(someSuccess, someRefreshingSuccess),
map(([a, b]) => a + b)
);
console.log(result3);
/**
* All values are good, so map is called, since one of the DatumEithers is refreshing, the sequence is refreshing
* result3 = refresh(right('DATA!DATA!'))
*/
|
clov3r/datum
|
test/DatumThese.ts
|
import * as assert from 'assert';
import * as DT from '../src/DatumThese';
import { refresh, replete } from '../src/Datum';
import { some, none, option } from 'fp-ts/es6/Option';
import { left, right, both, getSemigroup as theseGetSemigroup } from 'fp-ts/es6/These'
import { monoidSum } from 'fp-ts/es6/Monoid';
import { showNumber, showString } from 'fp-ts/es6/Show';
import { eqNumber, eqString } from 'fp-ts/es6/Eq';
import { Semigroup, semigroupString, semigroupSum } from 'fp-ts/es6/Semigroup';
import { identity } from 'fp-ts/es6/function';
import { DatumThese } from '../src/DatumThese';
import { Apply2C } from 'fp-ts/es6/Apply';
import { Applicative2C } from 'fp-ts/es6/Applicative';
import { Chain2C } from 'fp-ts/es6/Chain';
describe('DatumThese', () => {
it('URI', () => {
assert.strictEqual(DT.URI, '@nll/datum/DatumThese')
})
it('successR', () => {
assert.deepStrictEqual(DT.successR(1), DT.toRefresh(DT.success(1)));
});
it('failureR', () => {
assert.deepStrictEqual(DT.failureR(1), DT.toRefresh(DT.failure(1)));
});
it ('partialSuccessR', () => {
assert.deepStrictEqual(DT.partialSuccessR(1, 1), DT.toRefresh(DT.partialSuccess(1, 1)))
})
it('isInitial', () => {
assert.deepStrictEqual(DT.isInitial(DT.initial), true);
assert.deepStrictEqual(DT.isInitial(DT.pending), false);
assert.deepStrictEqual(DT.isInitial(DT.failure(1)), false);
assert.deepStrictEqual(DT.isInitial(DT.toRefresh(DT.failure(1))), false);
assert.deepStrictEqual(DT.isInitial(DT.success(1)), false);
assert.deepStrictEqual(DT.isInitial(DT.toRefresh(DT.success(1))), false);
assert.deepStrictEqual(DT.isInitial(DT.partialSuccess(1, 1)), false);
assert.deepStrictEqual(DT.isInitial(DT.toRefresh(DT.partialSuccess(1, 1))), false);
});
it('isPending', () => {
assert.deepStrictEqual(DT.isPending(DT.initial), false);
assert.deepStrictEqual(DT.isPending(DT.pending), true);
assert.deepStrictEqual(DT.isPending(DT.failure(1)), false);
assert.deepStrictEqual(DT.isPending(DT.toRefresh(DT.failure(1))), false);
assert.deepStrictEqual(DT.isPending(DT.success(1)), false);
assert.deepStrictEqual(DT.isPending(DT.toRefresh(DT.success(1))), false);
assert.deepStrictEqual(DT.isPending(DT.partialSuccess(1, 1)), false);
assert.deepStrictEqual(DT.isPending(DT.toRefresh(DT.partialSuccess(1, 1))), false);
});
it('isRefresh', () => {
assert.deepStrictEqual(DT.isRefresh(DT.initial), false);
assert.deepStrictEqual(DT.isRefresh(DT.pending), false);
assert.deepStrictEqual(DT.isRefresh(DT.failure(1)), false);
assert.deepStrictEqual(DT.isRefresh(DT.toRefresh(DT.failure(1))), true);
assert.deepStrictEqual(DT.isRefresh(DT.success(1)), false);
assert.deepStrictEqual(DT.isRefresh(DT.toRefresh(DT.success(1))), true);
assert.deepStrictEqual(DT.isRefresh(DT.partialSuccess(1, 1)), false);
assert.deepStrictEqual(DT.isRefresh(DT.toRefresh(DT.partialSuccess(1, 1))), true);
});
it('isReplete', () => {
assert.deepStrictEqual(DT.isReplete(DT.initial), false);
assert.deepStrictEqual(DT.isReplete(DT.pending), false);
assert.deepStrictEqual(DT.isReplete(DT.failure(1)), true);
assert.deepStrictEqual(DT.isReplete(DT.toRefresh(DT.failure(1))), false);
assert.deepStrictEqual(DT.isReplete(DT.success(1)), true);
assert.deepStrictEqual(DT.isReplete(DT.toRefresh(DT.success(1))), false);
assert.deepStrictEqual(DT.isReplete(DT.partialSuccess(1, 1)), true);
assert.deepStrictEqual(DT.isReplete(DT.toRefresh(DT.partialSuccess(1, 1))), false);
});
it('isValued', () => {
assert.deepStrictEqual(DT.isValued(DT.initial), false);
assert.deepStrictEqual(DT.isValued(DT.pending), false);
assert.deepStrictEqual(DT.isValued(DT.failure(1)), true);
assert.deepStrictEqual(DT.isValued(DT.toRefresh(DT.failure(1))), true);
assert.deepStrictEqual(DT.isValued(DT.success(1)), true);
assert.deepStrictEqual(DT.isValued(DT.toRefresh(DT.success(1))), true);
assert.deepStrictEqual(DT.isValued(DT.partialSuccess(1, 1)), true);
assert.deepStrictEqual(DT.isValued(DT.toRefresh(DT.partialSuccess(1, 1))), true);
});
it('isSuccess', () => {
assert.deepStrictEqual(DT.isSuccess(DT.initial), false);
assert.deepStrictEqual(DT.isSuccess(DT.pending), false);
assert.deepStrictEqual(DT.isSuccess(refresh(left(1))), false);
assert.deepStrictEqual(DT.isSuccess(refresh(right(1))), true);
assert.deepStrictEqual(DT.isSuccess(refresh(both(1, 1))), false);
assert.deepStrictEqual(DT.isSuccess(replete(left(1))), false);
assert.deepStrictEqual(DT.isSuccess(replete(right(1))), true);
assert.deepStrictEqual(DT.isSuccess(replete(both(1, 1))), false)
});
it('isFailure', () => {
assert.deepStrictEqual(DT.isFailure(DT.initial), false);
assert.deepStrictEqual(DT.isFailure(DT.pending), false);
assert.deepStrictEqual(DT.isFailure(refresh(left(1))), true);
assert.deepStrictEqual(DT.isFailure(refresh(right(1))), false);
assert.deepStrictEqual(DT.isFailure(refresh(both(1, 1))), false);
assert.deepStrictEqual(DT.isFailure(replete(left(1))), true);
assert.deepStrictEqual(DT.isFailure(replete(right(1))), false);
assert.deepStrictEqual(DT.isFailure(replete(both(1, 1))), false);
});
it('isPartialSuccess', () => {
assert.deepStrictEqual(DT.isPartialSuccess(DT.initial), false);
assert.deepStrictEqual(DT.isPartialSuccess(DT.pending), false);
assert.deepStrictEqual(DT.isPartialSuccess(refresh(left(1))), false);
assert.deepStrictEqual(DT.isPartialSuccess(refresh(right(1))), false);
assert.deepStrictEqual(DT.isPartialSuccess(refresh(both(1, 1))), true);
assert.deepStrictEqual(DT.isPartialSuccess(replete(left(1))), false);
assert.deepStrictEqual(DT.isPartialSuccess(replete(right(1))), false);
assert.deepStrictEqual(DT.isPartialSuccess(replete(both(1, 1))), true);
});
it('isRefreshLeft', () => {
assert.deepStrictEqual(DT.isRefreshLeft(DT.initial), false);
assert.deepStrictEqual(DT.isRefreshLeft(DT.pending), false);
assert.deepStrictEqual(DT.isRefreshLeft(refresh(left(1))), true);
assert.deepStrictEqual(DT.isRefreshLeft(refresh(right(1))), false);
assert.deepStrictEqual(DT.isRefreshLeft(refresh(both(1, 1))), false);
assert.deepStrictEqual(DT.isRefreshLeft(replete(left(1))), false);
assert.deepStrictEqual(DT.isRefreshLeft(replete(right(1))), false);
assert.deepStrictEqual(DT.isRefreshLeft(replete(both(1, 1))), false);
});
it('isRefreshRight', () => {
assert.deepStrictEqual(DT.isRefreshRight(DT.initial), false);
assert.deepStrictEqual(DT.isRefreshRight(DT.pending), false);
assert.deepStrictEqual(DT.isRefreshRight(refresh(left(1))), false);
assert.deepStrictEqual(DT.isRefreshRight(refresh(right(1))), true);
assert.deepStrictEqual(DT.isRefreshRight(refresh(both(1, 1))), false);
assert.deepStrictEqual(DT.isRefreshRight(replete(left(1))), false);
assert.deepStrictEqual(DT.isRefreshRight(replete(right(1))), false);
assert.deepStrictEqual(DT.isRefreshRight(replete(both(1, 1))), false);
});
it('isRefreshBoth', () => {
assert.deepStrictEqual(DT.isRefreshBoth(DT.initial), false);
assert.deepStrictEqual(DT.isRefreshBoth(DT.pending), false);
assert.deepStrictEqual(DT.isRefreshBoth(refresh(left(1))), false);
assert.deepStrictEqual(DT.isRefreshBoth(refresh(right(1))), false);
assert.deepStrictEqual(DT.isRefreshBoth(refresh(both(1, 1))), true);
assert.deepStrictEqual(DT.isRefreshBoth(replete(left(1))), false);
assert.deepStrictEqual(DT.isRefreshBoth(replete(right(1))), false);
assert.deepStrictEqual(DT.isRefreshBoth(replete(both(1, 1))), false);
});
it('isRepleteLeft', () => {
assert.deepStrictEqual(DT.isRepleteLeft(DT.initial), false);
assert.deepStrictEqual(DT.isRepleteLeft(DT.pending), false);
assert.deepStrictEqual(DT.isRepleteLeft(refresh(left(1))), false);
assert.deepStrictEqual(DT.isRepleteLeft(refresh(right(1))), false);
assert.deepStrictEqual(DT.isRepleteLeft(refresh(both(1, 1))), false);
assert.deepStrictEqual(DT.isRepleteLeft(replete(left(1))), true);
assert.deepStrictEqual(DT.isRepleteLeft(replete(right(1))), false);
assert.deepStrictEqual(DT.isRepleteLeft(replete(both(1, 1))), false);
});
it('isRepleteRight', () => {
assert.deepStrictEqual(DT.isRepleteRight(DT.initial), false);
assert.deepStrictEqual(DT.isRepleteRight(DT.pending), false);
assert.deepStrictEqual(DT.isRepleteRight(refresh(left(1))), false);
assert.deepStrictEqual(DT.isRepleteRight(refresh(right(1))), false);
assert.deepStrictEqual(DT.isRepleteRight(refresh(both(1, 1))), false);
assert.deepStrictEqual(DT.isRepleteRight(replete(left(1))), false);
assert.deepStrictEqual(DT.isRepleteRight(replete(right(1))), true);
assert.deepStrictEqual(DT.isRepleteRight(replete(both(1, 1))), false);
});
it('isRepleteBoth', () => {
assert.deepStrictEqual(DT.isRepleteBoth(DT.initial), false);
assert.deepStrictEqual(DT.isRepleteBoth(DT.pending), false);
assert.deepStrictEqual(DT.isRepleteBoth(refresh(left(1))), false);
assert.deepStrictEqual(DT.isRepleteBoth(refresh(right(1))), false);
assert.deepStrictEqual(DT.isRepleteBoth(refresh(both(1, 1))), false);
assert.deepStrictEqual(DT.isRepleteBoth(replete(left(1))), false);
assert.deepStrictEqual(DT.isRepleteBoth(replete(right(1))), false);
assert.deepStrictEqual(DT.isRepleteBoth(replete(both(1, 1))), true);
});
it('toRefresh', () => {
assert.deepStrictEqual(DT.toRefresh(DT.initial), DT.pending);
assert.deepStrictEqual(DT.toRefresh(DT.pending), DT.pending);
assert.deepStrictEqual(DT.toRefresh(refresh(left(1))), refresh(left(1)));
assert.deepStrictEqual(DT.toRefresh(refresh(right(1))), refresh(right(1)));
assert.deepStrictEqual(DT.toRefresh(refresh(both(1, 1))), refresh(both(1, 1)));
assert.deepStrictEqual(DT.toRefresh(replete(left(1))), refresh(left(1)));
assert.deepStrictEqual(DT.toRefresh(replete(right(1))), refresh(right(1)));
assert.deepStrictEqual(DT.toRefresh(replete(both(1, 1))), refresh(both(1, 1)));
});
it('toReplete', () => {
assert.deepStrictEqual(DT.toReplete(DT.initial), DT.initial);
assert.deepStrictEqual(DT.toReplete(DT.pending), DT.initial);
assert.deepStrictEqual(DT.toReplete(refresh(left(1))), replete(left(1)));
assert.deepStrictEqual(DT.toReplete(refresh(right(1))), replete(right(1)));
assert.deepStrictEqual(DT.toReplete(refresh(both(1, 1))), replete(both(1, 1)));
assert.deepStrictEqual(DT.toReplete(replete(left(1))), replete(left(1)));
assert.deepStrictEqual(DT.toReplete(replete(right(1))), replete(right(1)));
assert.deepStrictEqual(DT.toReplete(replete(both(1, 1))), replete(both(1, 1)));
});
it('fromOption', () => {
assert.deepStrictEqual(DT.fromOption(() => 1)(some(0)), DT.success(0));
assert.deepStrictEqual(DT.fromOption(() => 1)(none), DT.failure(1));
});
it('fromNullable', () => {
assert.deepStrictEqual(DT.fromNullable(2), DT.success(2));
assert.deepStrictEqual(DT.fromNullable(null), DT.initial);
assert.deepStrictEqual(DT.fromNullable(undefined), DT.initial);
});
it('fold', () => {
const onInitial = () => 'initial';
const onPending = () => `pending`;
const onRefreshLeft = (s: string) => `refreshLeft${s.length}`;
const onRefreshRight = (s: string) => `refreshRight${s.length}`;
const onRefreshBoth = (e: string, a: string) => `refreshBoth${e.length}:${a.length}`;
const onRepleteLeft = (s: string) => `repleteLeft${s.length}`;
const onRepleteRight = (s: string) => `repleteRight${s.length}`;
const onRepleteBoth = (e: string, a: string) => `repleteBoth${e.length}:${a.length}`;
const fold = DT.fold(
onInitial,
onPending,
onRefreshLeft,
onRefreshRight,
onRefreshBoth,
onRepleteLeft,
onRepleteRight,
onRepleteBoth
);
assert.strictEqual(fold(DT.initial), 'initial');
assert.strictEqual(fold(DT.pending), 'pending');
assert.strictEqual(fold(DT.failure('abc')), 'repleteLeft3');
assert.strictEqual(fold(DT.success('abc')), 'repleteRight3');
assert.strictEqual(fold(DT.partialSuccess('ab', 'cdef')), 'repleteBoth2:4');
assert.strictEqual(fold(DT.toRefresh(DT.failure('abc'))), 'refreshLeft3');
assert.strictEqual(fold(DT.toRefresh(DT.success('abc'))), 'refreshRight3');
assert.strictEqual(fold(DT.toRefresh(DT.partialSuccess('ab', 'cdef'))), 'refreshBoth2:4');
});
it('refreshFold', () => {
const onInitial = () => `initial`;
const onPending = () => `pending`;
const onFailure = (s: string, r?: boolean) => `failure${s.length}${r}`;
const onSuccess = (s: string, r?: boolean) => `success${s.length}${r}`;
const onPartialSuccess = (e: string, a: string, r?: boolean) => `partialSuccess${e.length}:${a.length}${r}`;
const refreshFold = DT.refreshFold(
onInitial,
onPending,
onFailure,
onSuccess,
onPartialSuccess
);
assert.strictEqual(refreshFold(DT.initial), 'initial');
assert.strictEqual(refreshFold(DT.pending), 'pending');
assert.strictEqual(
refreshFold(DT.toRefresh(DT.failure('abc'))),
'failure3true'
);
assert.strictEqual(
refreshFold(DT.toRefresh(DT.success('abc'))),
'success3true'
);
assert.strictEqual(
refreshFold(DT.toRefresh(DT.partialSuccessR('ab', 'cdef'))),
'partialSuccess2:4true'
);
assert.strictEqual(refreshFold(DT.failure('abc')), 'failure3false');
assert.strictEqual(refreshFold(DT.success('abc')), 'success3false');
assert.strictEqual(refreshFold(DT.partialSuccess('ab', 'cdef')), 'partialSuccess2:4false');
});
it('squash', () => {
const onNone = (r?: boolean) => `none${r}`;
const onFailure = (s: string, r?: boolean) => `failure${s.length}${r}`;
const onSuccess = (s: string, r?: boolean) => `success${s.length}${r}`;
const onPartialSuccess = (e: string, a: string, r?: boolean) => `partialSuccess${e.length}:${a.length}${r}`;
const squash = DT.squash(onNone, onFailure, onSuccess, onPartialSuccess);
assert.strictEqual(squash(DT.initial), 'nonefalse');
assert.strictEqual(squash(DT.pending), 'nonetrue');
assert.strictEqual(squash(DT.toRefresh(DT.failure('abc'))), 'failure3true');
assert.strictEqual(squash(DT.toRefresh(DT.success('abc'))), 'success3true');
assert.strictEqual(squash(DT.toRefresh(DT.partialSuccess('ab', 'cdef'))), 'partialSuccess2:4true');
assert.strictEqual(squash(DT.failure('abc')), 'failure3false');
assert.strictEqual(squash(DT.success('abc')), 'success3false');
assert.strictEqual(squash(DT.partialSuccess('ab', 'cdef')), 'partialSuccess2:4false');
});
it('traverse', () => {
const traverse = DT.Traversable.traverse(option);
const fab = (n: number) => (n < 0 ? none : some(n));
assert.deepStrictEqual(traverse(DT.initial, fab), some(DT.initial));
assert.deepStrictEqual(traverse(DT.pending, fab), some(DT.pending));
assert.deepStrictEqual(
traverse(DT.toRefresh(DT.success(0)), fab),
some(DT.toRefresh(DT.success(0)))
);
assert.deepStrictEqual(
traverse(DT.toRefresh(DT.failure(0)), fab),
some(DT.toRefresh(DT.failure(0)))
);
assert.deepStrictEqual(
traverse(DT.toRefresh(DT.partialSuccess(0, 0)), fab),
some(DT.toRefresh(DT.partialSuccess(0, 0)))
);
assert.deepStrictEqual(traverse(DT.toRefresh(DT.success(-1)), fab), none);
assert.deepStrictEqual(
traverse(DT.toRefresh(DT.failure(-1)), fab),
some(DT.toRefresh(DT.failure(-1)))
);
assert.deepStrictEqual(
traverse(DT.toRefresh(DT.partialSuccess(-1, -1)), fab),
none
);
assert.deepStrictEqual(traverse(DT.success(0), fab), some(DT.success(0)));
assert.deepStrictEqual(traverse(DT.failure(0), fab), some(DT.failure(0)));
assert.deepStrictEqual(traverse(DT.partialSuccess(0, 0), fab), some(DT.partialSuccess(0, 0)))
assert.deepStrictEqual(traverse(DT.success(-1), fab), none);
assert.deepStrictEqual(traverse(DT.failure(-1), fab), some(DT.failure(-1)));
assert.deepStrictEqual(traverse(DT.partialSuccess(-1, -1), fab), none);
});
it('sequence', () => {
const sequence = DT.Traversable.sequence(option);
assert.deepStrictEqual(sequence(DT.initial), some(DT.initial));
assert.deepStrictEqual(sequence(DT.pending), some(DT.pending));
assert.deepStrictEqual(sequence(DT.failure(0)), some(DT.failure(0)));
assert.deepStrictEqual(
sequence(DT.toRefresh(DT.failure(0))),
some(DT.toRefresh(DT.failure(0)))
);
assert.deepStrictEqual(sequence(DT.success(none)), none);
assert.deepStrictEqual(sequence(DT.success(some(0))), some(DT.success(0)));
assert.deepStrictEqual(sequence(DT.partialSuccess(0, none)), none);
assert.deepStrictEqual(sequence(DT.partialSuccess(0, some(0))), some(DT.partialSuccess(0, 0)));
assert.deepStrictEqual(sequence(DT.toRefresh(DT.success(none))), none);
assert.deepStrictEqual(
sequence(DT.toRefresh(DT.success(some(0)))),
some(DT.toRefresh(DT.success(0)))
);
assert.deepStrictEqual(sequence(DT.toRefresh(DT.partialSuccess(0, none))), none);
assert.deepStrictEqual(
sequence(DT.toRefresh(DT.partialSuccess(0, some(0)))),
some(DT.toRefresh(DT.partialSuccess(0, 0)))
);
});
it('reduce', () => {
const reduce = DT.Traversable.reduce;
const add = (acc: number, cur: number): number => acc + cur;
assert.deepStrictEqual(reduce(DT.initial, 0, add), 0);
assert.deepStrictEqual(reduce(DT.pending, 0, add), 0);
assert.deepStrictEqual(reduce(DT.success(1), 0, add), 1);
assert.deepStrictEqual(reduce(DT.failure(1), 0, add), 0);
assert.deepStrictEqual(reduce(DT.partialSuccess(0, 1), 0, add), 1);
assert.deepStrictEqual(reduce(DT.toRefresh(DT.success(1)), 0, add), 1);
assert.deepStrictEqual(reduce(DT.toRefresh(DT.failure(1)), 0, add), 0);
assert.deepStrictEqual(reduce(DT.toRefresh(DT.partialSuccess(0, 1)), 0, add), 1);
});
it('foldMap', () => {
const fab = (s: string): number => s.length;
const foldMap = DT.foldMap(monoidSum)(fab);
assert.deepStrictEqual(foldMap(DT.initial), monoidSum.empty);
assert.deepStrictEqual(foldMap(DT.pending), monoidSum.empty);
assert.deepStrictEqual(foldMap(DT.success('Hello')), 5);
assert.deepStrictEqual(foldMap(DT.failure('Hello')), monoidSum.empty);
assert.deepStrictEqual(foldMap(DT.partialSuccess('ab', 'cdef')), 4);
assert.deepStrictEqual(foldMap(DT.toRefresh(DT.success('Hello'))), 5);
assert.deepStrictEqual(
foldMap(DT.toRefresh(DT.failure('Hello'))),
monoidSum.empty
);
assert.deepStrictEqual(
foldMap(DT.toRefresh(DT.partialSuccess('ab', 'cdef'))),
4
);
});
it('reduceRight', () => {
const reduce = DT.Traversable.reduceRight;
const add = (acc: number, cur: number): number => acc + cur;
assert.deepStrictEqual(reduce(DT.initial, 0, add), 0);
assert.deepStrictEqual(reduce(DT.pending, 0, add), 0);
assert.deepStrictEqual(reduce(DT.success(1), 0, add), 1);
assert.deepStrictEqual(reduce(DT.failure(1), 0, add), 0);
assert.deepStrictEqual(reduce(DT.partialSuccess(0, 1), 0, add), 1);
assert.deepStrictEqual(reduce(DT.toRefresh(DT.success(1)), 0, add), 1);
assert.deepStrictEqual(reduce(DT.toRefresh(DT.failure(1)), 0, add), 0);
assert.deepStrictEqual(reduce(DT.toRefresh(DT.partialSuccess(0, 1)), 0, add), 1);
});
it('getShow', () => {
const S = DT.getShow(showString, showNumber);
assert.strictEqual(S.show(DT.initial), 'initial');
assert.strictEqual(S.show(DT.pending), 'pending');
assert.strictEqual(S.show(DT.success(1)), 'replete(right(1))');
assert.strictEqual(S.show(DT.failure('a')), 'replete(left("a"))');
assert.strictEqual(S.show(DT.partialSuccess('a', 1)), 'replete(both("a", 1))');
assert.strictEqual(S.show(DT.successR(1)), 'refresh(right(1))');
assert.strictEqual(S.show(DT.failureR('a')), 'refresh(left("a"))');
assert.strictEqual(S.show(DT.partialSuccessR('a', 1)), 'refresh(both("a", 1))');
});
it('getEq', () => {
const E = DT.getEq(eqString, eqNumber);
// Sanity check reference equality not needed
assert.strictEqual(E.equals(DT.success(1), DT.success(1)), true)
const uniqueValues = [
DT.initial,
DT.pending,
DT.success(1),
DT.failure('a'),
DT.partialSuccess('a', 1),
DT.success(2),
DT.failure('b'),
DT.partialSuccess('b', 2),
DT.successR(1),
DT.failureR('a'),
DT.partialSuccessR('a', 1),
DT.successR(2),
DT.failureR('b'),
DT.partialSuccessR('b', 2),
];
for (let i = 0; i < uniqueValues.length; i++) {
for (let j = i; j < uniqueValues.length; j++) {
assert.strictEqual(E.equals(uniqueValues[i], uniqueValues[j]), i === j)
}
}
});
it('getApplySemigroup', () => {
const S = DT.getApplySemigroup(theseGetSemigroup(semigroupString, semigroupSum));
const values = [
DT.success(1),
DT.failure('a'),
DT.partialSuccess('a', 1),
DT.successR(1),
DT.failureR('a'),
DT.partialSuccessR('a', 1),
];
const noValues = [
DT.initial,
DT.pending
];
assert.deepStrictEqual(S.concat(DT.initial, DT.initial), DT.initial);
assert.deepStrictEqual(S.concat(DT.initial, DT.pending), DT.initial);
assert.deepStrictEqual(S.concat(DT.pending, DT.pending), DT.pending);
assert.deepStrictEqual(S.concat(DT.pending, DT.initial), DT.pending);
noValues.forEach(noValue => {
values.forEach(value => {
assert.deepStrictEqual(S.concat(noValue, value), noValue);
assert.deepStrictEqual(S.concat(value, noValue), noValue);
});
});
const modifiers = [
identity,
DT.toRefresh
];
// Replete/Refresh of first valued datum does not matter
modifiers.forEach(modifier => {
assert.deepStrictEqual(S.concat(modifier(DT.success(1)), DT.success(1)), DT.success(2));
assert.deepStrictEqual(S.concat(modifier(DT.success(1)), DT.failure('a')), DT.partialSuccess('a', 1));
assert.deepStrictEqual(S.concat(modifier(DT.success(1)), DT.partialSuccess('a', 1)), DT.partialSuccess('a', 2));
assert.deepStrictEqual(S.concat(modifier(DT.success(1)), DT.successR(1)), DT.successR(2));
assert.deepStrictEqual(S.concat(modifier(DT.success(1)), DT.failureR('a')), DT.partialSuccessR('a', 1));
assert.deepStrictEqual(S.concat(modifier(DT.success(1)), DT.partialSuccessR('a', 1)), DT.partialSuccessR('a', 2));
assert.deepStrictEqual(S.concat(modifier(DT.failure('a')), DT.success(1)), DT.partialSuccess('a', 1));
assert.deepStrictEqual(S.concat(modifier(DT.failure('a')), DT.failure('a')), DT.failure('aa'));
assert.deepStrictEqual(S.concat(modifier(DT.failure('a')), DT.partialSuccess('a', 1)), DT.partialSuccess('aa', 1));
assert.deepStrictEqual(S.concat(modifier(DT.failure('a')), DT.successR(1)), DT.partialSuccessR('a', 1));
assert.deepStrictEqual(S.concat(modifier(DT.failure('a')), DT.failureR('a')), DT.failureR('aa'));
assert.deepStrictEqual(S.concat(modifier(DT.failure('a')), DT.partialSuccessR('a', 1)), DT.partialSuccessR('aa', 1));
assert.deepStrictEqual(S.concat(modifier(DT.partialSuccess('a', 1)), DT.success(1)), DT.partialSuccess('a', 2));
assert.deepStrictEqual(S.concat(modifier(DT.partialSuccess('a', 1)), DT.failure('a')), DT.partialSuccess('aa', 1));
assert.deepStrictEqual(S.concat(modifier(DT.partialSuccess('a', 1)), DT.partialSuccess('a', 1)), DT.partialSuccess('aa', 2));
assert.deepStrictEqual(S.concat(modifier(DT.partialSuccess('a', 1)), DT.successR(1)), DT.partialSuccessR('a', 2));
assert.deepStrictEqual(S.concat(modifier(DT.partialSuccess('a', 1)), DT.failureR('a')), DT.partialSuccessR('aa', 1));
assert.deepStrictEqual(S.concat(modifier(DT.partialSuccess('a', 1)), DT.partialSuccessR('a', 1)), DT.partialSuccessR('aa', 2));
});
});
function assertAp(A: Apply2C<DT.URI, string>) {
const f = (n: number) => n * 2;
const noValues = [
DT.initial,
DT.pending,
];
const values = [
DT.success(1),
DT.failure('a'),
DT.partialSuccess('a', 1),
DT.successR(1),
DT.failureR('a'),
DT.partialSuccessR('a', 1)
];
noValues.forEach(noValue1 => {
noValues.forEach(noValue2 => {
assert.deepStrictEqual(A.ap(noValue1, noValue2), noValue1)
});
});
noValues.forEach(noValue => {
values.forEach(value => {
assert.deepStrictEqual(A.ap(noValue, value), noValue)
});
});
noValues.forEach(noValue => {
assert.deepStrictEqual(A.ap(DT.success(f), noValue), noValue)
assert.deepStrictEqual(A.ap(DT.partialSuccess('a', f), noValue), noValue)
assert.deepStrictEqual(A.ap(DT.successR(f), noValue), noValue)
assert.deepStrictEqual(A.ap(DT.partialSuccessR('a', f), noValue), noValue)
});
values.concat(noValues).forEach(val => {
const failFn: DatumThese<string, typeof f> = DT.failure('a')
const failFnR: DatumThese<string, typeof f> = DT.failureR('a')
assert.deepStrictEqual(A.ap(failFn, val), DT.failure('a'))
assert.deepStrictEqual(A.ap(failFnR, val), DT.failure('a'))
})
assert.deepStrictEqual(A.ap(DT.success(f), DT.success(1)), DT.success(2));
assert.deepStrictEqual(A.ap(DT.success(f), DT.failure('a')), DT.failure('a'));
assert.deepStrictEqual(A.ap(DT.success(f), DT.partialSuccess('a', 1)), DT.partialSuccess('a', 2));
assert.deepStrictEqual(A.ap(DT.success(f), DT.successR(1)), DT.successR(2));
assert.deepStrictEqual(A.ap(DT.success(f), DT.failureR('a')), DT.failureR('a'));
assert.deepStrictEqual(A.ap(DT.success(f), DT.partialSuccessR('a', 1)), DT.partialSuccessR('a', 2));
assert.deepStrictEqual(A.ap(DT.successR(f), DT.success(1)), DT.success(2));
assert.deepStrictEqual(A.ap(DT.successR(f), DT.failure('a')), DT.failure('a'));
assert.deepStrictEqual(A.ap(DT.successR(f), DT.partialSuccess('a', 1)), DT.partialSuccess('a', 2));
assert.deepStrictEqual(A.ap(DT.successR(f), DT.successR(1)), DT.successR(2));
assert.deepStrictEqual(A.ap(DT.successR(f), DT.failureR('a')), DT.failureR('a'));
assert.deepStrictEqual(A.ap(DT.successR(f), DT.partialSuccessR('a', 1)), DT.partialSuccessR('a', 2));
assert.deepStrictEqual(A.ap(DT.partialSuccess('a', f), DT.success(1)), DT.partialSuccess('a', 2));
assert.deepStrictEqual(A.ap(DT.partialSuccess('a', f), DT.failure('a')), DT.failure('aa'));
assert.deepStrictEqual(A.ap(DT.partialSuccess('a', f), DT.partialSuccess('a', 1)), DT.partialSuccess('aa', 2));
assert.deepStrictEqual(A.ap(DT.partialSuccess('a', f), DT.successR(1)), DT.partialSuccessR('a', 2));
assert.deepStrictEqual(A.ap(DT.partialSuccess('a', f), DT.failureR('a')), DT.failureR('aa'));
assert.deepStrictEqual(A.ap(DT.partialSuccess('a', f), DT.partialSuccessR('a', 1)), DT.partialSuccessR('aa', 2));
assert.deepStrictEqual(A.ap(DT.partialSuccessR('a', f), DT.success(1)), DT.partialSuccess('a', 2));
assert.deepStrictEqual(A.ap(DT.partialSuccessR('a', f), DT.failure('a')), DT.failure('aa'));
assert.deepStrictEqual(A.ap(DT.partialSuccessR('a', f), DT.partialSuccess('a', 1)), DT.partialSuccess('aa', 2));
assert.deepStrictEqual(A.ap(DT.partialSuccessR('a', f), DT.successR(1)), DT.partialSuccessR('a', 2));
assert.deepStrictEqual(A.ap(DT.partialSuccessR('a', f), DT.failureR('a')), DT.failureR('aa'));
assert.deepStrictEqual(A.ap(DT.partialSuccessR('a', f), DT.partialSuccessR('a', 1)), DT.partialSuccessR('aa', 2));
}
it('getApply', () => {
const A = DT.getApply(semigroupString);
assertAp(A);
});
function assertOf(A: Applicative2C<DT.URI, string>) {
assert.deepStrictEqual(A.of(1), DT.success(1));
}
it('getApplicative', () => {
const A = DT.getApplicative(semigroupString);
assertAp(A);
assertOf(A);
});
function assertChain(C: Chain2C<DT.URI, string>) {
const f = (n: number) => n > 1 ? DT.success(n * 2) : DT.partialSuccess('b', n);
const g = (n: number) => DT.failureR('c')
const h = (n: number) => DT.initial
const noValues = [
DT.initial,
DT.pending,
];
noValues.forEach(noValue => {
assert.deepStrictEqual(C.chain(noValue, f), noValue);
});
[DT.failure('a'), DT.failureR('a')].forEach(fail => {
assert.deepStrictEqual(C.chain(fail, f), DT.failure('a'));
});
assert.deepStrictEqual(C.chain(DT.partialSuccess('a', 1), f), DT.partialSuccess('ab', 1));
assert.deepStrictEqual(C.chain(DT.partialSuccess('a', 2), f), DT.partialSuccess('a', 4));
assert.deepStrictEqual(C.chain(DT.partialSuccess('a', 1), g), DT.failureR('ac'));
assert.deepStrictEqual(C.chain(DT.partialSuccess('a', 1), h), DT.initial);
assert.deepStrictEqual(C.chain(DT.partialSuccessR('a', 1), f), DT.partialSuccess('ab', 1));
assert.deepStrictEqual(C.chain(DT.partialSuccessR('a', 2), f), DT.partialSuccess('a', 4));
assert.deepStrictEqual(C.chain(DT.partialSuccessR('a', 1), g), DT.failureR('ac'));
assert.deepStrictEqual(C.chain(DT.partialSuccessR('a', 1), h), DT.initial);
assert.deepStrictEqual(C.chain(DT.success(1), f), DT.partialSuccess('b', 1));
assert.deepStrictEqual(C.chain(DT.success(2), f), DT.success(4));
assert.deepStrictEqual(C.chain(DT.success(1), g), DT.failureR('c'));
assert.deepStrictEqual(C.chain(DT.success(1), h), DT.initial);
assert.deepStrictEqual(C.chain(DT.successR(1), f), DT.partialSuccess('b', 1));
assert.deepStrictEqual(C.chain(DT.successR(2), f), DT.success(4));
assert.deepStrictEqual(C.chain(DT.successR(1), g), DT.failureR('c'));
assert.deepStrictEqual(C.chain(DT.successR(1), h), DT.initial);
}
it('getChain', () => {
const C = DT.getChain(semigroupString);
assertAp(C)
assertChain(C)
});
it('getMonad', () => {
const M = DT.getMonad(semigroupString);
assertAp(M);;
assertChain(M);
assertOf(M);
});
it('getMonadThrow', () => {
const M = DT.getMonadThrow(semigroupString);
assertAp(M);;
assertChain(M);
assertOf(M);
assert.deepStrictEqual(M.throwError('bla'), DT.failure('bla'))
});
function assertStringSumSemigroup(S: Semigroup<DT.DatumThese<string, number>>) {
assert.deepStrictEqual(S.concat(DT.initial, DT.initial), DT.initial);
assert.deepStrictEqual(S.concat(DT.initial, DT.pending), DT.pending);
assert.deepStrictEqual(S.concat(DT.initial, DT.failureR('a')), DT.failureR('a'));
assert.deepStrictEqual(S.concat(DT.initial, DT.successR(1)), DT.successR(1));
assert.deepStrictEqual(S.concat(DT.initial, DT.partialSuccessR('a', 1)), DT.partialSuccessR('a', 1));
assert.deepStrictEqual(S.concat(DT.initial, DT.failure('a')), DT.failure('a'));
assert.deepStrictEqual(S.concat(DT.initial, DT.success(1)), DT.success(1));
assert.deepStrictEqual(S.concat(DT.initial, DT.partialSuccess('a', 1)), DT.partialSuccess('a', 1));
assert.deepStrictEqual(S.concat(DT.pending, DT.initial), DT.pending);
assert.deepStrictEqual(S.concat(DT.pending, DT.pending), DT.pending);
assert.deepStrictEqual(S.concat(DT.pending, DT.failureR('a')), DT.failureR('a'));
assert.deepStrictEqual(S.concat(DT.pending, DT.successR(1)), DT.successR(1));
assert.deepStrictEqual(S.concat(DT.pending, DT.partialSuccessR('a', 1)), DT.partialSuccessR('a', 1));
assert.deepStrictEqual(S.concat(DT.pending, DT.failure('a')), DT.failureR('a'));
assert.deepStrictEqual(S.concat(DT.pending, DT.success(1)), DT.successR(1));
assert.deepStrictEqual(S.concat(DT.pending, DT.partialSuccess('a', 1)), DT.partialSuccessR('a', 1));
assert.deepStrictEqual(S.concat(DT.failureR('a'), DT.initial), DT.failureR('a'));
assert.deepStrictEqual(S.concat(DT.failureR('a'), DT.pending), DT.failureR('a'));
assert.deepStrictEqual(S.concat(DT.failureR('a'), DT.failureR('a')), DT.failureR('aa'));
assert.deepStrictEqual(S.concat(DT.failureR('a'), DT.successR(1)), DT.partialSuccessR('a', 1));
assert.deepStrictEqual(S.concat(DT.failureR('a'), DT.partialSuccessR('a', 1)), DT.partialSuccessR('aa', 1));
assert.deepStrictEqual(S.concat(DT.failureR('a'), DT.failure('a')), DT.failureR('aa'));
assert.deepStrictEqual(S.concat(DT.failureR('a'), DT.success(1)), DT.partialSuccessR('a', 1));
assert.deepStrictEqual(S.concat(DT.failureR('a'), DT.partialSuccess('a', 1)), DT.partialSuccessR('aa', 1));
assert.deepStrictEqual(S.concat(DT.successR(1), DT.initial), DT.successR(1));
assert.deepStrictEqual(S.concat(DT.successR(1), DT.pending), DT.successR(1));
assert.deepStrictEqual(S.concat(DT.successR(1), DT.failureR('a')), DT.partialSuccessR('a', 1));
assert.deepStrictEqual(S.concat(DT.successR(1), DT.successR(1)), DT.successR(2));
assert.deepStrictEqual(S.concat(DT.successR(1), DT.partialSuccessR('a', 1)), DT.partialSuccessR('a', 2));
assert.deepStrictEqual(S.concat(DT.successR(1), DT.failure('a')), DT.partialSuccessR('a', 1));
assert.deepStrictEqual(S.concat(DT.successR(1), DT.success(1)), DT.successR(2));
assert.deepStrictEqual(S.concat(DT.successR(1), DT.partialSuccess('a', 1)), DT.partialSuccessR('a', 2));
assert.deepStrictEqual(S.concat(DT.failure('a'), DT.initial), DT.failure('a'));
assert.deepStrictEqual(S.concat(DT.failure('a'), DT.pending), DT.failureR('a'));
assert.deepStrictEqual(S.concat(DT.failure('a'), DT.failureR('a')), DT.failureR('aa'));
assert.deepStrictEqual(S.concat(DT.failure('a'), DT.successR(1)), DT.partialSuccessR('a', 1));
assert.deepStrictEqual(S.concat(DT.failure('a'), DT.partialSuccessR('a', 1)), DT.partialSuccessR('aa', 1));
assert.deepStrictEqual(S.concat(DT.failure('a'), DT.failure('a')), DT.failure('aa'));
assert.deepStrictEqual(S.concat(DT.failure('a'), DT.success(1)), DT.partialSuccess('a', 1));
assert.deepStrictEqual(S.concat(DT.failure('a'), DT.partialSuccess('a', 1)), DT.partialSuccess('aa', 1));
assert.deepStrictEqual(S.concat(DT.success(1), DT.initial), DT.success(1));
assert.deepStrictEqual(S.concat(DT.success(1), DT.pending), DT.successR(1));
assert.deepStrictEqual(S.concat(DT.success(1), DT.failureR('a')), DT.partialSuccessR('a', 1));
assert.deepStrictEqual(S.concat(DT.success(1), DT.successR(1)), DT.successR(2));
assert.deepStrictEqual(S.concat(DT.success(1), DT.partialSuccessR('a', 1)), DT.partialSuccessR('a', 2));
assert.deepStrictEqual(S.concat(DT.success(1), DT.failure('a')), DT.partialSuccess('a', 1));
assert.deepStrictEqual(S.concat(DT.success(1), DT.success(1)), DT.success(2));
assert.deepStrictEqual(S.concat(DT.success(1), DT.partialSuccess('a', 1)), DT.partialSuccess('a', 2));
}
it('getSemigroup', () => {
const S = DT.getSemigroup(theseGetSemigroup(semigroupString, semigroupSum));
assertStringSumSemigroup(S);
});
it('getMonoid', () => {
const M = DT.getMonoid(theseGetSemigroup(semigroupString, semigroupSum))
assertStringSumSemigroup(M);
const values = [
DT.initial,
DT.pending,
DT.failureR('a'),
DT.successR(1),
DT.partialSuccessR('a', 1),
DT.failure('a'),
DT.success(1),
DT.partialSuccess('a', 1)
];
values.forEach(value => {
assert.deepStrictEqual(M.concat(value, M.empty), value);
assert.deepStrictEqual(M.concat(M.empty, value), value)
});
});
});
|
clov3r/datum
|
scripts/prepare.ts
|
<filename>scripts/prepare.ts
///<reference path="../node_modules/@types/node/index.d.ts" />
import * as fs from 'fs';
import * as path from 'path';
/**
* Treat package.json root as root.
*/
const outDir = './dist';
const copyItems = ['README.md', 'src']; // For Sourcemaps
const pkg = require('../package.json');
const publishPackage = {
name: pkg.name,
version: pkg.version,
description: pkg.description,
files: pkg.files,
sideEffects: pkg.sideEffects,
repository: pkg.repository,
keywords: pkg.keywords,
author: pkg.author,
license: pkg.license,
bugs: pkg.bugs,
homepage: pkg.homepage,
dependencies: pkg.dependencies,
};
const copyRecursiveSync = (src: string, dest: string): void => {
const srcIsDirectory = fs.statSync(src).isDirectory();
if (srcIsDirectory) {
if (!fs.existsSync(dest)) {
fs.mkdirSync(dest);
}
fs.readdirSync(src).forEach(function (childItemName) {
copyRecursiveSync(
path.join(src, childItemName),
path.join(dest, childItemName)
);
});
} else {
fs.copyFileSync(src, dest); // UPDATE FROM: fs.linkSync(src, dest);
}
};
const remapSources = (map: { sources: string[] }) => {
const sources = map.sources.map((source) =>
source.replace(/\.\.\/src/, './src')
);
return {
...map,
sources,
};
};
if (!fs.existsSync(outDir)) {
fs.mkdirSync(outDir);
}
// Write package.json
fs.writeFileSync(
[outDir, 'package.json'].join('/'),
JSON.stringify(publishPackage, null, 2),
{
encoding: 'utf-8',
}
);
// Copy additional items
copyItems.forEach((src) => copyRecursiveSync(src, [outDir, src].join('/')));
// Modify sourcemaps
const sourceMaps = fs
.readdirSync(outDir)
.filter((file) => file.endsWith('js.map'))
.map((file) => [outDir, file].join('/'));
sourceMaps.forEach((map) => {
const file = JSON.parse(fs.readFileSync(map, { encoding: 'utf-8' }));
const newFile = remapSources(file);
fs.writeFileSync(map, JSON.stringify(newFile), { encoding: 'utf-8' });
});
|
clov3r/datum
|
test/DatumEither.ts
|
import * as assert from 'assert';
import * as DE from '../src/DatumEither';
import { refresh, replete } from '../src/Datum';
import { some, none, option } from 'fp-ts/es6/Option';
import { left, right, getSemigroup as eitherGetSemigroup } from 'fp-ts/es6/Either';
import { Monoid, monoidSum } from 'fp-ts/es6/Monoid';
import { Semigroup, semigroupSum } from 'fp-ts/es6/Semigroup';
import { identity } from 'fp-ts/es6/function';
describe('Datum', () => {
it('URI', () => {
assert.strictEqual(DE.URI, '@nll/datum/DatumEither');
});
it('successR', () => {
assert.deepEqual(DE.successR(1), DE.toRefresh(DE.success(1)));
});
it('failureR', () => {
assert.deepEqual(DE.failureR(1), DE.toRefresh(DE.failure(1)));
});
it('isInitial', () => {
assert.deepStrictEqual(DE.isInitial(DE.initial), true);
assert.deepStrictEqual(DE.isInitial(DE.pending), false);
assert.deepStrictEqual(DE.isInitial(DE.failure(1)), false);
assert.deepStrictEqual(DE.isInitial(DE.toRefresh(DE.failure(1))), false);
assert.deepStrictEqual(DE.isInitial(DE.success(1)), false);
assert.deepStrictEqual(DE.isInitial(DE.toRefresh(DE.success(1))), false);
});
it('isPending', () => {
assert.deepStrictEqual(DE.isPending(DE.initial), false);
assert.deepStrictEqual(DE.isPending(DE.pending), true);
assert.deepStrictEqual(DE.isPending(DE.failure(1)), false);
assert.deepStrictEqual(DE.isPending(DE.toRefresh(DE.failure(1))), false);
assert.deepStrictEqual(DE.isPending(DE.success(1)), false);
assert.deepStrictEqual(DE.isPending(DE.toRefresh(DE.success(1))), false);
});
it('isRefresh', () => {
assert.deepStrictEqual(DE.isRefresh(DE.initial), false);
assert.deepStrictEqual(DE.isRefresh(DE.pending), false);
assert.deepStrictEqual(DE.isRefresh(DE.failure(1)), false);
assert.deepStrictEqual(DE.isRefresh(DE.toRefresh(DE.failure(1))), true);
assert.deepStrictEqual(DE.isRefresh(DE.success(1)), false);
assert.deepStrictEqual(DE.isRefresh(DE.toRefresh(DE.success(1))), true);
});
it('isReplete', () => {
assert.deepStrictEqual(DE.isReplete(DE.initial), false);
assert.deepStrictEqual(DE.isReplete(DE.pending), false);
assert.deepStrictEqual(DE.isReplete(DE.failure(1)), true);
assert.deepStrictEqual(DE.isReplete(DE.toRefresh(DE.failure(1))), false);
assert.deepStrictEqual(DE.isReplete(DE.success(1)), true);
assert.deepStrictEqual(DE.isReplete(DE.toRefresh(DE.success(1))), false);
});
it('isValued', () => {
assert.deepStrictEqual(DE.isValued(DE.initial), false);
assert.deepStrictEqual(DE.isValued(DE.pending), false);
assert.deepStrictEqual(DE.isValued(DE.failure(1)), true);
assert.deepStrictEqual(DE.isValued(DE.toRefresh(DE.failure(1))), true);
assert.deepStrictEqual(DE.isValued(DE.success(1)), true);
assert.deepStrictEqual(DE.isValued(DE.toRefresh(DE.success(1))), true);
});
it('isSuccess', () => {
assert.deepStrictEqual(DE.isSuccess(DE.initial), false);
assert.deepStrictEqual(DE.isSuccess(DE.pending), false);
assert.deepStrictEqual(DE.isSuccess(refresh(left(1))), false);
assert.deepStrictEqual(DE.isSuccess(refresh(right(1))), true);
assert.deepStrictEqual(DE.isSuccess(replete(left(1))), false);
assert.deepStrictEqual(DE.isSuccess(replete(right(1))), true);
});
it('isFailure', () => {
assert.deepStrictEqual(DE.isFailure(DE.initial), false);
assert.deepStrictEqual(DE.isFailure(DE.pending), false);
assert.deepStrictEqual(DE.isFailure(refresh(left(1))), true);
assert.deepStrictEqual(DE.isFailure(refresh(right(1))), false);
assert.deepStrictEqual(DE.isFailure(replete(left(1))), true);
assert.deepStrictEqual(DE.isFailure(replete(right(1))), false);
});
it('isRefreshLeft', () => {
assert.deepStrictEqual(DE.isRefreshLeft(DE.initial), false);
assert.deepStrictEqual(DE.isRefreshLeft(DE.pending), false);
assert.deepStrictEqual(DE.isRefreshLeft(refresh(left(1))), true);
assert.deepStrictEqual(DE.isRefreshLeft(refresh(right(1))), false);
assert.deepStrictEqual(DE.isRefreshLeft(replete(left(1))), false);
assert.deepStrictEqual(DE.isRefreshLeft(replete(right(1))), false);
});
it('isRefreshRight', () => {
assert.deepStrictEqual(DE.isRefreshRight(DE.initial), false);
assert.deepStrictEqual(DE.isRefreshRight(DE.pending), false);
assert.deepStrictEqual(DE.isRefreshRight(refresh(left(1))), false);
assert.deepStrictEqual(DE.isRefreshRight(refresh(right(1))), true);
assert.deepStrictEqual(DE.isRefreshRight(replete(left(1))), false);
assert.deepStrictEqual(DE.isRefreshRight(replete(right(1))), false);
});
it('isRepleteLeft', () => {
assert.deepStrictEqual(DE.isRepleteLeft(DE.initial), false);
assert.deepStrictEqual(DE.isRepleteLeft(DE.pending), false);
assert.deepStrictEqual(DE.isRepleteLeft(refresh(left(1))), false);
assert.deepStrictEqual(DE.isRepleteLeft(refresh(right(1))), false);
assert.deepStrictEqual(DE.isRepleteLeft(replete(left(1))), true);
assert.deepStrictEqual(DE.isRepleteLeft(replete(right(1))), false);
});
it('isRepleteRight', () => {
assert.deepStrictEqual(DE.isRepleteRight(DE.initial), false);
assert.deepStrictEqual(DE.isRepleteRight(DE.pending), false);
assert.deepStrictEqual(DE.isRepleteRight(refresh(left(1))), false);
assert.deepStrictEqual(DE.isRepleteRight(refresh(right(1))), false);
assert.deepStrictEqual(DE.isRepleteRight(replete(left(1))), false);
assert.deepStrictEqual(DE.isRepleteRight(replete(right(1))), true);
});
it('toRefresh', () => {
assert.deepStrictEqual(DE.toRefresh(DE.initial), DE.pending);
assert.deepStrictEqual(DE.toRefresh(DE.pending), DE.pending);
assert.deepStrictEqual(DE.toRefresh(refresh(left(1))), refresh(left(1)));
assert.deepStrictEqual(DE.toRefresh(refresh(right(1))), refresh(right(1)));
assert.deepStrictEqual(DE.toRefresh(replete(left(1))), refresh(left(1)));
assert.deepStrictEqual(DE.toRefresh(replete(right(1))), refresh(right(1)));
});
it('toReplete', () => {
assert.deepStrictEqual(DE.toReplete(DE.initial), DE.initial);
assert.deepStrictEqual(DE.toReplete(DE.pending), DE.initial);
assert.deepStrictEqual(DE.toReplete(refresh(left(1))), replete(left(1)));
assert.deepStrictEqual(DE.toReplete(refresh(right(1))), replete(right(1)));
assert.deepStrictEqual(DE.toReplete(replete(left(1))), replete(left(1)));
assert.deepStrictEqual(DE.toReplete(replete(right(1))), replete(right(1)));
});
it('fromEither', () => {
assert.deepStrictEqual(
DE.fromEither(() => left(1)),
DE.failure(1)
);
assert.deepStrictEqual(
DE.fromEither(() => right(1)),
DE.success(1)
);
});
it('fromEither2', () => {
assert.deepStrictEqual(DE.fromEither2(left(1)), DE.failure(1));
assert.deepStrictEqual(DE.fromEither2(right(1)), DE.success(1));
});
it('fromOption', () => {
assert.deepStrictEqual(DE.fromOption(() => 1)(some(0)), DE.success(0));
assert.deepStrictEqual(DE.fromOption(() => 1)(none), DE.failure(1));
});
it('fromNullable', () => {
assert.deepStrictEqual(DE.fromNullable(2), DE.success(2));
assert.deepStrictEqual(DE.fromNullable(null), DE.initial);
assert.deepStrictEqual(DE.fromNullable(undefined), DE.initial);
});
it('fold', () => {
const onInitial = () => 'initial';
const onPending = () => `pending`;
const onRefreshLeft = (s: string) => `refreshLeft${s.length}`;
const onRefreshRight = (s: string) => `refreshRight${s.length}`;
const onRepleteLeft = (s: string) => `repleteLeft${s.length}`;
const onRepleteRight = (s: string) => `repleteRight${s.length}`;
const fold = DE.fold(
onInitial,
onPending,
onRefreshLeft,
onRefreshRight,
onRepleteLeft,
onRepleteRight
);
assert.strictEqual(fold(DE.initial), 'initial');
assert.strictEqual(fold(DE.pending), 'pending');
assert.strictEqual(fold(DE.failure('abc')), 'repleteLeft3');
assert.strictEqual(fold(DE.success('abc')), 'repleteRight3');
assert.strictEqual(fold(DE.toRefresh(DE.failure('abc'))), 'refreshLeft3');
assert.strictEqual(fold(DE.toRefresh(DE.success('abc'))), 'refreshRight3');
});
it('refreshFold', () => {
const onInitial = () => `initial`;
const onPending = () => `pending`;
const onFailure = (s: string, r?: boolean) => `failure${s.length}${r}`;
const onSuccess = (s: string, r?: boolean) => `success${s.length}${r}`;
const refreshFold = DE.refreshFold(
onInitial,
onPending,
onFailure,
onSuccess
);
assert.strictEqual(refreshFold(DE.initial), 'initial');
assert.strictEqual(refreshFold(DE.pending), 'pending');
assert.strictEqual(
refreshFold(DE.toRefresh(DE.failure('abc'))),
'failure3true'
);
assert.strictEqual(
refreshFold(DE.toRefresh(DE.success('abc'))),
'success3true'
);
assert.strictEqual(refreshFold(DE.failure('abc')), 'failure3false');
assert.strictEqual(refreshFold(DE.success('abc')), 'success3false');
});
it('squash', () => {
const onNone = (r?: boolean) => `none${r}`;
const onFailure = (s: string, r?: boolean) => `failure${s.length}${r}`;
const onSuccess = (s: string, r?: boolean) => `success${s.length}${r}`;
const squash = DE.squash(onNone, onFailure, onSuccess);
assert.strictEqual(squash(DE.initial), 'nonefalse');
assert.strictEqual(squash(DE.pending), 'nonetrue');
assert.strictEqual(squash(DE.toRefresh(DE.failure('abc'))), 'failure3true');
assert.strictEqual(squash(DE.toRefresh(DE.success('abc'))), 'success3true');
assert.strictEqual(squash(DE.failure('abc')), 'failure3false');
assert.strictEqual(squash(DE.success('abc')), 'success3false');
});
it('fromEither2', () => {
assert.deepStrictEqual(DE.fromEither2(left(1)), DE.failure(1));
assert.deepStrictEqual(DE.fromEither2(right(1)), DE.success(1));
});
it('traverse', () => {
const traverse = DE.Traversable.traverse(option);
const fab = (n: number) => (n < 0 ? none : some(n));
assert.deepEqual(traverse(DE.initial, fab), some(DE.initial));
assert.deepEqual(traverse(DE.pending, fab), some(DE.pending));
assert.deepEqual(
traverse(DE.toRefresh(DE.success(0)), fab),
some(DE.toRefresh(DE.success(0)))
);
assert.deepEqual(
traverse(DE.toRefresh(DE.failure(0)), fab),
some(DE.toRefresh(DE.failure(0)))
);
assert.deepEqual(traverse(DE.toRefresh(DE.success(-1)), fab), none);
assert.deepEqual(
traverse(DE.toRefresh(DE.failure(-1)), fab),
some(DE.toRefresh(DE.failure(-1)))
);
assert.deepEqual(traverse(DE.success(0), fab), some(DE.success(0)));
assert.deepEqual(traverse(DE.failure(0), fab), some(DE.failure(0)));
assert.deepEqual(traverse(DE.success(-1), fab), none);
assert.deepEqual(traverse(DE.failure(-1), fab), some(DE.failure(-1)));
});
it('sequence', () => {
const sequence = DE.Traversable.sequence(option);
assert.deepEqual(sequence(DE.initial), some(DE.initial));
assert.deepEqual(sequence(DE.pending), some(DE.pending));
assert.deepEqual(sequence(DE.failure(0)), some(DE.failure(0)));
assert.deepEqual(
sequence(DE.toRefresh(DE.failure(0))),
some(DE.toRefresh(DE.failure(0)))
);
assert.deepEqual(sequence(DE.success(none)), none);
assert.deepEqual(sequence(DE.success(some(0))), some(DE.success(0)));
assert.deepEqual(sequence(DE.toRefresh(DE.success(none))), none);
assert.deepEqual(
sequence(DE.toRefresh(DE.success(some(0)))),
some(DE.toRefresh(DE.success(0)))
);
});
it('reduce', () => {
const reduce = DE.Foldable.reduce;
const add = (acc: number, cur: number): number => acc + cur;
assert.deepEqual(reduce(DE.initial, 0, add), 0);
assert.deepEqual(reduce(DE.pending, 0, add), 0);
assert.deepEqual(reduce(DE.success(1), 0, add), 1);
assert.deepEqual(reduce(DE.failure(1), 0, add), 0);
assert.deepEqual(reduce(DE.toRefresh(DE.success(1)), 0, add), 1);
assert.deepEqual(reduce(DE.toRefresh(DE.failure(1)), 0, add), 0);
});
it('foldMap', () => {
const fab = (s: string): number => s.length;
const foldMap = DE.foldMap(monoidSum)(fab);
assert.deepEqual(foldMap(DE.initial), monoidSum.empty);
assert.deepEqual(foldMap(DE.pending), monoidSum.empty);
assert.deepEqual(foldMap(DE.success('Hello')), 5);
assert.deepEqual(foldMap(DE.failure('Hello')), monoidSum.empty);
assert.deepEqual(foldMap(DE.toRefresh(DE.success('Hello'))), 5);
assert.deepEqual(
foldMap(DE.toRefresh(DE.failure('Hello'))),
monoidSum.empty
);
});
it('reduceRight', () => {
const reduce = DE.Foldable.reduceRight;
const add = (acc: number, cur: number): number => acc + cur;
assert.deepEqual(reduce(DE.initial, 0, add), 0);
assert.deepEqual(reduce(DE.pending, 0, add), 0);
assert.deepEqual(reduce(DE.success(1), 0, add), 1);
assert.deepEqual(reduce(DE.failure(1), 0, add), 0);
assert.deepEqual(reduce(DE.toRefresh(DE.success(1)), 0, add), 1);
assert.deepEqual(reduce(DE.toRefresh(DE.failure(1)), 0, add), 0);
});
function assertSemigroup(S: Semigroup<DE.DatumEither<string, number>>) {
assert.deepStrictEqual(S.concat(DE.initial, DE.initial), DE.initial);
assert.deepStrictEqual(S.concat(DE.initial, DE.pending), DE.pending);
assert.deepStrictEqual(S.concat(DE.initial, DE.failureR('a')), DE.failureR('a'));
assert.deepStrictEqual(S.concat(DE.initial, DE.successR(1)), DE.successR(1));
assert.deepStrictEqual(S.concat(DE.initial, DE.failure('a')), DE.failure('a'));
assert.deepStrictEqual(S.concat(DE.initial, DE.success(1)), DE.success(1));
assert.deepStrictEqual(S.concat(DE.pending, DE.initial), DE.pending);
assert.deepStrictEqual(S.concat(DE.pending, DE.pending), DE.pending);
assert.deepStrictEqual(S.concat(DE.pending, DE.failureR('a')), DE.failureR('a'));
assert.deepStrictEqual(S.concat(DE.pending, DE.successR(1)), DE.successR(1));
assert.deepStrictEqual(S.concat(DE.pending, DE.failure('a')), DE.failureR('a'));
assert.deepStrictEqual(S.concat(DE.pending, DE.success(1)), DE.successR(1));
assert.deepStrictEqual(S.concat(DE.failureR('a'), DE.initial), DE.failureR('a'));
assert.deepStrictEqual(S.concat(DE.failureR('a'), DE.pending), DE.failureR('a'));
assert.deepStrictEqual(S.concat(DE.failureR('a'), DE.failureR('a')), DE.failureR('a'));
assert.deepStrictEqual(S.concat(DE.failureR('a'), DE.successR(1)), DE.successR(1));
assert.deepStrictEqual(S.concat(DE.failureR('a'), DE.failure('a')), DE.failureR('a'));
assert.deepStrictEqual(S.concat(DE.failureR('a'), DE.success(1)), DE.successR(1));
assert.deepStrictEqual(S.concat(DE.successR(1), DE.initial), DE.successR(1));
assert.deepStrictEqual(S.concat(DE.successR(1), DE.pending), DE.successR(1));
assert.deepStrictEqual(S.concat(DE.successR(1), DE.failureR('a')), DE.successR(1));
assert.deepStrictEqual(S.concat(DE.successR(1), DE.successR(1)), DE.successR(2));
assert.deepStrictEqual(S.concat(DE.successR(1), DE.failure('a')), DE.successR(1));
assert.deepStrictEqual(S.concat(DE.successR(1), DE.success(1)), DE.successR(2));
assert.deepStrictEqual(S.concat(DE.failure('a'), DE.initial), DE.failure('a'));
assert.deepStrictEqual(S.concat(DE.failure('a'), DE.pending), DE.failureR('a'));
assert.deepStrictEqual(S.concat(DE.failure('a'), DE.failureR('a')), DE.failureR('a'));
assert.deepStrictEqual(S.concat(DE.failure('a'), DE.successR(1)), DE.successR(1));
assert.deepStrictEqual(S.concat(DE.failure('a'), DE.failure('a')), DE.failure('a'));
assert.deepStrictEqual(S.concat(DE.failure('a'), DE.success(1)), DE.success(1));
assert.deepStrictEqual(S.concat(DE.success(1), DE.initial), DE.success(1));
assert.deepStrictEqual(S.concat(DE.success(1), DE.pending), DE.successR(1));
assert.deepStrictEqual(S.concat(DE.success(1), DE.failureR('a')), DE.successR(1));
assert.deepStrictEqual(S.concat(DE.success(1), DE.successR(1)), DE.successR(2));
assert.deepStrictEqual(S.concat(DE.success(1), DE.failure('a')), DE.success(1));
assert.deepStrictEqual(S.concat(DE.success(1), DE.success(1)), DE.success(2));
}
it('getSemigroup', () => {
const S: Semigroup<DE.DatumEither<string, number>> = DE.getSemigroup(eitherGetSemigroup(semigroupSum));
assertSemigroup(S);
});
it('getMonoid', () => {
const M: Monoid<DE.DatumEither<string, number>> = DE.getMonoid(eitherGetSemigroup(semigroupSum));
assertSemigroup(M);
const values = [
DE.initial,
DE.pending,
DE.failureR('a'),
DE.successR(1),
DE.failure('a'),
DE.success(1)
];
values.forEach(value => {
assert.deepStrictEqual(M.concat(value, M.empty), value);
assert.deepStrictEqual(M.concat(M.empty, value), value)
});
});
it('getApplySemigroup', () => {
const S = DE.getApplySemigroup(eitherGetSemigroup(semigroupSum))
const values = [
DE.success(1),
DE.failure('a'),
DE.successR(1),
DE.failureR('a'),
];
const noValues = [
DE.initial,
DE.pending
];
assert.deepStrictEqual(S.concat(DE.initial, DE.initial), DE.initial);
assert.deepStrictEqual(S.concat(DE.initial, DE.pending), DE.initial);
assert.deepStrictEqual(S.concat(DE.pending, DE.pending), DE.pending);
assert.deepStrictEqual(S.concat(DE.pending, DE.initial), DE.pending);
noValues.forEach(noValue => {
values.forEach(value => {
assert.deepStrictEqual(S.concat(noValue, value), noValue);
assert.deepStrictEqual(S.concat(value, noValue), noValue);
});
});
const modifiers = [
identity,
DE.toRefresh
];
// Replete/Refresh of first valued datum does not matter
modifiers.forEach(modifier => {
assert.deepStrictEqual(S.concat(modifier(DE.success(1)), DE.success(1)), DE.success(2));
assert.deepStrictEqual(S.concat(modifier(DE.success(1)), DE.failure('a')), DE.success(1));
assert.deepStrictEqual(S.concat(modifier(DE.success(1)), DE.successR(1)), DE.successR(2));
assert.deepStrictEqual(S.concat(modifier(DE.success(1)), DE.failureR('a')), DE.successR(1));
assert.deepStrictEqual(S.concat(modifier(DE.failure('a')), DE.success(1)), DE.success(1));
assert.deepStrictEqual(S.concat(modifier(DE.failure('a')), DE.failure('a')), DE.failure('a'));
assert.deepStrictEqual(S.concat(modifier(DE.failure('a')), DE.successR(1)), DE.successR(1));
assert.deepStrictEqual(S.concat(modifier(DE.failure('a')), DE.failureR('a')), DE.failureR('a'));
});
})
});
|
clov3r/datum
|
src/OneShot.ts
|
/**
* @since 3.3.0
*
* Represents a value of one of three possible types (a disjoint union).
*
* An instance of `OneShot` is either an instance of `Initial`, `Pending`, or `Complete`.
* In effect it is a non-refreshable Datum.
*/
import { Alternative1 } from 'fp-ts/es6/Alternative';
import { Applicative } from 'fp-ts/es6/Applicative';
import { Compactable1, Separated } from 'fp-ts/es6/Compactable';
import { Either, isLeft, isRight } from 'fp-ts/es6/Either';
import { Eq } from 'fp-ts/es6/Eq';
import { Extend1 } from 'fp-ts/es6/Extend';
import { Filterable1 } from 'fp-ts/es6/Filterable';
import { Foldable1 } from 'fp-ts/es6/Foldable';
import { constFalse, identity, Predicate, constant } from 'fp-ts/es6/function';
import { HKT } from 'fp-ts/es6/HKT';
import { Monad1 } from 'fp-ts/es6/Monad';
import { MonadThrow1 } from 'fp-ts/es6/MonadThrow';
import { Monoid } from 'fp-ts/es6/Monoid';
import { isSome, Option } from 'fp-ts/es6/Option';
import { Ord } from 'fp-ts/es6/Ord';
import { Ordering } from 'fp-ts/es6/Ordering';
import { pipeable } from 'fp-ts/es6/pipeable';
import { Semigroup } from 'fp-ts/es6/Semigroup';
import { Show } from 'fp-ts/es6/Show';
import { Traversable1 } from 'fp-ts/es6/Traversable';
import { Witherable1 } from 'fp-ts/es6/Witherable';
/**
* @since 3.3.0
*/
declare module 'fp-ts/es6/HKT' {
interface URItoKind<A> {
'@nll/datum/OneShot': OneShot<A>;
}
}
/**
* @since 3.3.0
*/
export const URI = '@nll/datum/OneShot';
/**
* @since 3.3.0
*/
export type URI = typeof URI;
/**
* @since 3.3.0
*/
export interface Initial {
readonly _tag: 'Initial';
}
/**
* @since 3.3.0
*/
export interface Pending {
readonly _tag: 'Pending';
}
/**
* @since 3.3.0
*/
export interface Complete<D> {
readonly _tag: 'Complete';
readonly value: D;
}
/**
* @since 3.3.0
*/
export type OneShot<D> = Initial | Pending | Complete<D>;
/**
* Constructs an initial `OneShot` holding no value.
*
* @since 3.3.0
*/
export const initial: OneShot<never> = {
_tag: 'Initial',
};
/**
* Constructs a pending `OneShot` holding no value.
*
* @since 3.3.0
*/
export const pending: OneShot<never> = {
_tag: 'Pending',
};
/**
* Constructs a new Complete `OneShot` holding a value.
*
* @since 3.3.0
*/
export const complete = <A = never>(value: A): OneShot<A> => ({
_tag: 'Complete',
value,
});
/**
* @since 3.3.0
*/
export const constInitial = constant(initial);
/**
* @since 3.3.0
*/
export const constPending = constant(pending);
/**
* Takes a nullable value, if the value is not nully, turn it into a `Complete`, otherwise `Initial`.
*
* @since 3.3.0
*/
export const fromNullable = <A>(a: A | null | undefined): OneShot<A> =>
a === null || a === undefined ? initial : complete(a);
/**
* @since 3.3.0
*/
export const fold = <A, B>(
onInitial: () => B,
onPending: () => B,
onComplete: (a: A) => B
) => (ma: OneShot<A>): B => {
switch (ma._tag) {
case 'Initial':
return onInitial();
case 'Pending':
return onPending();
case 'Complete':
return onComplete(ma.value);
}
};
/**
* @since 3.3.0
*/
export const getShow = <A>(S: Show<A>): Show<OneShot<A>> => ({
show: fold(
constant('Initial'),
constant('Pending'),
(v) => `Complete(${S.show(v)})`
),
});
/**
* @since 3.3.0
*/
export const getEq = <A>(E: Eq<A>): Eq<OneShot<A>> => ({
equals: (x, y) =>
x === y ||
(isComplete(x) && isComplete(y) && E.equals(x.value, y.value)) ||
(isInitial(x) && isInitial(y)) ||
(isPending(x) && isPending(y)),
});
/**
* Semigroup returning the left-most non-`Initial` and non-`Pending` value. If both operands
* are `Complete`s then the inner values are appended using the provided
* `Semigroup`
*
* @since 3.3.0
*/
export const getSemigroup = <A>(S: Semigroup<A>): Semigroup<OneShot<A>> => ({
concat: (fx, fy): OneShot<A> =>
fold<A, OneShot<A>>(
constInitial,
constant(
fold<A, OneShot<A>>(constInitial, constPending, constPending)(fy)
),
(x) =>
fold<A, OneShot<A>>(constInitial, constPending, (y) =>
complete(S.concat(x, y))
)(fy)
)(fx),
});
const constZero = constant<0>(0);
const constNegOne = constant<-1>(-1);
const constOne = constant<1>(1);
/**
* The `Ord` instance allows `OneShot` values to be compared with
* `compare`, whenever there is an `Ord` instance for
* the type the `OneShot` contains.
*
* `Initial` < `Pending` < `Refresh` | `Complete`
*
* @since 3.3.0
*/
export function getOrd<A>(O: Ord<A>): Ord<OneShot<A>> {
return {
equals: getEq(O).equals,
compare: (xa, ya): Ordering =>
fold<A, Ordering>(
// x Initial
constant(fold<A, Ordering>(constZero, constNegOne, constNegOne)(ya)),
// x Pending
constant(fold<A, Ordering>(constOne, constZero, constNegOne)(ya)),
// x Complete
(x) => fold<A, Ordering>(constOne, constOne, (y) => O.compare(x, y))(ya)
)(xa),
};
}
/**
* `Apply` semigroup
*
* @since 3.3.0
*/
export const getApplySemigroup = <A>(S: Semigroup<A>): Semigroup<OneShot<A>> =>
getSemigroup(S);
/**
* @since 3.3.0
*/
export const getApplyMonoid = <A>(M: Monoid<A>): Monoid<OneShot<A>> => ({
...getApplySemigroup(M),
empty: complete(M.empty),
});
/**
* Returns `true` if the Async is an instance of `Initial`, `false` otherwise
*
* @since 3.3.0
*/
export const isInitial = <A>(ma: OneShot<A>): ma is Initial =>
ma._tag === 'Initial';
/**
* Returns `true` if the Async is an instance of `Pending`, `false` otherwise
*
* @since 3.3.0
*/
export const isPending = <A>(ma: OneShot<A>): ma is Pending =>
ma._tag === 'Pending';
/**
* Returns `true` if the Async is an instance of `Complete`, `false` otherwise
*
* @since 3.3.0
*/
export const isComplete = <A>(ma: OneShot<A>): ma is Complete<A> =>
ma._tag === 'Complete';
/**
* @since 3.3.0
*/
export const getOrElse = <A>(onInitial: () => A, onPending: () => A) => (
ma: OneShot<A>
): A => fold<A, A>(onInitial, onPending, identity)(ma);
/**
* @since 3.3.0
*/
export const elem = <A>(E: Eq<A>) => <E>(a: A, ma: OneShot<A>): boolean =>
fold<A, boolean>(constFalse, constFalse, (b) => E.equals(a, b))(ma);
/**
* Returns `false` if `Refresh` or returns the result of the application of the given predicate to the `Complete` value.
*
* @since 3.3.0
*/
export const exists = <A>(predicate: Predicate<A>) => <E>(
ma: OneShot<A>
): boolean => fold<A, boolean>(constFalse, constFalse, predicate)(ma);
/**
* @since 3.3.0
*/
const mapC = <A, B>(fa: OneShot<A>, f: (a: A) => B): OneShot<B> =>
fold<A, OneShot<B>>(constInitial, constPending, (a) => complete(f(a)))(fa);
/**
* @since 3.3.0
*/
const apC = <A, B>(fab: OneShot<(a: A) => B>, fa: OneShot<A>): OneShot<B> =>
fold<(a: A) => B, OneShot<B>>(
constInitial,
() => fold<A, OneShot<B>>(constInitial, constPending, constPending)(fa),
(f) =>
fold<A, OneShot<B>>(constInitial, constPending, (a) => complete(f(a)))(fa)
)(fab);
/**
* @since 3.3.0
*/
const chainC = <A, B>(fa: OneShot<A>, f: (a: A) => OneShot<B>): OneShot<B> =>
fold<A, OneShot<B>>(constInitial, constPending, f)(fa);
/**
* @since 3.3.0
*/
const reduceC = <A, B>(fa: OneShot<A>, b: B, f: (b: B, a: A) => B): B =>
fold<A, B>(
() => b,
() => b,
(a) => f(b, a)
)(fa);
/**
* @since 3.3.0
*/
const foldMapC = <M>(M: Monoid<M>) => <A>(fa: OneShot<A>, f: (a: A) => M): M =>
fold<A, M>(
() => M.empty,
() => M.empty,
f
)(fa);
/**
* @since 3.3.0
*/
const reduceRightC = <A, B>(fa: OneShot<A>, b: B, f: (a: A, b: B) => B): B =>
fold<A, B>(
() => b,
() => b,
(a) => f(a, b)
)(fa);
/**
* @since 3.3.0
*/
const traverseC = <F>(F: Applicative<F>) => <A, B>(
ta: OneShot<A>,
f: (a: A) => HKT<F, B>
): HKT<F, OneShot<B>> =>
fold<A, HKT<F, OneShot<B>>>(
() => F.of(initial),
() => F.of(pending),
(a) => F.map(f(a), complete)
)(ta);
/**
* @since 3.3.0
*/
const sequenceC = <F>(F: Applicative<F>) => <A>(
ta: OneShot<HKT<F, A>>
): HKT<F, OneShot<A>> =>
fold<HKT<F, A>, HKT<F, OneShot<A>>>(
() => F.of(initial),
() => F.of(pending),
(a) => F.map(a, complete)
)(ta);
/**
* @since 3.3.0
*/
const altC = <A>(fx: OneShot<A>, fy: () => OneShot<A>): OneShot<A> =>
fold<A, OneShot<A>>(fy, fy, complete)(fx);
/**
* @since 3.3.0
*/
const extendC = <A, B>(wa: OneShot<A>, f: (wa: OneShot<A>) => B): OneShot<B> =>
complete(f(wa));
/**
* @since 3.3.0
*/
const compactC = <A>(fa: OneShot<Option<A>>): OneShot<A> =>
fold<Option<A>, OneShot<A>>(constInitial, constPending, (a) =>
isSome(a) ? complete(a.value) : initial
)(fa);
const defaultSeparate = {
left: initial as OneShot<any>,
right: initial as OneShot<any>,
};
/**
* @since 3.3.0
*/
const separateC = <A, B>(
fa: OneShot<Either<A, B>>
): Separated<OneShot<A>, OneShot<B>> => {
const s = mapC(fa, (e) => ({
left: isLeft(e) ? complete(e.left) : initial,
right: isRight(e) ? complete(e.right) : initial,
}));
return getOrElse(
() => defaultSeparate,
() => defaultSeparate
)(s);
};
/**
* @since 3.3.0
*/
const filterC = <A>(fa: OneShot<A>, predicate: Predicate<A>): OneShot<A> =>
fold<A, OneShot<A>>(constInitial, constPending, (a) =>
predicate(a) ? fa : initial
)(fa);
/**
* @since 3.3.0
*/
const filterMapC = <A, B>(ma: OneShot<A>, f: (a: A) => Option<B>): OneShot<B> =>
compactC(mapC(ma, f));
/**
* @since 3.3.0
*/
const partitionC = <A>(
fa: OneShot<A>,
predicate: Predicate<A>
): Separated<OneShot<A>, OneShot<A>> => ({
left: filterC(fa, (a) => !predicate(a)),
right: filterC(fa, predicate),
});
/**
* @since 3.3.0
*/
const partitionMapC = <A, B, C>(fa: OneShot<A>, f: (a: A) => Either<B, C>) =>
separateC(mapC(fa, f));
/**
* @since 3.3.0
*/
const witherC = <F>(F: Applicative<F>) => <A, B>(
fa: OneShot<A>,
f: (a: A) => HKT<F, Option<B>>
): HKT<F, OneShot<B>> =>
fold<A, HKT<F, OneShot<B>>>(
constant(F.of(initial)),
constant(F.of(pending)),
(a) => F.map(f(a), (o) => (isSome(o) ? complete(o.value) : initial))
)(fa);
/**
* @since 3.3.0
*/
const wiltC = <F>(F: Applicative<F>) => <A, B, C>(
fa: OneShot<A>,
f: (a: A) => HKT<F, Either<B, C>>
): HKT<F, Separated<OneShot<B>, OneShot<C>>> => {
const s = mapC(fa, (a) =>
F.map(f(a), (e) => ({
left: isLeft(e) ? complete(e.left) : initial,
right: isRight(e) ? complete(e.right) : initial,
}))
);
return isComplete(s) ? s.value : F.of(defaultSeparate);
};
/**
* @since 3.3.0
*/
const throwErrorC = <E, A>(e: E): OneShot<A> => initial;
/**
* @since 3.3.0
*/
export const OneShot: Monad1<URI> &
Foldable1<URI> &
Traversable1<URI> &
Alternative1<URI> &
Extend1<URI> &
Compactable1<URI> &
Filterable1<URI> &
Witherable1<URI> &
MonadThrow1<URI> = {
URI,
map: mapC,
of: complete,
ap: apC,
chain: chainC,
reduce: reduceC,
foldMap: foldMapC,
reduceRight: reduceRightC,
traverse: traverseC,
sequence: sequenceC,
zero: constInitial,
alt: altC,
extend: extendC,
compact: compactC,
separate: separateC,
filter: filterC,
filterMap: filterMapC,
partition: partitionC,
partitionMap: partitionMapC,
wither: witherC,
wilt: wiltC,
throwError: throwErrorC,
};
const {
alt,
ap,
apFirst,
apSecond,
chain,
chainFirst,
duplicate,
extend,
filter,
filterMap,
flatten,
foldMap,
map,
partition,
partitionMap,
reduce,
reduceRight,
compact,
separate,
fromEither,
filterOrElse,
fromOption,
fromPredicate,
} = pipeable(OneShot);
export {
/**
* @since 3.3.0
*/
alt,
/**
* @since 3.3.0
*/
ap,
/**
* @since 3.3.0
*/
apFirst,
/**
* @since 3.3.0
*/
apSecond,
/**
* @since 3.3.0
*/
chain,
/**
* @since 3.3.0
*/
chainFirst,
/**
* @since 3.3.0
*/
duplicate,
/**
* @since 3.3.0
*/
extend,
/**
* @since 3.3.0
*/
filter,
/**
* @since 3.3.0
*/
filterMap,
/**
* @since 3.3.0
*/
flatten,
/**
* @since 3.3.0
*/
foldMap,
/**
* @since 3.3.0
*/
map,
/**
* @since 3.3.0
*/
partition,
/**
* @since 3.3.0
*/
partitionMap,
/**
* @since 3.3.0
*/
reduce,
/**
* @since 3.3.0
*/
reduceRight,
/**
* @since 3.3.0
*/
compact,
/**
* @since 3.3.0
*/
separate,
/**
* @since 3.3.0
*/
fromEither,
/**
* @since 3.3.0
*/
filterOrElse,
/**
* @since 3.3.0
*/
fromOption,
/**
* @since 3.3.0
*/
fromPredicate,
};
|
clov3r/datum
|
src/index.ts
|
<filename>src/index.ts
/**
* @since 3.1.0
*/
import * as datum from './Datum';
import * as datumEither from './DatumEither';
import * as datumThese from './DatumThese';
import * as oneShot from './OneShot';
export {
/**
* @since 3.1.0
*/
datum,
/**
* @since 3.1.0
*/
datumEither,
/**
* @since TODO
*/
datumThese,
/**
* @since 3.3.0
*/
oneShot,
};
|
clov3r/datum
|
test/index.ts
|
import * as assert from 'assert';
import { datum, datumEither, datumThese, oneShot } from '../src';
import * as Datum from '../src/Datum';
import * as DatumEither from '../src/DatumEither';
import * as DatumThese from '../src/DatumThese';
import * as OneShot from '../src/OneShot';
describe('Index', () => {
it('Re-exports the Datum module', () => {
assert.strictEqual(datum, Datum);
});
it('Re-exports the DatumEither module', () => {
assert.strictEqual(datumEither, DatumEither);
});
it ('Re-exports the DatumThese module', () => {
assert.strictEqual(datumThese, DatumThese)
});
it('Re-exports the OneShot module', () => {
assert.strictEqual(oneShot, OneShot);
});
});
|
clov3r/datum
|
src/DatumEither.ts
|
/**
* @since 2.0.0
*
* Represents a value of one of six possible types (a disjoint union).
*
* An instance of `DatumEither` is equivalent to `Datum<Either<E, A>>`
*
* A common use of `DatumEither` is as a container for dealing with refreshable data values that
* can have error conditions. The full type list is:
*
* - `Initial`
* - `Pending`
* - `Refresh<Either<E, A>>`
* - `Refresh<Left<E>>`
* - `Refresh<Right<A>>`
* - `Replete<Either<E, A>>`
* - `Replete<Left<E>>`
* - `Replete<Right<A>>`
*
* There are additional helper methods for going from refresh to replete and back.
*/
import {
Either,
left,
isRight,
Right,
isLeft,
Left,
right,
fromOption as eitherFromOption,
fold as eitherFold,
} from 'fp-ts/es6/Either';
import { getEitherM } from 'fp-ts/es6/EitherT';
import { Monad2 } from 'fp-ts/es6/Monad';
import { pipe, pipeable } from 'fp-ts/es6/pipeable';
import * as D from './Datum';
import { Option } from 'fp-ts/es6/Option';
import { Lazy, constant, FunctionN, flow } from 'fp-ts/es6/function';
import { Apply2, sequenceS, sequenceT } from 'fp-ts/es6/Apply';
import { Applicative as ApplicativeHKT, Applicative2 } from 'fp-ts/es6/Applicative';
import { HKT } from 'fp-ts/es6/HKT';
import { Traversable2 } from 'fp-ts/es6/Traversable';
import { Monoid } from 'fp-ts/es6/Monoid';
import { Functor2 } from 'fp-ts/es6/Functor';
import { Chain2 } from 'fp-ts/es6/Chain';
import { Alt2 } from 'fp-ts/es6/Alt';
import { Alternative2 } from 'fp-ts/es6/Alternative';
import { MonadThrow2 } from 'fp-ts/es6/MonadThrow';
import { Foldable2 } from 'fp-ts/es6/Foldable';
import { Bifunctor2 } from 'fp-ts/es6/Bifunctor';
import { Semigroup } from 'fp-ts/es6/Semigroup';
/**
* A Monad instance for `Datum<Either<E, A>>`
*
* @since 2.0.0
*/
declare module 'fp-ts/es6/HKT' {
interface URItoKind2<E, A> {
'@nll/datum/DatumEither': D.Datum<Either<E, A>>;
}
}
/**
* @since 2.0.0
*/
export const URI = '@nll/datum/DatumEither';
/**
* @since 2.0.0
*/
export type URI = typeof URI;
/**
* @since 2.1.0
*/
export type DatumEither<E, A> = D.Datum<Either<E, A>>;
/**
* @since 3.4.0
*/
export type Valued<A> = D.Refresh<A> | D.Replete<A>;
/**
* @since 2.3.0
*/
export type Success<A> = Valued<Right<A>>;
/**
* @since 2.3.0
*/
export type Failure<E> = Valued<Left<E>>;
/**
* @since 3.2.0
*/
export type ToLeft<T> = T extends DatumEither<infer L, infer _> ? L : never;
/**
* @since 3.2.0
*/
export type ToRight<T> = T extends DatumEither<infer _, infer R> ? R : never;
/**
* @since 2.4.1
*/
export const initial: DatumEither<never, never> = D.initial;
/**
* @since 2.4.1
*/
export const pending: DatumEither<never, never> = D.pending;
/**
* @since 2.1.0
*/
export const success = <E = never, A = never>(a: A): DatumEither<E, A> =>
D.replete(right(a));
/**
* @since 2.1.0
*/
export const failure = <E = never, A = never>(e: E): DatumEither<E, A> =>
D.replete(left(e));
/**
* @since 3.4.0
*/
export const successR = <E = never, A = never>(a: A): DatumEither<E, A> =>
toRefresh(D.replete(right(a)));
/**
* @since 3.4.0
*/
export const failureR = <E = never, A = never>(e: E): DatumEither<E, A> =>
toRefresh(D.replete(left(e)));
/**
* @since 2.4.1
*/
export function constInitial<E = never, D = never>(): DatumEither<E, D> {
return initial;
}
/**
* @since 2.4.1
*/
export const constPending = <E = never, D = never>(): DatumEither<E, D> =>
pending;
/**
* @since 2.7.0
*/
export const isInitial = D.isInitial;
/**
* @since 2.7.0
*/
export const isPending = D.isPending;
/**
* @since 2.7.0
*/
export const isRefresh = D.isRefresh;
/**
* @since 2.7.0
*/
export const isReplete = D.isReplete;
/**
* @since 2.7.0
*/
export const isValued = D.isValued;
/**
* @since 2.7.0
*/
export const isRefreshLeft = <E, A>(
fea: DatumEither<E, A>
): fea is D.Refresh<Left<E>> => isRefresh(fea) && isLeft(fea.value);
/**
* @since 2.7.0
*/
export const isRefreshRight = <E, A>(
fea: DatumEither<E, A>
): fea is D.Refresh<Right<A>> => isRefresh(fea) && isRight(fea.value);
/**
* @since 2.7.0
*/
export const isRepleteLeft = <E, A>(
fea: DatumEither<E, A>
): fea is D.Replete<Left<E>> => isReplete(fea) && isLeft(fea.value);
/**
* @since 2.7.0
*/
export const isRepleteRight = <E, A>(
fea: DatumEither<E, A>
): fea is D.Replete<Right<A>> => isReplete(fea) && isRight(fea.value);
/**
* @since 2.1.0
*/
export const isSuccess = <E, A>(fea: DatumEither<E, A>): fea is Success<A> =>
isValued(fea) && isRight(fea.value);
/**
* @since 2.1.0
*/
export const isFailure = <E, A>(fea: DatumEither<E, A>): fea is Failure<E> =>
isValued(fea) && isLeft(fea.value);
/**
* @since 2.1.0
*/
export const toRefresh = <E, A>(fea: DatumEither<E, A>): DatumEither<E, A> =>
D.fold<Either<E, A>, DatumEither<E, A>>(
constPending,
constPending,
constant(fea),
D.refresh
)(fea);
/**
* @since 2.7.0
*/
export const toReplete = <E, A>(fea: DatumEither<E, A>): DatumEither<E, A> =>
D.fold<Either<E, A>, DatumEither<E, A>>(
constInitial,
constInitial,
D.replete,
constant(fea)
)(fea);
/**
* fromEither will remove the Lazy input in the next major release
*
* @since 2.2.0
*
* @deprecated
*/
export const fromEither = <E, A>(e: Lazy<Either<E, A>>): DatumEither<E, A> =>
D.replete(e());
/**
* fromEither2 will replace fromEither in the next major release
*
* @since 3.4.0
*
* @deprecated
*/
export const fromEither2 = <E, A>(e: Either<E, A>): DatumEither<E, A> =>
D.replete(e);
/**
* @since 2.2.0
*/
export const fromOption = <E, A>(onNone: Lazy<E>) => (
o: Option<A>
): DatumEither<E, A> => D.replete(eitherFromOption(onNone)(o));
/**
* Takes a nullable value, if the value is not nully, turn it into a `Success<A>`, otherwise `Initial`.
*
* @since 2.4.0
*/
export const fromNullable = <E, A>(
a: A | null | undefined
): DatumEither<E, A> => (a === null || a === undefined ? initial : success(a));
/**
* @since 2.7.0
*/
export const fold = <E, A, B>(
onInitial: Lazy<B>,
onPending: Lazy<B>,
onRefreshLeft: FunctionN<[E], B>,
onRefreshRight: FunctionN<[A], B>,
onRepleteLeft: FunctionN<[E], B>,
onRepleteRight: FunctionN<[A], B>
) => (fea: DatumEither<E, A>): B =>
pipe(
fea,
D.fold(
onInitial,
onPending,
eitherFold(onRefreshLeft, onRefreshRight),
eitherFold(onRepleteLeft, onRepleteRight)
)
);
/**
* @since 2.1.0
*/
export const refreshFold = <E, A, B>(
onInitial: () => B,
onPending: () => B,
onFailure: (e: E, r?: boolean) => B,
onSuccess: (a: A, r?: boolean) => B
) => (fea: DatumEither<E, A>): B =>
D.fold<Either<E, A>, B>(
onInitial,
onPending,
(e) => (isRight(e) ? onSuccess(e.right, true) : onFailure(e.left, true)),
(e) => (isRight(e) ? onSuccess(e.right, false) : onFailure(e.left, false))
)(fea);
/**
* @since 2.3.0
*/
export const squash = <E, A, B>(
onNone: (r?: boolean) => B,
onFailure: (e: E, r?: boolean) => B,
onSuccess: (a: A, r?: boolean) => B
) => (fea: DatumEither<E, A>) =>
D.fold<Either<E, A>, B>(
() => onNone(false),
() => onNone(true),
(e) => (isRight(e) ? onSuccess(e.right, true) : onFailure(e.left, true)),
(e) => (isRight(e) ? onSuccess(e.right, false) : onFailure(e.left, false))
)(fea);
/**
* @since 3.4.0
*/
const traverseC = <F>(F: ApplicativeHKT<F>) => <E, A, B>(
ta: DatumEither<E, A>,
f: (a: A) => HKT<F, B>
): HKT<F, DatumEither<E, B>> =>
fold<E, A, HKT<F, DatumEither<E, B>>>(
() => F.of(initial),
() => F.of(pending),
(e) => F.of(D.refresh(left(e))),
(a) => F.map(f(a), flow(right, D.refresh)),
(e) => F.of(D.replete(left(e))),
(a) => F.map(f(a), flow(right, D.replete))
)(ta);
/**
* @since 3.4.0
*/
const sequenceC = <F>(F: ApplicativeHKT<F>) => <E, A>(
ta: DatumEither<E, HKT<F, A>>
): HKT<F, DatumEither<E, A>> =>
fold<E, HKT<F, A>, HKT<F, DatumEither<E, A>>>(
() => F.of(initial),
() => F.of(pending),
(e) => F.of(D.refresh(left(e))),
(a) => F.map(a, flow(right, D.refresh)),
(e) => F.of(D.replete(left(e))),
(a) => F.map(a, flow(right, D.replete))
)(ta);
/**
* @since 3.4.0
*/
const reduceC = <E, A, B>(
fa: DatumEither<E, A>,
b: B,
f: (b: B, a: A) => B
): B =>
pipe(
fa,
fold(
() => b,
() => b,
() => b,
(a) => f(b, a),
() => b,
(a) => f(b, a)
)
);
/**
* @since 3.4.0
*/
const foldMapC = <M>(M: Monoid<M>) => <E, A>(
fa: DatumEither<E, A>,
f: (a: A) => M
): M =>
fold<E, A, M>(
() => M.empty,
() => M.empty,
() => M.empty,
f,
() => M.empty,
f
)(fa);
/**
* @since 3.4.0
*/
const reduceRightC = <E, A, B>(
fa: DatumEither<E, A>,
b: B,
f: (a: A, b: B) => B
): B =>
fold<E, A, B>(
() => b,
() => b,
() => b,
(a) => f(a, b),
() => b,
(a) => f(a, b)
)(fa);
// TODO: After we bump the min bound to >= 2.10, replace this with individual helper fns
const eitherTDatum = getEitherM(D.Monad)
/**
* @since 3.5.0
*/
export const Functor: Functor2<URI> = {
URI,
map: eitherTDatum.map
}
/**
* @since 3.5.0
*/
export const Bifunctor: Bifunctor2<URI> = {
URI,
mapLeft: eitherTDatum.mapLeft,
bimap: eitherTDatum.bimap
}
/**
* @since 3.5.0
*
* Note: This instance agrees with the standalone Applicative/Chain/Monad instances but _disagrees_ with the deprecated `datum` mega-instance.
*/
export const Apply: Apply2<URI> = {
...Functor,
ap: eitherTDatum.ap
}
/**
* @since 3.5.0
*/
export const Chain: Chain2<URI> = {
...Apply,
chain: eitherTDatum.chain
}
/**
* @since 3.5.0
*/
export const Applicative: Applicative2<URI> = {
...Apply,
of: eitherTDatum.of
}
/**
* @since 3.5.0
*/
export const Alt: Alt2<URI> = {
...Functor,
alt: eitherTDatum.alt
}
/**
* @since 3.5.0
*/
export const Alternative: Alternative2<URI> = {
...Alt,
...Applicative,
zero: constInitial
}
/**
* @since 3.5.0
*/
export const Monad: Monad2<URI> = {
...Chain,
of: eitherTDatum.of
}
/**
* @since 3.5.0
*/
export const MonadThrow: MonadThrow2<URI> = {
...Monad,
throwError: failure
}
/**
* @since 3.5.0
*/
export const Foldable: Foldable2<URI> = {
URI,
reduce: reduceC,
reduceRight: reduceRightC,
foldMap: foldMapC
}
/**
* @since 3.5.0
*/
export const Traversable: Traversable2<URI> = {
...Functor,
...Foldable,
sequence: sequenceC,
traverse: traverseC
}
/**
* @since 4.0.0
*/
export const getSemigroup = <E, A>(S: Semigroup<Either<E, A>>): Semigroup<DatumEither<E, A>> =>
D.getSemigroup(S)
/**
* @since 4.0.0
*/
export const getMonoid = <E, A>(S: Semigroup<Either<E, A>>): Monoid<DatumEither<E, A>> =>
D.getMonoid(S)
/**
* @since 4.0.0
*/
export const getApplySemigroup = <E, A>(S: Semigroup<Either<E, A>>): Semigroup<DatumEither<E, A>> =>
D.getApplySemigroup(S)
/**
* @since 4.0.0
*/
export const sequenceTuple = sequenceT(Apply);
/**
* @since 4.0.0
*/
export const sequenceStruct = sequenceS(Apply);
/**
* @since 4.0.0
*/
const {
ap,
apFirst,
apSecond,
chain,
chainFirst,
flatten,
map,
} = pipeable(Monad);
/**
* @since 3.2.0
*/
const {
bimap,
mapLeft,
} = pipeable(Bifunctor)
/**
* @since 3.2.0
*/
const {
alt,
} = pipeable(Alt)
const {
foldMap,
reduce,
reduceRight,
} = pipeable(Foldable)
export {
/**
* @since 2.0.0
*/
alt,
/**
* @since 4.0.0
*/
ap,
/**
* @since 2.0.0
*/
apFirst,
/**
* @since 2.0.0
*/
apSecond,
/**
* @since 2.0.0
*/
bimap,
/**
* @since 2.0.0
*/
chain,
/**
* @since 2.0.0
*/
chainFirst,
/**
* @since 2.0.0
*/
flatten,
/**
* @since 2.0.0
*/
map,
/**
* @since 2.0.0
*/
mapLeft,
/**
* @since 3.4.0
*/
reduce,
/**
* @since 3.4.0
*/
foldMap,
/**
* @since 3.4.0
*/
reduceRight,
};
|
clov3r/datum
|
src/DatumThese.ts
|
<reponame>clov3r/datum<gh_stars>10-100
/**
* @since 3.5.0
*
* Represents a value of one of eight possible types (a disjoint union).
*
* An instance of `DatumThese` is equivalent to `Datum<These<E, A>>`
*
* A common use of `DatumThese` is as a container for dealing with refreshable data values that
* can have error conditions (including partial error conditions). The full type list is:
*
* - `Initial`
* - `Pending`
* - `Refresh<These<E, A>>`
* - `Refresh<Left<E>>`
* - `Refresh<Right<A>>`
* - `Refresh<Both<E, A>>`
* - `Replete<Either<E, A>>`
* - `Replete<Left<E>>`
* - `Replete<Right<A>>`
* - `Replete<Both<E, A>>`
*
* There are additional helper methods for going from refresh to replete and back.
*
*/
import {
Left,
Right
} from 'fp-ts/es6/Either'
import {
These,
left,
isRight,
right,
isLeft,
both,
isBoth,
fold as theseFold,
Both,
getShow as theseGetShow,
getEq as theseGetEq,
} from 'fp-ts/es6/These'
import * as D from './Datum';
import { Option, fold as optionFold } from 'fp-ts/es6/Option';
import { constant, flow, FunctionN, Lazy, pipe } from 'fp-ts/es6/function'
import { Applicative, Applicative2C } from 'fp-ts/es6/Applicative';
import { HKT } from 'fp-ts/es6/HKT';
import { Semigroup } from 'fp-ts/es6/Semigroup';
import { Monoid } from 'fp-ts/es6/Monoid';
import { Traversable2 } from 'fp-ts/es6/Traversable';
import { getTheseM, TheseM1 } from 'fp-ts/lib/TheseT';
import { pipeable } from 'fp-ts/es6/pipeable';
import { Functor2 } from 'fp-ts/es6/Functor';
import { Apply2C } from 'fp-ts/es6/Apply';
import { Monad2C } from 'fp-ts/es6/Monad';
import { Chain2C } from 'fp-ts/es6/Chain';
import { Bifunctor2 } from 'fp-ts/es6/Bifunctor';
import { Foldable2 } from 'fp-ts/es6/Foldable';
import { MonadThrow2C } from 'fp-ts/es6/MonadThrow';
import { Show } from 'fp-ts/es6/Show';
import { Eq } from 'fp-ts/es6/Eq';
/**
* A Monad instance for `Datum<These<E, A>>`
*
* @since 3.5.0
*/
declare module 'fp-ts/es6/HKT' {
interface URItoKind2<E, A> {
'@nll/datum/DatumThese': D.Datum<These<E, A>>;
}
}
/**
* @since 3.5.0
*/
export const URI = '@nll/datum/DatumThese';
/**
* @since 3.5.0
*/
export type URI = typeof URI;
/**
* @since 3.5.0
*/
export type DatumThese<E, A> = D.Datum<These<E, A>>;
/**
* @since 3.5.0
*/
export type Valued<A> = D.Refresh<A> | D.Replete<A>;
/**
* @since 3.5.0
*/
export type Success<A> = Valued<Right<A>>;
/**
* @since 3.5.0
*/
export type Failure<E> = Valued<Left<E>>;
/**
* @since 3.5.0
*/
export type PartialSuccess<E, A> = Valued<Both<E, A>>
/**
* @since 3.5.0
*/
export type ToLeft<T> = T extends DatumThese<infer L, infer _> ? L : never;
/**
* @since 3.5.0
*/
export type ToRight<T> = T extends DatumThese<infer _, infer R> ? R : never;
/**
* @since 3.5.0
*/
export const initial: DatumThese<never, never> = D.initial;
/**
* @since 3.5.0
*/
export const pending: DatumThese<never, never> = D.pending;
/**
* @since 3.5.0
*/
export const success = <E = never, A = never>(a: A): DatumThese<E, A> =>
D.replete(right(a));
/**
* @since 3.5.0
*/
export const failure = <E = never, A = never>(e: E): DatumThese<E, A> =>
D.replete(left(e));
/**
* @since 3.5.0
*/
export const partialSuccess = <E = never, A = never>(e: E, a: A): DatumThese<E, A> =>
D.replete(both(e, a))
/**
* @since 3.5.0
*/
export const successR = <E = never, A = never>(a: A): DatumThese<E, A> =>
D.refresh(right(a));
/**
* @since 3.5.0
*/
export const failureR = <E = never, A = never>(e: E): DatumThese<E, A> =>
D.refresh(left(e));
/**
* @since 3.5.0
*/
export const partialSuccessR = <E = never, A = never>(e: E, a: A): DatumThese<E, A> =>
D.refresh(both(e, a))
/**
* @since 3.5.0
*/
export function constInitial<E = never, D = never>(): DatumThese<E, D> {
return initial;
}
/**
* @since 3.5.0
*/
export const constPending = <E = never, D = never>(): DatumThese<E, D> =>
pending;
/**
* @since 3.5.0
*/
export const isInitial = D.isInitial;
/**
* @since 3.5.0
*/
export const isPending = D.isPending;
/**
* @since 3.5.0
*/
export const isRefresh = D.isRefresh;
/**
* @since 3.5.0
*/
export const isReplete = D.isReplete;
/**
* @since 3.5.0
*/
export const isValued = D.isValued;
/**
* @since 3.5.0
*/
export const isRefreshLeft = <E, A>(
fea: DatumThese<E, A>
): fea is D.Refresh<Left<E>> => isRefresh(fea) && isLeft(fea.value);
/**
* @since 3.5.0
*/
export const isRefreshRight = <E, A>(
fea: DatumThese<E, A>
): fea is D.Refresh<Right<A>> => isRefresh(fea) && isRight(fea.value);
/**
* @since 3.5.0
*/
export const isRefreshBoth = <E, A>(
fea: DatumThese<E, A>
): fea is D.Refresh<Both<E, A>> => isRefresh(fea) && isBoth(fea.value)
/**
* @since 3.5.0
*/
export const isRepleteLeft = <E, A>(
fea: DatumThese<E, A>
): fea is D.Replete<Left<E>> => isReplete(fea) && isLeft(fea.value);
/**
* @since 3.5.0
*/
export const isRepleteRight = <E, A>(
fea: DatumThese<E, A>
): fea is D.Replete<Right<A>> => isReplete(fea) && isRight(fea.value);
/**
* @since 3.5.0
*/
export const isRepleteBoth = <E, A>(
fea: DatumThese<E, A>
): fea is D.Replete<Both<E, A>> => isReplete(fea) && isBoth(fea.value)
/**
* @since 3.5.0
*/
export const isSuccess = <E, A>(fea: DatumThese<E, A>): fea is Success<A> =>
isValued(fea) && isRight(fea.value);
/**
* @since 3.5.0
*/
export const isFailure = <E, A>(fea: DatumThese<E, A>): fea is Failure<E> =>
isValued(fea) && isLeft(fea.value);
/**
* @since 3.5.0
*/
export const isPartialSuccess = <E, A>(fea: DatumThese<E, A>): fea is PartialSuccess<E, A> =>
isValued(fea) && isBoth(fea.value);
/**
* @since 3.5.0
*/
export const toRefresh = <E, A>(fea: DatumThese<E, A>): DatumThese<E, A> =>
D.fold<These<E, A>, DatumThese<E, A>>(
constPending,
constPending,
constant(fea),
D.refresh
)(fea);
/**
* @since 3.5.0
*/
export const toReplete = <E, A>(fea: DatumThese<E, A>): DatumThese<E, A> =>
D.fold<These<E, A>, DatumThese<E, A>>(
constInitial,
constInitial,
D.replete,
constant(fea)
)(fea);
// TODO - fromThese vs fromThese2 ? Either equivalents are marked deprecated
/**
* @since 3.5.0
*/
export const fromOption = <E, A>(onNone: Lazy<E>) => (
o: Option<A>
): DatumThese<E, A> => D.replete(optionFold<A, These<E, A>>(() => left(onNone()), right)(o));
/**
* Takes a nullable value, if the value is not nully, turn it into a `Success<A>`, otherwise `Initial`.
*
* @since 3.5.0
*/
export const fromNullable = <E, A>(
a: A | null | undefined
): DatumThese<E, A> => (a === null || a === undefined ? initial : success(a));
/**
* @since 3.5.0
*/
export const fold = <E, A, B>(
onInitial: Lazy<B>,
onPending: Lazy<B>,
onRefreshLeft: FunctionN<[E], B>,
onRefreshRight: FunctionN<[A], B>,
onRefreshBoth: FunctionN<[E, A], B>,
onRepleteLeft: FunctionN<[E], B>,
onRepleteRight: FunctionN<[A], B>,
onRepleteBoth: FunctionN<[E, A], B>
) => (fea: DatumThese<E, A>): B =>
pipe(
fea,
D.fold(
onInitial,
onPending,
theseFold(onRefreshLeft, onRefreshRight, onRefreshBoth),
theseFold(onRepleteLeft, onRepleteRight, onRepleteBoth)
)
);
/**
* @since 3.5.0
*/
export const refreshFold = <E, A, B>(
onInitial: () => B,
onPending: () => B,
onFailure: (e: E, r?: boolean) => B,
onSuccess: (a: A, r?: boolean) => B,
onPartialSuccess: (e: E, a: A, r?: boolean) => B
) => (fea: DatumThese<E, A>): B =>
D.fold<These<E, A>, B>(
onInitial,
onPending,
(e) => (isRight(e) ? onSuccess(e.right, true) : isBoth(e) ? onPartialSuccess(e.left, e.right, true) : onFailure(e.left, true)),
(e) => (isRight(e) ? onSuccess(e.right, false) : isBoth(e) ? onPartialSuccess(e.left, e.right, false) : onFailure(e.left, false))
)(fea);
/**
* @since 3.5.0
*/
export const squash = <E, A, B>(
onNone: (r?: boolean) => B,
onFailure: (e: E, r?: boolean) => B,
onSuccess: (a: A, r?: boolean) => B,
onPartialSuccess: (e: E, a: A, r?: boolean) => B
) => (fea: DatumThese<E, A>) =>
D.fold<These<E, A>, B>(
() => onNone(false),
() => onNone(true),
(e) => (isRight(e) ? onSuccess(e.right, true) : isBoth(e) ? onPartialSuccess(e.left, e.right, true) : onFailure(e.left, true)),
(e) => (isRight(e) ? onSuccess(e.right, false) : isBoth(e) ? onPartialSuccess(e.left, e.right, false) : onFailure(e.left, false))
)(fea);
/**
* @since 3.5.0
*/
const traverseC = <F>(F: Applicative<F>) => <E, A, B>(
ta: DatumThese<E, A>,
f: (a: A) => HKT<F, B>
): HKT<F, DatumThese<E, B>> =>
fold<E, A, HKT<F, DatumThese<E, B>>>(
() => F.of(initial),
() => F.of(pending),
(e) => F.of(D.refresh(left(e))),
(a) => F.map(f(a), flow(right, D.refresh)),
(e, a) => F.map(f(a), flow(b => both(e, b), D.refresh)),
(e) => F.of(D.replete(left(e))),
(a) => F.map(f(a), flow(right, D.replete)),
(e, a) => F.map(f(a), flow(b => both(e, b), D.replete))
)(ta);
/**
* @since 3.5.0
*/
const sequenceC = <F>(F: Applicative<F>) => <E, A>(
ta: DatumThese<E, HKT<F, A>>
): HKT<F, DatumThese<E, A>> =>
fold<E, HKT<F, A>, HKT<F, DatumThese<E, A>>>(
() => F.of(initial),
() => F.of(pending),
(e) => F.of(D.refresh(left(e))),
(a) => F.map(a, flow(right, D.refresh)),
(e, a) => F.map(a, flow(b => both(e, b), D.refresh)),
(e) => F.of(D.replete(left(e))),
(a) => F.map(a, flow(right, D.replete)),
(e, a) => F.map(a, flow(b => both(e, b), D.replete))
)(ta);
/**
* @since 3.5.0
*/
const reduceC = <E, A, B>(
fa: DatumThese<E, A>,
b: B,
f: (b: B, a: A) => B
): B =>
pipe(
fa,
fold(
() => b,
() => b,
() => b,
(a) => f(b, a),
(e, a) => f(b, a),
() => b,
(a) => f(b, a),
(e, a) => f(b, a)
)
);
/**
* @since 3.5.0
*/
const foldMapC = <M>(M: Monoid<M>) => <E, A>(
fa: DatumThese<E, A>,
f: (a: A) => M
): M =>
fold<E, A, M>(
() => M.empty,
() => M.empty,
() => M.empty,
f,
(e, a) => f(a),
() => M.empty,
f,
(e, a) => f(a)
)(fa);
/**
* @since 3.5.0
*/
const reduceRightC = <E, A, B>(
fa: DatumThese<E, A>,
b: B,
f: (a: A, b: B) => B
): B =>
fold<E, A, B>(
() => b,
() => b,
() => b,
(a) => f(a, b),
(e, a) => f(a, b),
() => b,
(a) => f(a, b),
(e, a) => f(a, b)
)(fa);
// TODO: After we bump the min bound to >= 2.10, replace this with individual helper fns
// Also, fix the instance factories below to not re-use getMonad for better tree-shaking.
const theseTDatum: Traversable2<URI> & TheseM1<D.URI> = {
URI,
...getTheseM(D.Monad),
traverse: traverseC,
sequence: sequenceC,
reduce: reduceC,
foldMap: foldMapC,
reduceRight: reduceRightC,
};
/**
* @since 3.5.0
*/
export const Functor: Functor2<URI> = {
URI,
map: theseTDatum.map
};
const {
map
} = pipeable(Functor);
/**
* @since 3.5.0
*/
export const Bifunctor: Bifunctor2<URI> = {
URI,
mapLeft: theseTDatum.mapLeft,
bimap: theseTDatum.bimap
}
const {
mapLeft,
bimap
} = pipeable(Bifunctor);
/**
* @since 3.5.0
*/
export const getMonad = <E>(S: Semigroup<E>): Monad2C<URI, E> => ({
...theseTDatum.getMonad(S),
URI
});
/**
* @since 3.5.0
*/
export const getMonadThrow = <E>(S: Semigroup<E>): MonadThrow2C<URI, E> => ({
...theseTDatum.getMonad(S),
URI,
throwError: failure
})
/**
* @since 3.5.0
*/
export const getChain = <E>(S: Semigroup<E>): Chain2C<URI, E> => ({
...theseTDatum.getMonad(S),
URI
});
/**
* @since 3.5.0
*/
export const getApplicative = <E>(S: Semigroup<E>): Applicative2C<URI, E> => ({
...theseTDatum.getMonad(S),
URI
});
/**
* @since 3.5.0
*/
export const getApply = <E>(S: Semigroup<E>): Apply2C<URI, E> => ({
...theseTDatum.getMonad(S),
URI
});
/**
* @since 3.5.0
*/
export const Foldable: Foldable2<URI> = {
URI,
reduce: reduceC,
reduceRight: reduceRightC,
foldMap: foldMapC
};
const {
reduce,
reduceRight,
foldMap
} = pipeable(Foldable);
/**
* @since 3.5.0
*/
export const Traversable: Traversable2<URI> = {
...Functor,
...Foldable,
sequence: sequenceC,
traverse: traverseC
}
/**
* @since 3.5.0
*/
export const getShow = <E, A>(SE: Show<E>, SA: Show<A>): Show<DatumThese<E, A>> =>
D.getShow(theseGetShow(SE, SA));
/**
* @since 3.5.0
*/
export const getEq = <E, A>(EE: Eq<E>, EA: Eq<A>): Eq<DatumThese<E, A>> =>
D.getEq(theseGetEq(EE, EA))
/**
* @since 4.0.0
*/
export const getSemigroup = <E, A>(S: Semigroup<These<E, A>>): Semigroup<DatumThese<E, A>> =>
D.getSemigroup(S)
/**
* @since 4.0.0
*/
export const getMonoid = <E, A>(S: Semigroup<These<E, A>>): Monoid<DatumThese<E, A>> =>
D.getMonoid(S)
/**
* @since 3.5.0
*/
export const getApplySemigroup = <E, A>(S: Semigroup<These<E, A>>): Semigroup<DatumThese<E, A>> =>
D.getApplySemigroup(S)
export {
/**
* @since 3.5.0
*/
bimap,
/**
* @since 3.5.0
*/
map,
/**
* @since 3.5.0
*/
mapLeft,
/**
* @since 3.5.0
*/
reduce,
/**
* @since 3.5.0
*/
foldMap,
/**
* @since 3.5.0
*/
reduceRight,
};
|
clov3r/datum
|
test/Datum.ts
|
import * as assert from 'assert';
import { left, right } from 'fp-ts/es6/Either';
import { eqNumber } from 'fp-ts/es6/Eq';
import { identity } from 'fp-ts/es6/function';
import { monoidString, monoidSum } from 'fp-ts/es6/Monoid';
import { none, some, option } from 'fp-ts/es6/Option';
import { ordString } from 'fp-ts/es6/Ord';
import { pipe } from 'fp-ts/es6/pipeable';
import { Semigroup, semigroupSum } from 'fp-ts/es6/Semigroup';
import { showString } from 'fp-ts/es6/Show';
import * as I from 'fp-ts/es6/Identity';
import { array } from 'fp-ts/es6/Array';
import * as D from '../src/Datum';
const predicate = (n: number): boolean => n > 2;
describe('Datum', () => {
it('URI', () => {
assert.strictEqual(D.URI, '@nll/datum/Datum');
});
it('creates', () => {
assert.deepStrictEqual(D.initial, { _tag: 'Initial' });
assert.deepStrictEqual(D.pending, { _tag: 'Pending' });
assert.deepStrictEqual(D.constInitial(), { _tag: 'Initial' });
assert.deepStrictEqual(D.constPending(), { _tag: 'Pending' });
assert.deepStrictEqual(D.refresh(1), { _tag: 'Refresh', value: 1 });
assert.deepStrictEqual(D.replete(1), { _tag: 'Replete', value: 1 });
});
it('fold', () => {
const onInitial = () => 'initial';
const onPending = () => `pending`;
const onRefresh = (s: string) => `refresh${s.length}`;
const onReplete = (s: string) => `replete${s.length}`;
const fold = D.fold(onInitial, onPending, onRefresh, onReplete);
assert.strictEqual(fold(D.initial), 'initial');
assert.strictEqual(fold(D.pending), 'pending');
assert.strictEqual(fold(D.refresh('abc')), 'refresh3');
assert.strictEqual(fold(D.replete('abc')), 'replete3');
});
it('getOrElse', () => {
assert.strictEqual(
pipe(
D.initial,
D.getOrElse(
() => 0,
() => 1
)
),
0
);
assert.strictEqual(
pipe(
D.pending,
D.getOrElse(
() => 0,
() => 1
)
),
1
);
assert.strictEqual(
pipe(
D.refresh(2),
D.getOrElse(
() => 0,
() => 1
)
),
2
);
assert.strictEqual(
pipe(
D.replete(3),
D.getOrElse(
() => 0,
() => 1
)
),
3
);
});
it('getEq', () => {
const { equals } = D.getEq(eqNumber);
assert.strictEqual(equals(D.initial, D.initial), true);
assert.strictEqual(equals(D.initial, D.pending), false);
assert.strictEqual(equals(D.initial, D.refresh(1)), false);
assert.strictEqual(equals(D.initial, D.replete(1)), false);
assert.strictEqual(equals(D.pending, D.initial), false);
assert.strictEqual(equals(D.pending, D.pending), true);
assert.strictEqual(equals(D.pending, D.refresh(1)), false);
assert.strictEqual(equals(D.pending, D.replete(2)), false);
assert.strictEqual(equals(D.refresh(1), D.initial), false);
assert.strictEqual(equals(D.refresh(1), D.pending), false);
assert.strictEqual(equals(D.refresh(1), D.refresh(1)), true);
assert.strictEqual(equals(D.refresh(1), D.replete(1)), false);
assert.strictEqual(equals(D.replete(1), D.initial), false);
assert.strictEqual(equals(D.replete(1), D.pending), false);
assert.strictEqual(equals(D.replete(1), D.refresh(1)), false);
assert.strictEqual(equals(D.replete(1), D.replete(1)), true);
});
it('map', () => {
const f = (n: number) => n * 2;
assert.deepStrictEqual(D.Functor.map(D.initial, f), D.initial);
assert.deepStrictEqual(D.Functor.map(D.pending, f), D.pending);
assert.deepStrictEqual(D.Functor.map(D.replete(2), f), D.replete(4));
assert.deepStrictEqual(D.Functor.map(D.refresh(2), f), D.refresh(4));
});
it('getOrd', () => {
const { compare } = D.getOrd(ordString);
assert.deepStrictEqual(compare(D.initial, D.initial), 0);
assert.deepStrictEqual(compare(D.initial, D.pending), -1);
assert.deepStrictEqual(compare(D.initial, D.refresh('a')), -1);
assert.deepStrictEqual(compare(D.initial, D.replete('a')), -1);
assert.deepStrictEqual(compare(D.pending, D.initial), 1);
assert.deepStrictEqual(compare(D.pending, D.pending), 0);
assert.deepStrictEqual(compare(D.pending, D.refresh('a')), -1);
assert.deepStrictEqual(compare(D.pending, D.replete('a')), -1);
assert.deepStrictEqual(compare(D.refresh('a'), D.initial), 1);
assert.deepStrictEqual(compare(D.refresh('a'), D.pending), 1);
assert.deepStrictEqual(compare(D.refresh('a'), D.refresh('a')), 0);
assert.deepStrictEqual(compare(D.refresh('a'), D.refresh('b')), -1);
assert.deepStrictEqual(compare(D.refresh('a'), D.replete('a')), -1);
assert.deepStrictEqual(compare(D.replete('a'), D.initial), 1);
assert.deepStrictEqual(compare(D.replete('a'), D.pending), 1);
assert.deepStrictEqual(compare(D.replete('a'), D.refresh('a')), 1);
assert.deepStrictEqual(compare(D.replete('a'), D.replete('a')), 0);
assert.deepStrictEqual(compare(D.replete('a'), D.replete('b')), -1);
});
/**
* 1. Identity: `A.ap(A.of(a => a), fa) = fa`
* 2. Homomorphism: `A.ap(A.of(ab), A.of(a)) = A.of(ab(a))`
* 3. Interchange: `A.ap(fab, A.of(a)) = A.ap(A.of(ab => ab(a)), fab)`
*/
it('ap', () => {
const f = (n: number) => n * 2;
assert.deepStrictEqual(D.Apply.ap(D.initial, D.initial), D.initial);
assert.deepStrictEqual(D.Apply.ap(D.initial, D.pending), D.initial);
assert.deepStrictEqual(D.Apply.ap(D.initial, D.refresh(1)), D.initial);
assert.deepStrictEqual(D.Apply.ap(D.initial, D.replete(1)), D.initial);
assert.deepStrictEqual(D.Apply.ap(D.pending, D.initial), D.pending);
assert.deepStrictEqual(D.Apply.ap(D.pending, D.pending), D.pending);
assert.deepStrictEqual(D.Apply.ap(D.pending, D.refresh(1)), D.pending);
assert.deepStrictEqual(D.Apply.ap(D.pending, D.replete(1)), D.pending);
assert.deepStrictEqual(D.Apply.ap(D.refresh(f), D.initial), D.initial);
assert.deepStrictEqual(D.Apply.ap(D.refresh(f), D.pending), D.pending);
assert.deepStrictEqual(
D.Apply.ap(D.refresh(f), D.refresh(1)),
D.refresh(2)
);
assert.deepStrictEqual(
D.Apply.ap(D.refresh(f), D.replete(1)),
D.replete(2)
);
assert.deepStrictEqual(D.Apply.ap(D.replete(f), D.initial), D.initial);
assert.deepStrictEqual(D.Apply.ap(D.replete(f), D.pending), D.pending);
assert.deepStrictEqual(
D.Apply.ap(D.replete(f), D.refresh(1)),
D.refresh(2)
);
assert.deepStrictEqual(
D.Apply.ap(D.replete(f), D.replete(1)),
D.replete(2)
);
});
it('chain', () => {
const f = (n: number) => D.replete(n * 2);
const g = () => D.initial;
assert.deepStrictEqual(D.Chain.chain(D.initial, f), D.initial);
assert.deepStrictEqual(D.Chain.chain(D.initial, g), D.initial);
assert.deepStrictEqual(D.Chain.chain(D.pending, f), D.pending);
assert.deepStrictEqual(D.Chain.chain(D.pending, g), D.pending);
assert.deepStrictEqual(D.Chain.chain(D.refresh(1), f), D.replete(2));
assert.deepStrictEqual(D.Chain.chain(D.refresh(1), g), D.initial);
assert.deepStrictEqual(D.Chain.chain(D.replete(1), f), D.replete(2));
assert.deepStrictEqual(D.Chain.chain(D.replete(1), g), D.initial);
});
/**
* `Alt` instances are required to satisfy the following laws:
*
* 1. Associativity: `A.alt(A.alt(fa, ga), ha) = A.alt(fa, A.alt(ga, ha))`
* 2. Distributivity: `A.map(A.alt(fa, ga), ab) = A.alt(A.map(fa, ab), A.map(ga, ab))`
*/
it('alt', () => {
const f = (n: number) => n * 2;
const alt = D.Alt.alt;
const map = D.Alt.map;
assert.deepStrictEqual(
alt(
alt(D.initial, () => D.pending),
() => D.pending
),
alt(D.initial, () => alt(D.pending, () => D.pending))
);
assert.deepStrictEqual(
alt(
alt(D.pending, () => D.initial),
() => D.pending
),
alt(D.pending, () => alt(D.initial, () => D.pending))
);
assert.deepStrictEqual(
alt(
alt(D.pending, () => D.refresh(1)),
() => D.pending
),
alt(D.pending, () => alt(D.refresh(1), () => D.pending))
);
assert.deepStrictEqual(
alt(
alt(D.pending, () => D.replete(1)),
() => D.pending
),
alt(D.pending, () => alt(D.replete(1), () => D.pending))
);
assert.deepStrictEqual(
alt(
alt(D.refresh(1), () => D.replete(1)),
() => D.pending
),
alt(D.refresh(1), () => alt(D.replete(1), () => D.pending))
);
assert.deepStrictEqual(
map(
alt(D.initial, () => D.pending),
f
),
alt(map(D.initial, f), () => map(D.pending, f))
);
assert.deepStrictEqual(
map(
alt(D.pending, () => D.initial),
f
),
alt(map(D.pending, f), () => map(D.initial, f))
);
assert.deepStrictEqual(
map(
alt(D.pending, () => D.refresh(1)),
f
),
alt(map(D.pending, f), () => map(D.refresh(1), f))
);
assert.deepStrictEqual(
map(
alt(D.initial, () => D.replete(1)),
f
),
alt(map(D.initial, f), () => map(D.replete(1), f))
);
});
it('extend', () => {
const f = D.getOrElse(
() => 0,
() => 1
);
assert.deepStrictEqual(D.Extend.extend(D.replete(2), f), D.replete(2));
assert.deepStrictEqual(D.Extend.extend(D.initial, f), D.replete(0));
});
it('fromNullable', () => {
assert.deepStrictEqual(D.fromNullable(2), D.replete(2));
assert.deepStrictEqual(D.fromNullable(null), D.initial);
assert.deepStrictEqual(D.fromNullable(undefined), D.initial);
});
// TODO Fix these tests!
it('traverse', () => {
assert.deepStrictEqual(
D.Traversable.traverse(option)(D.initial, () => none),
some(D.initial)
);
assert.deepStrictEqual(
D.Traversable.traverse(option)(D.pending, () => none),
some(D.pending)
);
assert.deepStrictEqual(
D.Traversable.traverse(option)(D.refresh('foo'), a =>
a.length >= 2 ? some(a) : none
),
some(D.refresh('foo'))
);
assert.deepStrictEqual(
D.Traversable.traverse(option)(D.refresh(1), a => (a >= 2 ? some(a) : none)),
none
);
assert.deepStrictEqual(
D.Traversable.traverse(option)(D.refresh(3), a => (a >= 2 ? some(a) : none)),
some(D.refresh(3))
);
assert.deepStrictEqual(
D.Traversable.traverse(option)(D.replete('foo'), a =>
a.length >= 2 ? some(a) : none
),
some(D.replete('foo'))
);
assert.deepStrictEqual(
D.Traversable.traverse(option)(D.replete(1), a => (a >= 2 ? some(a) : none)),
none
);
assert.deepStrictEqual(
D.Traversable.traverse(option)(D.replete(3), a => (a >= 2 ? some(a) : none)),
some(D.replete(3))
);
});
// TODO Fix these tests!
it('sequence', () => {
assert.deepStrictEqual(D.Traversable.sequence(array)(D.initial), [D.initial]);
assert.deepStrictEqual(D.Traversable.sequence(array)(D.pending), [D.pending]);
assert.deepStrictEqual(D.Traversable.sequence(array)(D.refresh([1, 2])), [
D.refresh(1),
D.refresh(2)
]);
assert.deepStrictEqual(D.Traversable.sequence(array)(D.replete([1, 2])), [
D.replete(1),
D.replete(2)
]);
});
it('reduce', () => {
assert.strictEqual(
D.Foldable.reduce(D.initial, 2, (b, a) => b + a),
2
);
assert.strictEqual(
D.Foldable.reduce(D.pending, 2, (b, a) => b + a),
2
);
assert.strictEqual(
D.Foldable.reduce(D.refresh(3), 2, (b, a) => b + a),
5
);
assert.strictEqual(
D.Foldable.reduce(D.replete(3), 2, (b, a) => b + a),
5
);
});
it('foldMap', () => {
const foldMap = D.Foldable.foldMap(monoidString);
assert.strictEqual(foldMap(D.initial, identity), '');
assert.strictEqual(foldMap(D.pending, identity), '');
assert.strictEqual(foldMap(D.refresh('a'), identity), 'a');
assert.strictEqual(foldMap(D.replete('a'), identity), 'a');
});
it('reduceRight', () => {
const reduceRight = D.Foldable.reduceRight;
const concat = (a: string, acc: string) => acc + a;
assert.strictEqual(reduceRight(D.initial, 'init', concat), 'init');
assert.strictEqual(reduceRight(D.pending, 'init', concat), 'init');
assert.strictEqual(reduceRight(D.refresh('a'), 'init', concat), 'inita');
assert.strictEqual(reduceRight(D.replete('a'), 'init', concat), 'inita');
});
function assertSemigroup(S: Semigroup<D.Datum<number>>) {
const triples = [
[D.initial, D.initial, D.initial],
[D.initial, D.pending, D.pending],
[D.initial, D.refresh(1), D.refresh(1)],
[D.initial, D.replete(1), D.replete(1)],
[D.pending, D.pending, D.pending],
[D.pending, D.refresh(1), D.refresh(1)],
[D.pending, D.replete(1), D.refresh(1)],
[D.refresh(1), D.refresh(1), D.refresh(2)],
[D.refresh(1), D.replete(1), D.refresh(2)],
[D.replete(1), D.replete(1), D.replete(2)]
];
triples.forEach(([s1, s2, expected]) => {
assert.deepStrictEqual(S.concat(s1, s2), expected);
assert.deepStrictEqual(S.concat(s2, s1), expected);
});
}
it('getSemigroup', () => {
const S = D.getSemigroup(semigroupSum);
assertSemigroup(S);
});
it('getMonoid', () => {
const M = D.getMonoid(monoidSum);
assertSemigroup(M);
const values = [
D.initial,
D.pending,
D.refresh(1),
D.replete(1)
];
values.forEach(value => {
assert.deepStrictEqual(M.concat(M.empty, value), value)
assert.deepStrictEqual(M.concat(value, M.empty), value)
});
});
it('getApplySemigroup', () => {
const S = D.getApplySemigroup(semigroupSum);
assert.deepStrictEqual(S.concat(D.initial, D.initial), D.initial);
assert.deepStrictEqual(S.concat(D.pending, D.pending), D.pending);
assert.deepStrictEqual(S.concat(D.refresh(1), D.initial), D.initial);
assert.deepStrictEqual(S.concat(D.initial, D.refresh(1)), D.initial);
assert.deepStrictEqual(S.concat(D.refresh(1), D.refresh(2)), D.refresh(3));
assert.deepStrictEqual(S.concat(D.replete(1), D.initial), D.initial);
assert.deepStrictEqual(S.concat(D.initial, D.replete(1)), D.initial);
assert.deepStrictEqual(S.concat(D.replete(1), D.refresh(2)), D.refresh(3));
assert.deepStrictEqual(S.concat(D.refresh(1), D.replete(2)), D.replete(3));
assert.deepStrictEqual(S.concat(D.replete(1), D.replete(2)), D.replete(3));
});
it('elem', () => {
assert.deepStrictEqual(D.elem(eqNumber)(2, D.initial), false);
assert.deepStrictEqual(D.elem(eqNumber)(2, D.pending), false);
assert.deepStrictEqual(D.elem(eqNumber)(2, D.refresh(2)), true);
assert.deepStrictEqual(D.elem(eqNumber)(1, D.refresh(2)), false);
assert.deepStrictEqual(D.elem(eqNumber)(2, D.replete(2)), true);
assert.deepStrictEqual(D.elem(eqNumber)(1, D.replete(2)), false);
});
it('isInitial', () => {
assert.deepStrictEqual(D.isInitial(D.initial), true);
assert.deepStrictEqual(D.isInitial(D.pending), false);
assert.deepStrictEqual(D.isInitial(D.refresh(1)), false);
assert.deepStrictEqual(D.isInitial(D.replete(1)), false);
});
it('isPending', () => {
assert.deepStrictEqual(D.isPending(D.initial), false);
assert.deepStrictEqual(D.isPending(D.pending), true);
assert.deepStrictEqual(D.isPending(D.refresh(1)), false);
assert.deepStrictEqual(D.isPending(D.replete(1)), false);
});
it('isRefresh', () => {
assert.deepStrictEqual(D.isRefresh(D.initial), false);
assert.deepStrictEqual(D.isRefresh(D.pending), false);
assert.deepStrictEqual(D.isRefresh(D.refresh(1)), true);
assert.deepStrictEqual(D.isRefresh(D.replete(1)), false);
});
it('isReplete', () => {
assert.deepStrictEqual(D.isReplete(D.initial), false);
assert.deepStrictEqual(D.isReplete(D.pending), false);
assert.deepStrictEqual(D.isReplete(D.refresh(1)), false);
assert.deepStrictEqual(D.isReplete(D.replete(1)), true);
});
it('isValued', () => {
assert.deepStrictEqual(D.isValued(D.initial), false);
assert.deepStrictEqual(D.isValued(D.pending), false);
assert.deepStrictEqual(D.isValued(D.refresh(1)), true);
assert.deepStrictEqual(D.isValued(D.replete(1)), true);
});
it('exists', () => {
const predicate = (a: number) => a === 2;
assert.deepStrictEqual(pipe(D.initial, D.exists(predicate)), false);
assert.deepStrictEqual(pipe(D.replete(1), D.exists(predicate)), false);
assert.deepStrictEqual(pipe(D.replete(2), D.exists(predicate)), true);
});
it('compact', () => {
assert.deepStrictEqual(D.Compactable.compact(D.initial), D.initial);
assert.deepStrictEqual(D.Compactable.compact(D.pending), D.pending);
assert.deepStrictEqual(D.Compactable.compact(D.refresh(none)), D.initial);
assert.deepStrictEqual(
D.Compactable.compact(D.refresh(some('123'))),
D.refresh('123')
);
assert.deepStrictEqual(D.Compactable.compact(D.replete(none)), D.initial);
assert.deepStrictEqual(
D.Compactable.compact(D.replete(some('123'))),
D.replete('123')
);
});
it('separate', () => {
assert.deepStrictEqual(D.Compactable.separate(D.initial), {
left: D.initial,
right: D.initial
});
assert.deepStrictEqual(D.Compactable.separate(D.pending), {
left: D.initial,
right: D.initial
});
assert.deepStrictEqual(D.Compactable.separate(D.refresh(left('123'))), {
left: D.replete('123'),
right: D.initial
});
assert.deepStrictEqual(D.Compactable.separate(D.replete(right('123'))), {
left: D.initial,
right: D.replete('123')
});
});
it('filter', () => {
const predicate = (a: number) => a === 2;
assert.deepStrictEqual(D.Filterable.filter(D.initial, predicate), D.initial);
assert.deepStrictEqual(D.Filterable.filter(D.refresh(1), predicate), D.initial);
assert.deepStrictEqual(
D.Filterable.filter(D.refresh(2), predicate),
D.refresh(2)
);
assert.deepStrictEqual(D.Filterable.filter(D.replete(1), predicate), D.initial);
assert.deepStrictEqual(
D.Filterable.filter(D.replete(2), predicate),
D.replete(2)
);
});
it('filterMap', () => {
const f = (n: number) => (predicate(n) ? some(n + 1) : none);
assert.deepStrictEqual(D.Filterable.filterMap(D.initial, f), D.initial);
assert.deepStrictEqual(D.Filterable.filterMap(D.replete(1), f), D.initial);
assert.deepStrictEqual(D.Filterable.filterMap(D.replete(3), f), D.replete(4));
});
it('partition', () => {
assert.deepStrictEqual(D.Filterable.partition(D.initial, predicate), {
left: D.initial,
right: D.initial
});
assert.deepStrictEqual(D.Filterable.partition(D.replete(1), predicate), {
left: D.replete(1),
right: D.initial
});
assert.deepStrictEqual(D.Filterable.partition(D.replete(3), predicate), {
left: D.initial,
right: D.replete(3)
});
});
it('partitionMap', () => {
const f = (n: number) => (predicate(n) ? right(n + 1) : left(n - 1));
assert.deepStrictEqual(D.Filterable.partitionMap(D.initial, f), {
left: D.initial,
right: D.initial
});
assert.deepStrictEqual(D.Filterable.partitionMap(D.replete(1), f), {
left: D.replete(0),
right: D.initial
});
assert.deepStrictEqual(D.Filterable.partitionMap(D.replete(3), f), {
left: D.initial,
right: D.replete(4)
});
});
// TODO Fix these tests
it('wither', () => {
const witherIdentity = D.Witherable.wither(I.identity);
const f = (n: number) => I.identity.of(predicate(n) ? some(n + 1) : none);
assert.deepStrictEqual(
witherIdentity(D.initial, f),
I.identity.of(D.initial)
);
assert.deepStrictEqual(
witherIdentity(D.pending, f),
I.identity.of(D.pending)
);
assert.deepStrictEqual(
witherIdentity(D.refresh(1), f),
I.identity.of(D.initial)
);
assert.deepStrictEqual(
witherIdentity(D.refresh(3), f),
I.identity.of(D.refresh(4))
);
assert.deepStrictEqual(
witherIdentity(D.replete(1), f),
I.identity.of(D.initial)
);
assert.deepStrictEqual(
witherIdentity(D.replete(3), f),
I.identity.of(D.replete(4))
);
});
// TODO Fix these tests
it('wilt', () => {
const wiltIdentity = D.Witherable.wilt(I.identity);
const f = (n: number) =>
I.identity.of(predicate(n) ? right(n + 1) : left(n - 1));
assert.deepStrictEqual(
wiltIdentity(D.initial, f),
I.identity.of({ left: D.initial, right: D.initial })
);
assert.deepStrictEqual(
wiltIdentity(D.replete(1), f),
I.identity.of({ left: D.replete(0), right: D.initial })
);
assert.deepStrictEqual(
wiltIdentity(D.replete(3), f),
I.identity.of({ left: D.initial, right: D.replete(4) })
);
});
it('getShow', () => {
const S = D.getShow(showString);
assert.strictEqual(S.show(D.initial), `initial`);
assert.strictEqual(S.show(D.pending), `pending`);
assert.strictEqual(S.show(D.refresh('a')), `refresh("a")`);
assert.strictEqual(S.show(D.replete('a')), `replete("a")`);
});
it('fromEither', () => {
assert.strictEqual(D.fromEither(left('a')), D.initial);
assert.deepStrictEqual(D.fromEither(right(1)), D.replete(1));
});
});
|
javiercbk/vue-vite-typescript-eslint-prettier-tailwind
|
src/store/index.ts
|
<filename>src/store/index.ts<gh_stars>0
import Vuex from 'vuex'
const store = new Vuex.Store({
state: {
count: 0,
},
mutations: {
increment(state) {
state.count++
},
},
actions: {
incrementAction({ commit }) {
commit('increment')
},
},
})
export default store
|
tomsjansons/firestore-schema-validator
|
firebase-admin/index.d.ts
|
<filename>firebase-admin/index.d.ts
import * as firestore from '@google-cloud/firestore'
import EventEmitter from 'events'
export function setFirestore(_firestore: any): void
export function field(label: string): Field<unknown>
export class Field<T> {
/**
* Creates an instance of Field.
*
* @param {String} _label Field's Label.
* @memberof Field
*/
constructor(_label: string)
/**
* Validates Field Data against Field.
*
* @param {*} fieldData Field Data.
* @returns Validated Field Data.
* @memberof Field
*/
validate(fieldData: T): Promise<T>
/**
* Validated Field Data at high level.
*
* @param {*} fieldData Field Data.
* @returns Validated Field Data.
* @memberof Field
*/
validateField(fieldData: T): Promise<T>
/**
* Validates nested Fields of Object Field.
*
* @param {*} fieldData Field Data.
* @returns Validated Field Data.
* @memberof Field
*/
validateObject(fieldData: T): Promise<T>
/**
* Validates nested Fields of Array Field.
*
* @param {*} arrayData Array Data.
* @returns Validated Array Data.
* @memberof Field
*/
validateArray(arrayData: T): Promise<T>
/**
* Adds custom filter to stack.
*
* @param {Function} filter
* @returns {this}
* @memberof Field
*/
custom<TCustom>(filter: (fieldData: any) => T): Field<TCustom>
/**
* Defines default value that will be returned if Field Data is undefined.
*
* @param {*} defaultValue
* @returns {this}
* @memberof Field
*/
default(defaultValue: T): Field<T>
/**
* Allows Field Data to be null.
*
* @returns {this}
* @memberof Field
*/
nullable(): Field<T>
/**
* Makes Field optional.
*
* @returns {this}
* @memberof Field
*/
optional(): Field<T>
/**
* Defines Field as an Array with items defined by nested Field.
*
* @param {Field} field Field.
* @param {*} args
* @returns {this}
* @memberof Field
*/
arrayOf<TSub>(field: Field<TSub>, errorMessage?: string): Field<TSub[]>
/**
* Defines Field as an Object with entries defined by nested Fields.
*
* @param {Object<Field>} fields Object of Fields.
* @param {*} args
* @returns {this}
* @memberof Field
*/
objectOf<T>(fields: { [n in keyof T]: Field<T[n]> }, errorMessage?: string): Field<T>
after(date: Date, errorMessage?: string): Field<Date>
any(errorMessage?: string): Field<any>
array(errorMessage?: string): Field<any[]>
before(date: Date, errorMessage?: string): Field<Date>
boolean(errorMessage?: string): Field<boolean>
date(format: string, errorMessage?: string): Field<Date>
email(errorMessage?: string): Field<string>
equal(compare: T, errorMessage?: string): Field<T>
geopoint(errorMessage?: string): Field<firestore.GeoPoint>
integer(errorMessage?: string): Field<number>
length(length: number, errorMessage?: string): Field<T>
number(errorMessage?: string): Field<number>
match(regEx: RegExp, errorMessage?: string): Field<T>
max(max: T, errorMessage?: string): Field<T>
maxLength(maxLength: number, errorMessage?: string): Field<T>
min(min: T, errorMessage?: string): Field<T>
minLength(minLength: number, errorMessage?: string): Field<T>
object(errorMessage?: string): Field<Object>
oneOf(acceptableValues: T[], errorMessage?: string): Field<T>
range(min: T, max: T, errorMessage?: string): Field<T>
reference(errorMessage?: string): Field<firestore.DocumentReference>
string(errorMessage?: string): Field<string>
timestamp(errorMessage?: string): Field<firestore.Timestamp>
toLowerCase(errorMessage?: string): Field<T>
toUpperCase(errorMessage?: string): Field<T>
trim(errorMessage?: string): Field<T>
_defineType(): void
_add(filter: Function): Field<T>
}
type DataFields = {
[n: string]: any
}
type SchemaFields<T extends DataFields> = {
[n in keyof T]: Field<T[n]>
}
export function schema<T extends DataFields>(fields: SchemaFields<T>): Schema<T>
export class Schema<T extends DataFields> {
/**
* Creates an instance of Schema.
*
* @param {Object<Field>} _fields Object containing Field definitions.
* @memberof Schema
*/
constructor(_fields: SchemaFields<T>)
/**
* Validates Document Data agains Fields.
*
* @param {Object} [data={}]
* @param {Object<Field>} [fields=this._fields]
* @returns Validated Document Data.
* @memberof Schema
*/
validate(data?: T, fields?: T): Promise<T>
/**
* Validates Document Data against selected Fields.
*
* @param {Object} [data={}] Document Data
* @param {Set} [changedKeys=new Set()] Set with Paths of changed Fields.
* @returns Valdiated Document Data.
* @memberof Schema
*/
validateSelected(data?: T, changedKeys?: Set<string>): Promise<T>
}
type DataEvent = 'created' | 'updated' | 'deleted'
type WhereModifier = {
key: string
opStr: firestore.WhereFilterOp
value: any
}
type Hooks<T, M> = {
[n in keyof T]: ((data: any, obj: M) => void)[]
}
type SubscribeCallback<T> = (document: T | undefined) => void
type SubscribeCallbackList<T> = (
documents: T[],
removedDocuments: T[],
addedDocuments: T[],
changedDocuments: T[]
) => void
type Unsubscribe = () => void
export function Model<T extends DataFields, M>() {
abstract class ModelClass {
/**
* Creates an instance of Model.
*
* @param {DocumentSnapshot} _snapshot - Document Snapshot.
* @param {Object} _data - Document Data.
* @returns {Proxy} ModelProxy which handles data setters and getters.
* @memberof Model
*/
constructor(_snapshot: firestore.DocumentSnapshot, _data?: T)
get _data(): T
/**
* ID of Document.
*
* @readonly
* @type {String}
* @memberof Model
*/
get _id(): string
/**
* Date of Document creation in ISO String format.
*
* @readonly
* @type {String}
* @memberof Model
*/
get _createdAt(): string
/**
* Date of Document update in ISO String format.
*
* @readonly
* @type {String}
* @memberof Model
*/
get _updatedAt(): string
/**
* Collection Path.
*
* @readonly
* @type {String}
* @memberof Model
*/
get _collectionPath(): string
/**
* Collection Reference.
*
* @readonly
* @static
* @type {CollectionReference}
* @memberof Model
*/
static get _collectionRef(): firestore.CollectionReference
/**
* Collection Reference.
*
* @readonly
* @type {String}
* @memberof Model
*/
get _collectionRef(): firestore.CollectionReference
/**
* Document Reference.
*
* @readonly
* @type {String}
* @memberof Model
*/
get _docRef(): firestore.DocumentReference
/**
* Instance of EventEmitter used with this.on() and this.emit().
*
* @readonly
* @static
* @type {EventEmitter}
* @memberof Model
*/
static get _events(): EventEmitter.EventEmitter
/**
* Subsribes to event.
*
* @static
* @param {String} event - Event name.
* @param {Function} cb - Callback function.
* @memberof Model
*/
static on(event: DataEvent, cb: (obj: T) => Promise<void>): void
/**
* Emits event.
*
* @param {String} event - Event name.
* @memberof Model
*/
emit(event: DataEvent): void
/**
* Adds hook that will be fired before parsing data
* if this[path] has changed.
*
* @static
* @param {String} path - Path of property.
* @param {Function} cb - Callback function.
* @memberof Model
*/
static prehook(path: keyof T, cb: (data: any, obj: M) => void): void
/**
* Adds hook that will be fired after parsing data
* if this[path] has changed.
*
* @static
* @param {String} path - Path of property.
* @param {Function} cb - Callback function.
* @memberof Model
*/
static posthook(path: keyof T, cb: (data: any, obj: M) => void): void
/**
* Processes subscription callback
*
* @static
* @param {QuerySnapshot} querySnap - Path of property.
* @param {Function} subscriptionCallback - Callback function.
* @memberof ModelClass
*/
static _querySubscriptionCallback(
querySnap: firestore.QuerySnapshot,
subscriptionCallback: SubscribeCallbackList<M>
): void
/**
* Fetches Document by ID.
*
* @static
* @param {String} id
* @returns {this|null} Instance of Model or null.
* @memberof Model
*/
static getById(id: string): Promise<M | null>
/**
* Fetches Document by ID.
*
* @static
* @param {String} id
* @param {Function} subscriptionCallback - Subscription Callback.
* @returns {Function} Unsubscribe.
* @memberof ModelClass
*/
static getByIdSubscribe(id: string, subscriptionCallback: SubscribeCallback<M | null>): Unsubscribe
/**
* Validates where cluyases for use with firestore queries directly, errors on encountered invalid value
*
* @param {WhereModifier[]} whereClauses Where clauses to validate with key, opStr, value
* @returns {WhereModifier[]} Validated where clauses with key, opStr, value
*/
static validateWhereClauses(whereClauses: WhereModifier[]): Promise<WhereModifier[]>
/**
* Fetches Document by key and value pair.
*
* @static
* @param {String} key - Key.
* @param {*} value - Value to compare.
* @returns {this|null} Instance of this or null.
* @memberof Model
*/
static getBy(key: string, value: any): Promise<M | null>
/**
* Fetches Document by key and value pair.
*
* @static
* @param {String} key - Key.
* @param {*} value - Value to compare.
* @param {Function} subscriptionCallback - Subscription Callback.
* @returns {Function} Unsubscribe.
* @memberof Model
*/
static getBySubscribe(key: string, value: any, subscriptionCallback: SubscribeCallbackList<M>): Unsubscribe
/**
* Fetches all Documents by key and value pair.
*
* @static
* @param {String} key
* @param {*} value
* @param {array} optionalModifiers
* @returns {Array<this>} Array of instances of this.
* @memberof Model
*/
static getAllBy(key: string, value: any, optionalModifiers?: WhereModifier[]): Promise<M[]>
/**
* Fetches all Documents by key and value pair.
*
* @static
* @param {String} key
* @param {*} value
* @param {array} optionalModifiers
* @param {Function} subscriptionCallback - Subscription Callback.
* @returns {Function} Unsubscribe.
* @memberof Model
*/
static getAllBySubscribe(
key: string,
value: any,
optionalModifiers: WhereModifier[] | undefined,
subscriptionCallback: SubscribeCallbackList<M>
): Unsubscribe
/**
* Creates new Document.
*
* @static
* @param {Object} [data={}]
* @returns Instance of this.
* @memberof Model
*/
static create(data?: T, id?: string): Promise<M>
/**
* Deletes Document.
*
* @memberof Model
*/
delete(): Promise<void>
/**
* Saves changes made to Document.
*
* @param {*} options
* @returns This.
* @memberof Model
*/
save(options?: firestore.SetOptions): Promise<this>
/**
* Validates Document Data.
*
* @param {*} [data={}]
* @param {boolean} [all=false]
* @returns Validated Data.
* @memberof Model
*/
validate(data?: T, all?: boolean): Promise<T>
/**
* Runs hooks on Document Data.
*
* @param {Object} hooks
* @param {Object} [data={}]
* @returns Updated Document Data.
* @memberof Model
*/
runHooks(hooks: Hooks<true, this>, data?: T): Promise<T>
/**
* Parses Document Data, running hooks and validating it.
*
* @param {*} [data=this._data]
* @param {boolean} [all=false]
* @returns Updated and Validated Document Data.
* @memberof Model
*/
parseData(data?: T, all?: boolean): Promise<T>
/**
* Exposes public data to be shown in API responses.
*
* @returns {Object}
* @memberof Model
*/
toJSON(): any
//[n in T]: T[n];
}
return ModelClass
}
export function asyncForEach(array: any[], callback: (value: any) => Promise<void>): void
|
lettucebowler/stencildoku
|
src/components/sudoku/lettuce-sudoku-move-buttons/lettuce-sudoku-move-buttons.tsx
|
<gh_stars>1-10
import { Component, Event, h, Prop, EventEmitter } from '@stencil/core';
@Component({
tag: 'lettuce-sudoku-move-buttons',
styleUrl: 'lettuce-sudoku-move-buttons.css',
shadow: true,
})
export class LettuceSudokuMoveButtons {
@Prop() order = 3;
@Event() moveEvent: EventEmitter;
render() {
return (
<div class="move-buttons">
{Array.from({length: this.order * this.order + 1}, (_, i) => i + 1).map((num) =>
<lettuce-button
square
text={(num % (this.order * this.order + 1)).toString()}
size-selection="lg"
onClick={() => this.moveEvent.emit({num: num % (this.order * this.order + 1)})}
/>
)}
</div>
);
}
}
|
lettucebowler/stencildoku
|
src/components/lettuce-modal/lettuce-modal.tsx
|
<filename>src/components/lettuce-modal/lettuce-modal.tsx
import { Component, h, Event, EventEmitter, Element } from '@stencil/core';
@Component({
tag: 'lettuce-modal',
styleUrl: 'lettuce-modal.css',
})
export class LettuceModal {
@Element() el: HTMLElement;
async closeModal() {
await (this.el.closest('ion-modal') as
HTMLIonModalElement).dismiss();
}
@Event() generateBoard: EventEmitter<string>
async getNewGame(hints: string) {
this.generateBoard.emit(hints);
await this.closeModal();
}
render() {
return [
<ion-content class="ion-padding">
<ion-text><h3>Select your preferred difficulty</h3></ion-text>
<ion-text><h4>I want to solve a puzzle...</h4></ion-text>
<lettuce-button text="while asleep." type="primary" fluid size-selection="lg" onClick={() => this.getNewGame('easy')} />
<lettuce-spacing-vertical size-selection="xxs" />
<lettuce-button text="before I've had coffee." type="primary" fluid size-selection="lg" onClick={() => this.getNewGame('medium')} />
<lettuce-spacing-vertical size-selection="xxs" />
<lettuce-button text="fully conscious." type="primary" fluid size-selection="lg" onClick={() => this.getNewGame('hard')} />
<lettuce-spacing-vertical size-selection="xxs" />
<lettuce-button text="as a relaxing exercise." type="primary" fluid size-selection="lg" onClick={() => this.getNewGame('very-hard')} />
<lettuce-spacing-vertical size-selection="xxs" />
<lettuce-button text="as a test of my will." type="primary" fluid size-selection="lg" onClick={() => this.getNewGame('insane')} />
<lettuce-spacing-vertical size-selection="xxs" />
<lettuce-button text="that I'll never finish" type="primary" fluid size-selection="lg" onClick={() => this.getNewGame('inhuman')} />
</ion-content>
]
}
}
|
lettucebowler/stencildoku
|
src/components/lettuce-button/lettuce-button.tsx
|
<filename>src/components/lettuce-button/lettuce-button.tsx<gh_stars>1-10
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import {Component, h, Prop} from '@stencil/core';
@Component({
tag: 'lettuce-button',
styleUrl: 'lettuce-button.css',
shadow: true,
})
export class LettuceButton {
@Prop() text: string;
@Prop() type = 'primary';
@Prop() fluid = false;
@Prop() sizeSelection: string | 'sm' | 'md' | 'lg' = 'md';
@Prop() square = false;
@Prop() newGame = false;
render(): void {
return (
<button type="button" class={`btn ${this.square ? 'square' : ''} ${this.newGame ? 'new-game' : ''} ${this.type} ${this.fluid ? 'fluid' : null} txt-${this.sizeSelection}`}>
{this.text}
<slot />
</button>
);
}
}
|
lettucebowler/stencildoku
|
src/components/sudoku/lettuce-sudoku-game/lettuce-sudoku-game.tsx
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { Component, Listen, h, Prop, State, Event, EventEmitter } from '@stencil/core';
import { modalController } from '@ionic/core';
import { getIndex } from '../../../helpers/utils';
import SudokuToolCollection from 'sudokutoolcollection';
@Component({
tag: 'lettuce-sudoku-game',
styleUrl: 'lettuce-sudoku-game.css',
shadow: true,
})
export class LettuceSudokuGame {
@Prop() order = 3;
@State() initialBoard: number[] = Array(this.order * this.order * this.order * this.order).fill(0)
@State() currentBoard: number[] = JSON.parse(JSON.stringify(this.initialBoard));
@State() selectedRow: number = null;
@State() selectedCol: number = null;
@Event() newGameEvent: EventEmitter;
@Event({bubbles: true, composed: true}) moveEvent: EventEmitter;
@Listen('keydown', { target: 'document' })
onKeyDown(event: KeyboardEvent): void {
this.updateBoard(parseInt(event.key), this.selectedRow, this.selectedCol);
}
@Listen('cellSelected')
onCellSelected(event: CustomEvent): void {
event.stopPropagation();
const {row, col} = event.detail;
this.selectedRow = row;
this.selectedCol = col;
}
@Listen('newGameEvent')
async openModal() {
const modal: HTMLIonModalElement =
await modalController.create({
component: 'lettuce-modal',
backdropDismiss: false
});
await modal.present();
}
@Listen('generateBoard', {target: 'document'})
async generateBoard(event: CustomEvent) {
const modal: HTMLIonModalElement =
await modalController.create({
component: 'lettuce-modal',
backdropDismiss: false
});
event.stopPropagation();
if (this.order === 3) {
const hints = event.detail || 17;
const board = SudokuToolCollection().generator.generate(hints);
const boardString = board.split('');
const numArray = [];
boardString.map((c: string) => {
numArray.push(parseInt(c) || 0);
});
this.initialBoard = JSON.parse(JSON.stringify(numArray));
this.currentBoard = JSON.parse(JSON.stringify(numArray));
}
await modal.dismiss();
}
@Listen('moveEvent')
onMoveEvent(event: CustomEvent): void {
event.stopImmediatePropagation();
const { num } = event.detail;
this.updateBoard(num, this.selectedRow, this.selectedCol);
}
componentWillLoad(): void {
this.newGameEvent.emit(30);
}
updateBoard(num: number, row: number, col: number): void {
if (!isNaN(num) && num >= 0 && num <= this.order * this.order) {
const spot = getIndex(row, col, this.order);
const before = this.currentBoard.slice(0, spot);
const after = this.currentBoard.slice(spot + 1);
this.currentBoard = [
...before,
num,
...after
];
}
}
render(): void {
return (
<lettuce-page-content-container>
<div class="sudoku-game">
<div>
<lettuce-spacing-vertical size-selection="xxs" />
<lettuce-sudoku-board
order={this.order}
initial-board={JSON.stringify(this.initialBoard)}
current-board={JSON.stringify(this.currentBoard)}
/>
</div>
<div>
<lettuce-spacing-vertical size-selection="xxs" />
<lettuce-sudoku-move-buttons order={this.order} />
</div>
<div class="bottom-row" style={{ display: 'flex', flexDirection: 'column' }}>
<lettuce-spacing-vertical size-selection="xxs" />
<lettuce-button text="New game" new-game fluid size-selection="lg" onClick={() => this.newGameEvent.emit()} />
<lettuce-spacing-vertical size-selection="xxs" />
</div>
</div>
</lettuce-page-content-container>
);
}
}
|
lettucebowler/stencildoku
|
src/components.d.ts
|
<reponame>lettucebowler/stencildoku<filename>src/components.d.ts
/* eslint-disable */
/* tslint:disable */
/**
* This is an autogenerated file created by the Stencil compiler.
* It contains typing information for all components that exist in this project.
*/
import { HTMLStencilElement, JSXBase } from "@stencil/core/internal";
export namespace Components {
interface AppRoot {
}
interface LettuceButton {
"fluid": boolean;
"newGame": boolean;
"sizeSelection": string | 'sm' | 'md' | 'lg';
"square": boolean;
"text": string;
"type": string;
}
interface LettuceModal {
}
interface LettucePageContentContainer {
}
interface LettuceSpacingVertical {
"sizeSelection": string;
}
interface LettuceSudokuBoard {
"currentBoard": string;
"initialBoard": string;
"order": number;
"selectedCol": number;
"selectedRow": number;
}
interface LettuceSudokuCell {
"col": number;
"number": number;
"numberStatus": string;
"row": number;
"selectionState": string;
"type": string;
}
interface LettuceSudokuGame {
"order": number;
}
interface LettuceSudokuMoveButtons {
"order": number;
}
}
declare global {
interface HTMLAppRootElement extends Components.AppRoot, HTMLStencilElement {
}
var HTMLAppRootElement: {
prototype: HTMLAppRootElement;
new (): HTMLAppRootElement;
};
interface HTMLLettuceButtonElement extends Components.LettuceButton, HTMLStencilElement {
}
var HTMLLettuceButtonElement: {
prototype: HTMLLettuceButtonElement;
new (): HTMLLettuceButtonElement;
};
interface HTMLLettuceModalElement extends Components.LettuceModal, HTMLStencilElement {
}
var HTMLLettuceModalElement: {
prototype: HTMLLettuceModalElement;
new (): HTMLLettuceModalElement;
};
interface HTMLLettucePageContentContainerElement extends Components.LettucePageContentContainer, HTMLStencilElement {
}
var HTMLLettucePageContentContainerElement: {
prototype: HTMLLettucePageContentContainerElement;
new (): HTMLLettucePageContentContainerElement;
};
interface HTMLLettuceSpacingVerticalElement extends Components.LettuceSpacingVertical, HTMLStencilElement {
}
var HTMLLettuceSpacingVerticalElement: {
prototype: HTMLLettuceSpacingVerticalElement;
new (): HTMLLettuceSpacingVerticalElement;
};
interface HTMLLettuceSudokuBoardElement extends Components.LettuceSudokuBoard, HTMLStencilElement {
}
var HTMLLettuceSudokuBoardElement: {
prototype: HTMLLettuceSudokuBoardElement;
new (): HTMLLettuceSudokuBoardElement;
};
interface HTMLLettuceSudokuCellElement extends Components.LettuceSudokuCell, HTMLStencilElement {
}
var HTMLLettuceSudokuCellElement: {
prototype: HTMLLettuceSudokuCellElement;
new (): HTMLLettuceSudokuCellElement;
};
interface HTMLLettuceSudokuGameElement extends Components.LettuceSudokuGame, HTMLStencilElement {
}
var HTMLLettuceSudokuGameElement: {
prototype: HTMLLettuceSudokuGameElement;
new (): HTMLLettuceSudokuGameElement;
};
interface HTMLLettuceSudokuMoveButtonsElement extends Components.LettuceSudokuMoveButtons, HTMLStencilElement {
}
var HTMLLettuceSudokuMoveButtonsElement: {
prototype: HTMLLettuceSudokuMoveButtonsElement;
new (): HTMLLettuceSudokuMoveButtonsElement;
};
interface HTMLElementTagNameMap {
"app-root": HTMLAppRootElement;
"lettuce-button": HTMLLettuceButtonElement;
"lettuce-modal": HTMLLettuceModalElement;
"lettuce-page-content-container": HTMLLettucePageContentContainerElement;
"lettuce-spacing-vertical": HTMLLettuceSpacingVerticalElement;
"lettuce-sudoku-board": HTMLLettuceSudokuBoardElement;
"lettuce-sudoku-cell": HTMLLettuceSudokuCellElement;
"lettuce-sudoku-game": HTMLLettuceSudokuGameElement;
"lettuce-sudoku-move-buttons": HTMLLettuceSudokuMoveButtonsElement;
}
}
declare namespace LocalJSX {
interface AppRoot {
}
interface LettuceButton {
"fluid"?: boolean;
"newGame"?: boolean;
"sizeSelection"?: string | 'sm' | 'md' | 'lg';
"square"?: boolean;
"text"?: string;
"type"?: string;
}
interface LettuceModal {
"onGenerateBoard"?: (event: CustomEvent<string>) => void;
}
interface LettucePageContentContainer {
}
interface LettuceSpacingVertical {
"sizeSelection"?: string;
}
interface LettuceSudokuBoard {
"currentBoard"?: string;
"initialBoard"?: string;
"order"?: number;
"selectedCol"?: number;
"selectedRow"?: number;
}
interface LettuceSudokuCell {
"col"?: number;
"number"?: number;
"numberStatus"?: string;
"onCellSelected"?: (event: CustomEvent<any>) => void;
"row"?: number;
"selectionState"?: string;
"type"?: string;
}
interface LettuceSudokuGame {
"onMoveEvent"?: (event: CustomEvent<any>) => void;
"onNewGameEvent"?: (event: CustomEvent<any>) => void;
"order"?: number;
}
interface LettuceSudokuMoveButtons {
"onMoveEvent"?: (event: CustomEvent<any>) => void;
"order"?: number;
}
interface IntrinsicElements {
"app-root": AppRoot;
"lettuce-button": LettuceButton;
"lettuce-modal": LettuceModal;
"lettuce-page-content-container": LettucePageContentContainer;
"lettuce-spacing-vertical": LettuceSpacingVertical;
"lettuce-sudoku-board": LettuceSudokuBoard;
"lettuce-sudoku-cell": LettuceSudokuCell;
"lettuce-sudoku-game": LettuceSudokuGame;
"lettuce-sudoku-move-buttons": LettuceSudokuMoveButtons;
}
}
export { LocalJSX as JSX };
declare module "@stencil/core" {
export namespace JSX {
interface IntrinsicElements {
"app-root": LocalJSX.AppRoot & JSXBase.HTMLAttributes<HTMLAppRootElement>;
"lettuce-button": LocalJSX.LettuceButton & JSXBase.HTMLAttributes<HTMLLettuceButtonElement>;
"lettuce-modal": LocalJSX.LettuceModal & JSXBase.HTMLAttributes<HTMLLettuceModalElement>;
"lettuce-page-content-container": LocalJSX.LettucePageContentContainer & JSXBase.HTMLAttributes<HTMLLettucePageContentContainerElement>;
"lettuce-spacing-vertical": LocalJSX.LettuceSpacingVertical & JSXBase.HTMLAttributes<HTMLLettuceSpacingVerticalElement>;
"lettuce-sudoku-board": LocalJSX.LettuceSudokuBoard & JSXBase.HTMLAttributes<HTMLLettuceSudokuBoardElement>;
"lettuce-sudoku-cell": LocalJSX.LettuceSudokuCell & JSXBase.HTMLAttributes<HTMLLettuceSudokuCellElement>;
"lettuce-sudoku-game": LocalJSX.LettuceSudokuGame & JSXBase.HTMLAttributes<HTMLLettuceSudokuGameElement>;
"lettuce-sudoku-move-buttons": LocalJSX.LettuceSudokuMoveButtons & JSXBase.HTMLAttributes<HTMLLettuceSudokuMoveButtonsElement>;
}
}
}
|
lettucebowler/stencildoku
|
src/components/sudoku/lettuce-sudoku-board/lettuce-sudoku-board.tsx
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { Component, h, Prop, State, Watch, Listen } from '@stencil/core';
import { boardSuccess, cellLegal, getIndex, isInitialHint } from '../../../helpers/utils';
@Component({
tag: 'lettuce-sudoku-board',
styleUrl: 'lettuce-sudoku-board.css',
shadow: true,
})
export class LettuceSudokuBoard {
@Prop() order = 3;
@Prop() initialBoard: string = JSON.stringify(new Array(this.order * this.order * this.order * this.order).fill(0));
@Prop() currentBoard: string = JSON.stringify(JSON.parse(this.initialBoard));
@State() initialState: number[] = JSON.parse(this.initialBoard);
@State() currentState: number[] = JSON.parse(this.currentBoard);
@Prop({mutable: true}) selectedRow: number;
@Prop({mutable: true}) selectedCol: number;
indexes = {
3: {
0: 0,
1: 1,
2: 2,
3: null,
4: 3,
5: 4,
6: 5,
7: null,
8: 6,
9: 7,
10: 8,
},
2: {
0: 0,
1: 1,
2: null,
3: 2,
4: 3,
}
}
@Listen('cellSelected')
onCellSelected(event: CustomEvent): void {
const { row, col } = event.detail;
this.selectedRow = row;
this.selectedCol = col;
}
@Watch('currentBoard')
onCurrentUpdate(): void {
this.currentState = JSON.parse(this.currentBoard);
}
@Watch('initialBoard')
onInitialUpdate(): void {
this.initialState = JSON.parse(this.initialBoard);
this.currentState = JSON.parse(this.initialBoard);
this.selectedRow = -1;
this.selectedCol = -1;
}
translateRow(index: number): number {
return this.indexes[this.order][Math.floor(index / (this.order * this.order + this.order - 1))];
}
translateCol(index: number): number {
return this.indexes[this.order][index % (this.order * this.order + this.order - 1)];
}
getRow(index: number): number {
return Math.floor(index / (this.order * this.order));
}
getCol(index: number): number {
return index % (this.order * this.order);
}
isSameBlock(row: number, col: number): boolean {
const sameLane = Math.floor(this.selectedRow / this.order) === Math.floor(row / this.order);
const sameTrunk = Math.floor(this.selectedCol / this.order) === Math.floor(col / this.order);
return sameLane && sameTrunk;
}
isSameRow(row: number): boolean {
return this.selectedRow === row;
}
isSameCol(col: number): boolean {
return this.selectedCol === col;
}
isSameCell(row: number, col: number): boolean {
return row === this.selectedRow && col === this.selectedCol;
}
isPeerCell(row: number, col: number): boolean {
return (this.isSameRow(row) || this.isSameCol(col) || this.isSameBlock(row, col)) && !this.isSameCell(row, col);
}
isPeerDigit(row: number, col: number): boolean {
const index = getIndex(row, col, this.order);
const selectedIndex = getIndex(this.selectedRow, this.selectedCol, this.order);
return this.currentState[index] === this.currentState[selectedIndex] && this.currentState[index] !== 0 && !this.isSameCell(row, col);
}
getCellStyling(row: number, col: number): string {
const peerCell = this.isPeerCell(row, col);
const selected = this.isSameCell(row, col);
const peerDigit = this.isPeerDigit(row, col);
const success = boardSuccess(this.currentState, this.order);
const initial = isInitialHint(this.initialState, row, col, this.order);
const valid = cellLegal(this.currentState, row, col, this.order);
const none = this.currentState[getIndex(row, col, this.order)] === 0;
let corner = '';
if (row === 0 && col === 0) {
corner = 'top-left';
} else if (row == 0 && col === this.order * this.order - 1) {
corner = 'top-right';
} else if (row === this.order * this.order - 1 && col === this.order * this.order - 1) {
corner = 'bottom-right';
} else if (row === this.order * this.order -1 && col === 0) {
corner = 'bottom-left';
}
const classString = `${selected ? 'selected' : ''} ${initial ? 'initial' : ''} ${valid ? 'valid' : 'invalid'} ${none ? 'none' : ''} ${success ? 'success' : ''} ${corner}`;
if( this.selectedRow !== null && this.selectedCol !== null && this.selectedRow > -1 && this.selectedRow < this.order * this.order && this.selectedCol > -1 && this.selectedCol < this.order * this.order) {
return `${classString} ${peerCell ? 'peer-cell' : ''} ${peerDigit ? 'peer-digit' : ''}`;
}
return classString;
}
render(): void {
const tmpBoard = JSON.parse(JSON.stringify(this.currentState));
let displayBoard = [];
const numbers = [];
for(let i = 0; i < this.order * this.order * this.order; i++) {
numbers[i] = tmpBoard.splice(0, this.order);
}
for (let i = 0; i < this.order * this.order; i++) {
for (let j = 0; j < this.order - 1; j++) {
displayBoard = displayBoard.concat(numbers[i * this.order + j]);
displayBoard.push(0);
}
displayBoard = displayBoard.concat(numbers[i * this.order + this.order - 1]);
if (i % this.order === (this.order - 1) && i !== (this.order * this.order - 1)) {
for (let j = 0; j < this.order * this.order + (this.order - 1); j++) {
displayBoard.push(0);
}
}
}
displayBoard = displayBoard.reduce((accumulator, value) => accumulator.concat(value), []);
return (
<div class="border">
<div class="content">
<div class={`sudoku-board ${this.order === 3 ? 'three' : 'two'}`}>
{displayBoard.map((num, index) => {
const row = this.translateRow(index);
const col = this.translateCol(index);
const bg = this.getCellStyling(row, col);
return row !== null && col !== null ? (
<lettuce-sudoku-cell
number={num}
row={row}
col={col}
selection-state={bg}
/>
) : <div />;
})
}
</div>
</div>
</div>
);
}
}
|
lettucebowler/stencildoku
|
src/components/sudoku/lettuce-sudoku-cell/lettuce-sudoku-cell.tsx
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { Component, h, Prop, Event, EventEmitter } from '@stencil/core';
@Component({
tag: 'lettuce-sudoku-cell',
styleUrl: 'lettuce-sudoku-cell.css',
shadow: true,
})
export class LettuceSudokuCell {
@Prop() number = 0;
@Prop() row: number;
@Prop() col: number;
@Prop() selectionState = '';
@Prop() numberStatus = 'none';
@Prop() type = '';
@Event() cellSelected: EventEmitter;
emitSelection(): void {
this.cellSelected.emit({row: this.row, col: this.col});
}
render(): void {
return (
<button class={`number ${this.type} ${this.selectionState}`} onClick={() => this.emitSelection()}>
{this.number}
</button>
);
}
}
|
lettucebowler/stencildoku
|
src/components/lettuce-page-content-container/lettuce-page-content-container.tsx
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { Component, h } from '@stencil/core';
@Component({
tag: 'lettuce-page-content-container',
styleUrl: 'lettuce-page-content-container.css',
shadow: true,
})
export class LettucePageContentContainer {
render(): void {
return (
<div class="center">
<div class="column">
<slot></slot>
</div>
</div>
);
}
}
|
lettucebowler/stencildoku
|
src/helpers/utils.ts
|
export function cellLegal(board: number[], row: number, col: number, order: number): boolean {
const index = getIndex(row, col, order);
const num = board[index];
if (num === 0) {
return true;
}
let count = 0;
// Check rows/columns
for (let i = 0; i < order * order; i++) {
if (board[getIndex(i, col, order)] === num) {
count++;
}
if (board[getIndex(row, i, order)] === num) {
count++;
}
}
// Check block
const startRow = Math.floor(row / order) * order;
const startCol = Math.floor(col / order) * order;
for (let i = 0; i < order; i++) {
for (let j = 0; j < order; j++) {
const index = getIndex(startRow + i, startCol + j, order);
if (board[index] === num) {
count++;
}
}
}
return count === 3;
}
export function isInitialHint(board: number[], row: number, col: number, order: number): boolean {
return board[getIndex(row, col, order)] !== 0;
}
export function boardSuccess(board: number[], order: number): boolean {
for (let i = 0; i < order * order; i++) {
for (let j = 0; j < order * order; j++) {
if (!rowGood(board, i, order)) {
return false;
}
if (!colGood(board, j, order)) {
return false;
}
if (i < order && j < order) {
if (!blockGood(board, i, j, order)) {
return false;
}
}
}
}
return true;
}
export function getIndex(row: number, col: number, order: number): number {
return row * (order * order) + col;
}
const rowGood = (board: number[], row: number, order: number): boolean => {
const rowSet = new Set();
for (let i = 0; i < order * order; i++) {
const index = getIndex(row, i, order);
const num = board[index];
if (num !== 0) {
rowSet.add(num);
}
}
return rowSet.size === order * order;
}
const colGood = (board: number[], col: number, order: number): boolean => {
const colSet = new Set();
for (let i = 0; i < order * order; i++) {
const index = getIndex(i, col, order);
const num = board[index];
if (num !== 0) {
colSet.add(num);
}
}
return colSet.size === order * order;
}
const blockGood = (board: number[], lane: number, trunk: number, order: number): boolean => {
const blockSet = new Set();
for (let i = lane * order; i < lane * order + order; i++) {
for (let j = trunk * order; j < trunk * order + order; j++) {
const index = getIndex(i, j, order);
const num = board[index];
if (num !== 0) {
blockSet.add(num);
}
}
}
return blockSet.size === order * order;
}
|
lettucebowler/stencildoku
|
src/components/lettuce-spacing-vertical/lettuce-spacing-vertical.tsx
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { Component, h, Prop } from '@stencil/core';
@Component({
tag: 'lettuce-spacing-vertical',
styleUrl: 'lettuce-spacing-vertical.css',
shadow: true,
})
export class LettuceSpacingVertical {
@Prop() sizeSelection = 'md';
render(): void {
return (
<div class={`vertical-${this.sizeSelection}`} />
);
}
}
|
SudoDotDog/Simple-Redis
|
src/index.ts
|
<filename>src/index.ts
/**
* @author WMXPY
* @namespace Redis
* @description Index
*/
import * as Express from "express";
import * as Redis from "redis";
const app: Express.Express = Express();
const port: number = 8080;
const redis: Redis.RedisClient = Redis.createClient(6379, 'localhost');
app.get('/set', (_: Express.Request, res: Express.Response) => {
redis.set('color', 'red');
res.send('Hello World!');
});
app.get('/get', async (_: Express.Request, res: Express.Response) => {
redis.get('color', (err, color) => {
res.send(color);
});
});
app.listen(port, () => console.log(`Listening on port ${port}!`));
|
th1ag0-Zz/gofinances
|
src/__tests__/components/Forms/input.test.tsx
|
<filename>src/__tests__/components/Forms/input.test.tsx
import React from 'react';
import { render } from '@testing-library/react-native';
import { Input } from '../../../components/Forms/Input';
import { ThemeProvider } from 'styled-components/native';
import theme from '../../../global/styles/theme';
const Providers: React.FC = ({ children }) => (
<ThemeProvider theme={theme}>{children}</ThemeProvider>
);
describe('Input Component', () => {
it('must have specific border color when active', () => {
const { getByTestId } = render(
<Input testID="text-input" active={true} />,
{
wrapper: Providers,
},
);
const input = getByTestId('text-input');
expect(input.props.style[0].borderColor).toEqual(theme.colors.attention);
});
});
|
th1ag0-Zz/gofinances
|
src/__tests__/screens/Register.test.tsx
|
<filename>src/__tests__/screens/Register.test.tsx<gh_stars>0
import React from 'react';
import { render, fireEvent } from '@testing-library/react-native';
import { ThemeProvider } from 'styled-components/native';
import { AuthProvider } from '../../hooks/useAuth';
import { Register } from '../../screens/Register';
import theme from '../../global/styles/theme';
const Providers: React.FC = ({ children }) => (
<ThemeProvider theme={theme}>
{/* <AuthProvider>{children}</AuthProvider> */}
{children}
</ThemeProvider>
);
jest.mock('@react-navigation/native', () => {
return {
useNavigation: jest.fn(),
};
});
describe('Register Screen', () => {
it('should be open category modal', () => {
const { getByTestId } = render(<Register />, { wrapper: Providers });
const modalCategory = getByTestId('modal-category');
expect(modalCategory.props.visible).toBeFalsy();
const categorySelectButton = getByTestId('category-select');
fireEvent.press(categorySelectButton);
expect(modalCategory.props.visible).toBeTruthy();
});
});
|
th1ag0-Zz/gofinances
|
src/__tests__/hooks/auth.test.tsx
|
<reponame>th1ag0-Zz/gofinances
import React from 'react';
import { renderHook, act } from '@testing-library/react-hooks';
import { mocked } from 'ts-jest/utils';
import { startAsync } from 'expo-auth-session';
import fetchMock from 'jest-fetch-mock';
import 'jest-fetch-mock';
import { AuthProvider, useAuth } from '../../hooks/useAuth';
const Providers: React.FC = ({ children }) => (
<AuthProvider>{children}</AuthProvider>
);
jest.mock('expo-auth-session');
fetchMock.enableMocks();
describe('Auth Hook', () => {
it('should be able to signIn with Google account', async () => {
const googleMocked = mocked(startAsync as any);
googleMocked.mockReturnValueOnce({
type: 'success',
params: {
access_token: 'any_token',
},
});
fetchMock.mockResponseOnce(
JSON.stringify({
id: 'any_id',
email: '<EMAIL>',
name: 'Thiago',
photo: 'any_photo.png',
}),
);
const { result } = renderHook(() => useAuth(), {
wrapper: Providers,
});
await act(() => result.current.signInWithGoogle());
expect(result.current.user.email).toBe('<EMAIL>');
});
it('user should not connect cancel authentication with Google', async () => {
const googleMocked = mocked(startAsync as any);
googleMocked.mockReturnValueOnce({
type: 'cancel',
});
const { result } = renderHook(() => useAuth(), {
wrapper: Providers,
});
await act(() => result.current.signInWithGoogle());
expect(result.current.user).not.toHaveProperty('id');
});
it('should be error with Google authentication', async () => {
const { result } = renderHook(() => useAuth(), {
wrapper: Providers,
});
try {
await act(() => result.current.signInWithGoogle());
} catch (error) {
expect(result.current.user).toEqual({});
}
});
});
|
th1ag0-Zz/gofinances
|
src/screens/Resume/index.tsx
|
<reponame>th1ag0-Zz/gofinances
import React, { useState, useEffect, useCallback } from 'react';
import { ActivityIndicator } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { VictoryPie } from 'victory-native';
import { RFValue } from 'react-native-responsive-fontsize';
import { useTheme } from 'styled-components';
import { addMonths, format } from 'date-fns';
import { ptBR } from 'date-fns/locale';
import { HistoryCard } from '../../components/HistoryCard';
import {
Container,
Header,
Title,
Content,
ChartContainer,
MonthSelect,
MonthSelectButton,
MonthSelectIcon,
Month,
LoadContainer,
} from './styles';
import { categories } from '../../utils/categories';
import { useFocusEffect } from '@react-navigation/core';
import { useAuth } from '../../hooks/useAuth';
interface TransactionData {
type: 'positive' | 'negative';
name: string;
amount: string;
category: string;
date: string;
}
interface CategoryData {
key: string;
name: string;
total: number;
totalFormated: string;
color: string;
percent: string;
}
export const Resume: React.FC = () => {
const { colors } = useTheme();
const { user } = useAuth();
const [selectedDate, setSelectedDate] = useState(new Date());
const [isLoading, setIsloading] = useState(false);
const [totalByCategories, setTotalByCategories] = useState<CategoryData[]>(
[],
);
function handleDateChange(action: 'next' | 'prev') {
if (action === 'next') {
const newDate = addMonths(selectedDate, 1);
setSelectedDate(newDate);
} else {
const newDate = addMonths(selectedDate, -1);
setSelectedDate(newDate);
}
}
async function loadData() {
setIsloading(true);
try {
const dataKey = `@gofinances:transactions_user:${user.id}`;
const response = await AsyncStorage.getItem(dataKey);
const responseFormated = response ? JSON.parse(response) : [];
const expensives = responseFormated.filter(
(expensive: TransactionData) =>
expensive.type === 'negative' &&
new Date(expensive.date).getMonth() === selectedDate.getMonth() &&
new Date(expensive.date).getFullYear() === selectedDate.getFullYear(),
);
const expensivesTotal = expensives.reduce(
(acumullator: number, expensive: TransactionData) => {
return acumullator + Number(expensive.amount);
},
0,
);
const totalByCategory: CategoryData[] = [];
categories.forEach(category => {
let categorySum = 0;
expensives.forEach((expensive: TransactionData) => {
if (expensive.category === category.key) {
categorySum += Number(expensive.amount);
}
});
if (categorySum > 0) {
const total = categorySum.toLocaleString('pt-BR', {
style: 'currency',
currency: 'BRL',
});
const percent = `${((categorySum / expensivesTotal) * 100).toFixed(
0,
)}%`;
totalByCategory.push({
key: category.key,
name: category.name,
totalFormated: total,
total: categorySum,
color: category.color,
percent,
});
}
});
setTotalByCategories(totalByCategory);
} catch (error) {
console.log(error);
} finally {
setIsloading(false);
}
}
useEffect(() => {
loadData();
}, [selectedDate]);
useFocusEffect(
useCallback(() => {
loadData();
}, []),
);
return (
<Container>
<Header>
<Title>Resumo por categoria</Title>
</Header>
<Content>
<MonthSelect>
<MonthSelectButton onPress={() => handleDateChange('prev')}>
<MonthSelectIcon name="chevron-left" />
</MonthSelectButton>
<Month>{format(selectedDate, 'MMMM, yyyy', { locale: ptBR })}</Month>
<MonthSelectButton onPress={() => handleDateChange('next')}>
<MonthSelectIcon name="chevron-right" />
</MonthSelectButton>
</MonthSelect>
{isLoading ? (
<LoadContainer>
<ActivityIndicator size="large" color={colors.secondary} />
</LoadContainer>
) : (
<>
<ChartContainer>
<VictoryPie
data={totalByCategories}
colorScale={totalByCategories.map(category => category.color)}
x="percent"
y="total"
style={{
labels: {
fontSize: RFValue(18),
fontWeight: 'bold',
fill: colors.shape,
},
}}
labelRadius={50}
/>
</ChartContainer>
{totalByCategories.map(item => (
<HistoryCard
title={item.name}
key={item.key}
amount={item.totalFormated}
color={item.color}
/>
))}
</>
)}
</Content>
</Container>
);
};
|
th1ag0-Zz/gofinances
|
src/screens/SignIn/index.tsx
|
<gh_stars>0
import React, { useState } from 'react';
import { ActivityIndicator, Alert, Platform } from 'react-native';
import { useTheme } from 'styled-components';
import { RFValue } from 'react-native-responsive-fontsize';
import { useAuth } from '../../hooks/useAuth';
import AppeSvg from '../../assets/apple.svg';
import GoogleSvg from '../../assets/google.svg';
import LogoSvg from '../../assets/logo.svg';
import { SignInSocialButton } from '../../components/SignInSocialButton';
import {
Container,
Header,
TitleWraper,
Title,
SignInTitle,
Footer,
FooterWraper,
} from './styles';
export const SignIn: React.FC = () => {
const { colors } = useTheme();
const [isLoading, setIsLoading] = useState(false);
const { signInWithGoogle, signInWithApple } = useAuth();
async function handleSignInWithGoogle() {
try {
setIsLoading(true);
return await signInWithGoogle();
} catch (error) {
console.log(error);
Alert.alert('Não foi possível conectar a conta Google');
setIsLoading(false);
}
}
async function handleSignInWithApple() {
try {
setIsLoading(true);
return await signInWithApple();
} catch (error) {
console.log(error);
Alert.alert('Não foi possível conectar a conta Apple');
} finally {
setIsLoading(false);
}
}
return (
<Container>
<Header>
<TitleWraper>
<LogoSvg width={RFValue(120)} height={RFValue(68)} />
<Title>{'Controle suas\nfinanças de forma\nmuito simples'}</Title>
</TitleWraper>
<SignInTitle>{'Faça seu login com\numa das contas abaixo'}</SignInTitle>
</Header>
<Footer>
<FooterWraper>
<SignInSocialButton
svg={GoogleSvg}
title="Entrar com Google"
onPress={handleSignInWithGoogle}
/>
{Platform.OS === 'ios' && (
<SignInSocialButton
svg={AppeSvg}
title="Entrar com Apple"
onPress={handleSignInWithApple}
/>
)}
</FooterWraper>
{isLoading && (
<ActivityIndicator
size="large"
color={colors.shape}
style={{ marginTop: 14 }}
/>
)}
</Footer>
</Container>
);
};
|
proc7ts/hatsy
|
src/core/request-processor.ts
|
import type { RequestContext } from './request-context';
import type { RequestHandler, RequestHandlerMethod } from './request-handler';
import type { RequestModification } from './request-modification';
/**
* Generic request processor.
*
* Can be constructed by {@link requestProcessor} function.
*
* @typeParam TMeans - A type of initial request processing means.
*/
export type RequestProcessor<TMeans> =
/**
* @param means - Initial request processing means.
*
* @returns A promise resolved when request processing finishes. Resolves to `true` when request is responded,
* or to `false` otherwise.
*/
(this: void, means: TMeans) => Promise<boolean>;
export namespace RequestProcessor {
/**
* Request processor configuration.
*
* @typeParam TMeans - A type of initial request processing means.
*/
export interface Config<TMeans> {
/**
* Initial request processing handler.
*
* This processor is invoked immediately on request processor call.
*/
readonly handler: RequestHandlerMethod<this, TMeans>;
/**
* Calls the next request processing handler.
*
* This method is called when {@link RequestContext.Agent.next delegating to request handler}. The value returned
* is used as processing result.
*
* @param handler - Request processing handler.
* @param context - Request processing context.
*
* @returns A promise resolved when request processing finishes. Resolves to `true` when request is responded,
* or to `false` otherwise.
*/
next<TExt>(
handler: RequestHandler<TMeans & TExt>,
context: RequestContext<TMeans & TExt>,
): Promise<boolean>;
}
}
/**
* Builds a request processor.
*
* @typeParam TMeans - A type of initial request processing means.
* @param config - Request processor configuration.
*
* @returns New request processor.
*/
export function requestProcessor<TMeans>(
config: RequestProcessor.Config<TMeans>,
): RequestProcessor<TMeans> {
const handler = config.handler.bind(config);
return means => {
const context = { ...means } as RequestContext<TMeans>;
context.next = nextHandlerCaller(config, context) as RequestContext<TMeans>['next'];
return config.next(handler, context);
};
}
/**
* @internal
*/
function nextHandlerCaller<TBase, TMeans extends TBase, TExt>(
config: RequestProcessor.Config<TBase>,
means: TMeans,
): (
handler: RequestHandler<TMeans & TExt>,
modification?: RequestModification<TMeans, TExt>,
) => Promise<boolean> {
return async (
handler: RequestHandler<TMeans & TExt>,
modification?: RequestModification<TMeans, TExt>,
): Promise<boolean> => {
let context: RequestContext<TMeans & TExt>;
if (modification) {
context = { ...means, ...modification } as RequestContext<TMeans & TExt>;
context.next = nextHandlerCaller(config, context as TMeans & TExt);
} else {
context = means as RequestContext<TMeans & TExt>;
}
return config.next(handler, context);
};
}
|
proc7ts/hatsy
|
src/http/http-error.spec.ts
|
import { describe, expect, it } from '@jest/globals';
import { dueLog } from '@proc7ts/logger';
import { HttpError } from './http-error';
describe('HttpError', () => {
describe('message', () => {
it('contains status code without missing message', () => {
expect(new HttpError(404).message).toBe('404');
});
it('contains status code and message', () => {
expect(new HttpError(404, { statusMessage: 'Not Found' }).message).toBe('404 Not Found');
});
it('contains explicit message', () => {
expect(new HttpError(404, { message: 'TEST' }).message).toBe('TEST');
});
});
describe('toLog', () => {
it('does nothing at input stage', () => {
const error = new HttpError(400, { details: 'Test' });
expect(dueLog({ on: 'in', line: [error] }).line).toEqual([error]);
});
it('expands status message at default stage', () => {
expect(dueLog({ line: [new HttpError(404, { statusMessage: 'Not Found' })] }).line).toEqual(['404 Not Found']);
});
it('expands error details at default stage', () => {
expect(dueLog({ line: [new HttpError(400, { details: 'Test' })] }).line).toEqual(['400', 'Test']);
});
it('expands reason at output stage', () => {
const reason = new Error('test');
expect(dueLog({ on: 'out', line: [new HttpError(500, { reason })] }).line).toEqual(['500', reason]);
});
});
});
|
proc7ts/hatsy
|
src/http/http-config.ts
|
<reponame>proc7ts/hatsy<gh_stars>1-10
import type { ErrorMeans, RequestHandler } from '../core';
import type { HttpMeans } from './http.means';
/**
* HTTP processing configuration.
*
* @typeParam TMeans - A type of supported HTTP request processing means.
*/
export interface HttpConfig<TMeans extends HttpMeans = HttpMeans> {
/**
* Default HTTP request handler.
*
* This handler will be called after all other handlers when response is not generated.
*
* When set to `false` the default response won't be generated.
*
* @default `true`, which means a `404 Not Found` error will be raised if there is no response.
*/
readonly defaultHandler?: RequestHandler<TMeans> | boolean | undefined;
/**
* Error processing handler.
*
* This handler will be called once request processing error occurred. Such handler would receive
* a {@link ErrorMeans error processing means} along with {@link HttpMeans HTTP processing ones}.
*
* When set to `false` the request processing errors will be logged, but otherwise ignored.
*
* @default `true`, which means the request processing error page will be rendered by {@link renderHttpError}
* handler.
*/
readonly errorHandler?: RequestHandler<TMeans & ErrorMeans> | boolean | undefined;
/**
* Whether to log HTTP processing error.
*
* Unhandled errors will be logged with `console.error` in any case.
*
* @default `true`, which means an error will be logged with {@link LoggerMeans logger means}, created if necessary.
*/
readonly logError?: boolean | undefined;
}
export namespace HttpConfig {
/**
* HTTP processing configuration for extended requests.
*
* @typeParam TExt - Request processing means extension type.
* @typeParam TMeans - A type of supported HTTP request processing means.
*/
export interface Extended<TExt, TMeans extends HttpMeans = HttpMeans> extends HttpConfig<TMeans & TExt> {
/**
* Creates actual HTTP request handler.
*
* This can be used e.g. to set up additional request processing capabilities, such as {@link Logging}.
*
* @param handler - HTTP request handler.
*
* @returns HTTP request handler to use instead.
*/
handleBy(handler: RequestHandler<TMeans & TExt>): RequestHandler<TMeans>;
}
}
|
proc7ts/hatsy
|
src/core/request-value-transformer.ts
|
<gh_stars>1-10
import type { RequestContext } from './request-context';
/**
* Signature of request value transformer function.
*
* It is used to transform values in context of request processing.
*
* @typeParam TMeans - A type of request processing means.
* @typeParam TFrom - A type of original, non-transformed value.
* @typeParam TTo - A type of transformed value.
*/
export type RequestValueTransformer<TMeans, TFrom, TTo> =
/**
* @param from - Original value to transform.
* @param context - Request processing context to perform transformation in.
*
* @returns Transformed value or promise-like instance resolving to it.
*/
(this: void, from: TFrom, context: RequestContext<TMeans>) => TTo | PromiseLike<TTo>;
|
proc7ts/hatsy
|
src/http/http-listener.impl.ts
|
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { HttpConfig } from './http-config';
import type { HttpMeans } from './http.means';
/**
* @internal
*/
export interface BaseHttpConfig<TMeans extends HttpMeans = HttpMeans> extends HttpConfig<TMeans> {
handleBy?: undefined;
}
/**
* @internal
*/
export type AnyHttpConfig<
TExt,
TRequest extends IncomingMessage = IncomingMessage,
TResponse extends ServerResponse = ServerResponse,
> =
| BaseHttpConfig<HttpMeans<TRequest, TResponse>>
| HttpConfig.Extended<TExt, HttpMeans<TRequest, TResponse>>;
|
proc7ts/hatsy
|
src/http/render/rendering.capability.ts
|
<filename>src/http/render/rendering.capability.ts
import { MIMEType } from '@frontmeans/httongue';
import { RequestCapability, requestExtension, RequestHandler } from '../../core';
import type { HttpMeans } from '../http.means';
import type { RenderMeans } from './render.means';
/**
* @internal
*/
class RenderingCapability extends RequestCapability<HttpMeans, RenderMeans> {
for<TMeans extends HttpMeans>(
handler: RequestHandler<TMeans & RenderMeans>,
): RequestHandler<TMeans> {
return ({
request: { method },
response,
next,
}) => {
const renderBody = (body: string | Buffer, encoding: BufferEncoding = 'utf-8'): void => {
const length = Buffer.isBuffer(body) ? body.byteLength : Buffer.byteLength(body, encoding);
response.setHeader('Content-Length', length);
if (method === 'HEAD') {
response.end();
} else {
response.end(body, encoding);
}
};
return next(handler, requestExtension<TMeans, RenderMeans>({
renderBody,
renderHtml(html: string | Buffer) {
response.setHeader('Content-Type', `${MIMEType.HTML}; charset=utf-8`);
renderBody(html);
},
renderJson(body: any) {
response.setHeader('Content-Type', `${MIMEType.JSON}; charset=utf-8`);
renderBody(JSON.stringify(body));
},
}));
};
}
}
/**
* HTTP response rendering capability.
*
* Provides {@link RenderMeans HTTP response body render means} for handlers.
*/
export const Rendering: RequestCapability<HttpMeans, RenderMeans> = (/*#__PURE__*/ new RenderingCapability());
|
proc7ts/hatsy
|
src/http/util/index.ts
|
export * from './add-response-header';
|
proc7ts/hatsy
|
src/http/middleware.ts
|
import type { IncomingMessage, ServerResponse } from 'node:http';
import { RequestCapability, RequestContext, RequestHandler } from '../core';
import type { HttpMeans } from './http.means';
/**
* HTTP middleware signature.
*
* This is a [Connect]-style middleware.
*
* [Connect]: https://github.com/senchalabs/connect
*
* @typeParam TRequest - Supported HTTP request type.
* @typeParam TResponse - Supported HTTP response type.
*/
export type Middleware<
TRequest extends IncomingMessage = IncomingMessage,
TResponse extends ServerResponse = ServerResponse,
> =
/**
* @param request - HTTP request.
* @param response HTTP response.
* @param next - Next function to delegate request processing to or report error with.
*/
(
this: void,
request: TRequest,
response: TResponse,
next: Middleware.Next,
) => void;
export namespace Middleware {
/**
* A signature of the function the {@link Middleware middleware} may call to delegate request processing
* or report error with.
*/
export type Next =
/**
* @param error - Either an error to report, or nothing to delegate request processing to next handler.
*/
(this: void, error?: any) => void;
}
/**
* Involves the given `middleware` into HTTP request processing.
*
* @typeParam TInput - A type of input HTTP request processing means.
* @param middleware - Middleware to apply.
*
* @returns New request processing capability that processes HTTP requests by the given `middleware`.
*/
export function middleware<TInput extends HttpMeans>(
middleware: Middleware<TInput['request'], TInput['response']>,
): RequestCapability<TInput> {
return RequestCapability.of(
<TMeans extends TInput>(handler: RequestHandler<TMeans>) => async (
{ request, response, next }: RequestContext<TMeans>,
) => new Promise<void>((resolve, reject) => {
const mdNext = (error?: any): void => {
if (error !== undefined) {
reject(error);
} else {
next(handler).then(() => resolve(), reject);
}
};
middleware(request, response, mdNext);
}),
);
}
|
proc7ts/hatsy
|
src/core/request-handler.ts
|
import type { RequestContext } from './request-context';
/**
* Request processing handler signature.
*
* Handler implementations expect a request processing context containing specific processing means.
* E.g. the ones for {@link HttpMeans HTTP request processing}. The handler may either respond using the provided means,
* or delegate to {@link RequestContext.Agent.next next handler}.
*
* The handler may be asynchronous.
*
* @typeParam TMeans - A type of request processing means this handler expects.
*/
export type RequestHandler<TMeans> =
/**
* @param context - Request processing context containing the necessary means.
*
* @returns Either nothing if the handler completed its work synchronously, or a promise-like instance resolved when
* the handler completed its work asynchronously.
*/
(
this: void,
context: RequestContext<TMeans>,
) => PromiseLike<unknown> | void;
/**
* Request processing method signature.
*
* This is a {@link RequestHandler request handler} that requires a `this` object.
*
* @typeParam TThis - A type of `this` object.
* @typeParam TMeans - A type of request processing means this handler expects.
*/
export type RequestHandlerMethod<TThis, TMeans> =
/**
* @param context - Request processing context containing the necessary means.
*
* @returns Either nothing if the handler completed its work synchronously, or a promise-like instance resolved when
* the handler completed its work asynchronously.
*/
(
this: TThis,
context: RequestContext<TMeans>,
) => PromiseLike<unknown> | void;
/**
* Builds a request processing handler that delegates request processing to other handlers.
*
* Iterates over the given handlers in order and delegates the request processing to them. It stops when either
* response is generated, an error thrown, or no handlers left.
*
* @typeParam TMeans - A type of request processing means `handlers` expect.
* @param handlers - Either single handler or iterable of handlers to delegate request processing to.
*
* @returns Request processing handler.
*/
export function requestHandler<TMeans>(
handlers: RequestHandler<TMeans> | Iterable<RequestHandler<TMeans>>,
): RequestHandler<TMeans> {
if (typeof handlers === 'function') {
return handlers;
}
return async (context: RequestContext<TMeans>): Promise<void> => {
for (const handler of handlers) {
if (await context.next(handler)) {
return;
}
}
return;
};
}
|
proc7ts/hatsy
|
src/core/request-context.ts
|
import type { RequestHandler } from './request-handler';
import type { RequestModification } from './request-modification';
/**
* Request processing context.
*
* It is passed to {@link RequestHandler request processing handler}. It the necessary means. The handler can either
* respond by these means, or delegate processing to the {@link RequestContext.Agent.next next handler}.
*
* The context instance is immutable. The request processing means it contains can be {@link RequestModification
* modified} or even extended when delegating request processing to the {@link RequestContext.Agent.next next handler}
* by creating another context based on original one.
*
* @typeParam TMeans - Request processing means of this context.
*/
export type RequestContext<TMeans> = TMeans & RequestContext.Agent<TMeans>;
export namespace RequestContext {
/**
* Request processing agent interface.
*
* It is extended by {@link RequestContext request processing context} in order the {@link RequestHandler handlers}
* to be able to {@link next delegate processing} to other handlers.
*
* @typeParam TMeans - A type of request processing means.
*/
export interface Agent<TMeans> {
/**
* Delegates request processing to the next `handler` and optionally modifies processing means by creating a new
* context with the given `modifications` applied. The rest of the properties remain unchanged.
*
* @param handler - Target handler to delegate request processing to.
* @param modification - Request processing means modification. `this` context will be passed to the next
* `handler` when omitted.
*
* @returns A promise resolved when request processing finishes. Resolves to `true` when request is responded,
* or to `false` otherwise.
*/
next<TExt = object>(
this: void,
handler: RequestHandler<TMeans & TExt>,
modification?: RequestModification<TMeans, TExt>,
): Promise<boolean>;
}
}
|
proc7ts/hatsy
|
src/core/logging/logging.spec.ts
|
import { beforeEach, describe, expect, it, jest } from '@jest/globals';
import { consoleLogger, silentLogger } from '@proc7ts/logger';
import { noop } from '@proc7ts/primitives';
import type { Mock } from 'jest-mock';
import type { RequestContext } from '../request-context';
import type { RequestHandler } from '../request-handler';
import type { RequestProcessor } from '../request-processor';
import { requestProcessor } from '../request-processor';
import type { LoggerMeans } from './logger.means';
import { Logging } from './logging.capability';
import type { RequestLogger } from './request-logger';
describe('Logging', () => {
let handler: Mock<(context: RequestContext<LoggerMeans>) => void>;
beforeEach(() => {
handler = jest.fn();
});
describe('by default', () => {
it('uses `console` as request logger', async () => {
await processor(Logging.for(handler))({});
expect(handler).toHaveBeenCalledWith(expect.objectContaining({ log: consoleLogger }));
});
it('does not override the request logger', async () => {
const log: RequestLogger = silentLogger;
await processor<LoggerMeans>(Logging.for(handler))({ log });
expect(handler).toHaveBeenCalledWith(expect.objectContaining({ log }));
});
});
describe('logBy', () => {
it('overrides request logger', async () => {
const extendedLog = {
fatal: noop,
error: noop,
warn: noop,
info: noop,
debug: noop,
trace: noop,
};
await processor<LoggerMeans>(Logging.logBy<typeof extendedLog>(extendedLog).for(handler))({ log: console });
expect(handler).toHaveBeenCalledWith(expect.objectContaining({ log: extendedLog }));
});
});
function processor<TMeans>(handler: RequestHandler<TMeans>): RequestProcessor<TMeans> {
return requestProcessor({
handler,
async next<TExt>(
handler: RequestHandler<TMeans & TExt>,
context: RequestContext<TMeans & TExt>,
): Promise<boolean> {
await handler(context);
return true;
},
});
}
});
|
proc7ts/hatsy
|
src/http/render/index.ts
|
<filename>src/http/render/index.ts
export * from './render.means';
export * from './render-http-error.handler';
export * from './rendering.capability';
|
proc7ts/hatsy
|
src/http/dispatch/dispatch-by-accepted.handler.spec.ts
|
import { afterAll, beforeAll, beforeEach, describe, expect, it } from '@jest/globals';
import { silentLogger } from '@proc7ts/logger';
import type { RequestContext } from '../../core';
import { Logging } from '../../core';
import { TestHttpServer } from '../../testing';
import type { HttpMeans } from '../http.means';
import { Rendering, RenderMeans } from '../render';
import { addResponseHeader } from '../util';
import { dispatchByAccepted } from './dispatch-by-accepted.handler';
describe('dispatchByAccepted', () => {
let server: TestHttpServer;
beforeAll(async () => {
server = await TestHttpServer.start();
});
afterAll(async () => {
await server.stop();
});
beforeEach(() => {
server.handleBy(
{
handleBy(handler) {
return Logging.logBy(silentLogger).for(handler);
},
},
Rendering
.for(dispatchByAccepted({
['application/json']({ renderJson }: RequestContext<HttpMeans & RenderMeans>): void {
renderJson({ response: 'json' });
},
['text/html']({ renderHtml }: RequestContext<HttpMeans & RenderMeans>): void {
renderHtml('<html lang="en"><body>HTML</body></html>');
},
['*/*']({ response, renderJson }: RequestContext<HttpMeans & RenderMeans>): void {
addResponseHeader(response, 'Vary', 'Accept-Language');
renderJson({ response: 'fallback' });
},
})),
);
});
it('dispatches to accepted MIME', async () => {
const response = await server.get(
'/test',
{
headers: { accept: 'text/html,application/json;q=0.8,*/*;q=0.8' },
},
);
expect(await response.body()).toContain('HTML');
expect(response.headers.vary).toBe('Accept');
});
it('dispatches to preferred MIME', async () => {
const response = await server.get(
'/test',
{
headers: { accept: 'text/html;q=0.8,application/json;q=0.9,*/*;q=0.8' },
},
);
expect(JSON.parse(await response.body())).toEqual({ response: 'json' });
expect(response.headers.vary).toBe('Accept');
});
it('dispatches to fallback', async () => {
const response = await server.get('/test');
expect(JSON.parse(await response.body())).toEqual({ response: 'fallback' });
expect(response.headers.vary).toBe('Accept, Accept-Language');
});
it('sends with 406 (No Acceptable) when no matching handler found', async () => {
const response = await server.get(
'/test',
{
headers: { accept: 'image/jpeg,*/*;q=0' },
},
);
expect(response.statusCode).toBe(406);
expect(response.statusMessage).toBe('Not Acceptable');
});
});
|
proc7ts/hatsy
|
src/http/dispatch/index.ts
|
<reponame>proc7ts/hatsy<gh_stars>1-10
export * from './dispatch-by-accepted.handler';
export * from './dispatch-by-language.handler';
export * from './dispatch-by-method.handler';
|
proc7ts/hatsy
|
src/http/request/http-forwarding.capability.ts
|
import type { HttpForwardTrust } from '@hatsy/http-header-value/headers';
import { HttpAddressRep } from '@hatsy/http-header-value/node';
import { lazyValue } from '@proc7ts/primitives';
import { RequestCapability, RequestHandler, requestUpdate } from '../../core';
import type { HttpMeans } from '../http.means';
/**
* HTTP proxy forwarding capability.
*
* Extracts trusted forwarding information from HTTP request and updates {@link HttpMeans.requestAddresses HTTP request
* addressing info} accordingly.
*
* The proxy forwarding information is not trusted by default.
*/
export interface HttpForwarding extends RequestCapability<HttpMeans> {
/**
* Configures trust policy to proxy forwarding records.
*
* @param trust - New trust policy to HTTP proxy forwarding records.
*
* @returns New HTTP proxy forwarding capability.
*/
with(trust: HttpForwardTrust): HttpForwarding;
}
/**
* @internal
*/
class HttpForwardingCapability extends RequestCapability<HttpMeans> implements HttpForwarding {
constructor(private readonly _trust: HttpForwardTrust) {
super();
}
for<TMeans extends HttpMeans>(
handler: RequestHandler<TMeans & object>,
): RequestHandler<TMeans> {
return ({ request, next }) => {
const addresses = lazyValue(() => HttpAddressRep.by(request, this._trust));
return next(handler, requestUpdate<HttpMeans>({
requestAddresses: {
get url() {
return addresses().url;
},
get ip() {
return addresses().ip;
},
},
}));
};
}
with(trust: HttpForwardTrust): HttpForwarding {
return new HttpForwardingCapability(trust);
}
}
/**
* HTTP proxy forwarding capability.
*
* Can be used directly, or {@link HttpForwarding.with configured} first.
*/
export const HttpForwarding: HttpForwarding = (/*#__PURE__*/ new HttpForwardingCapability({}));
|
proc7ts/hatsy
|
src/index.ts
|
/**
* @packageDocumentation
* @module @hatsy/hatsy
*/
export * from './core';
export * from './http';
|
proc7ts/hatsy
|
src/http/request/http-forwarding.capability.spec.ts
|
<gh_stars>1-10
import { afterAll, beforeAll, describe, expect, it } from '@jest/globals';
import { TestHttpServer } from '../../testing';
import { Rendering } from '../render';
import { HttpForwarding } from './http-forwarding.capability';
describe('HttpForwarding', () => {
let server: TestHttpServer;
beforeAll(async () => {
server = await TestHttpServer.start();
});
afterAll(async () => {
await server.stop();
});
it('replaces addresses trusted forwarding info', async () => {
server.handleBy(
HttpForwarding
.with({ trusted: true })
.and(Rendering)
.for(({ renderJson, requestAddresses: { url: { href }, ip } }) => {
renderJson({ href, ip });
}),
);
const response = await server.get(
'/test/nested?param=value',
{
family: 4,
localAddress: '127.0.0.1',
headers: {
forwarded: 'host=test.com:8443;proto=https',
},
},
);
expect(JSON.parse(await response.body())).toEqual({
ip: '127.0.0.1',
href: 'https://test.com:8443/test/nested?param=value',
});
});
});
|
proc7ts/hatsy
|
src/http/http-error.ts
|
<filename>src/http/http-error.ts<gh_stars>1-10
import type { DueLog, Loggable } from '@proc7ts/logger';
/**
* A error corresponding to the given HTTP status code.
*
* HTTP request processing handlers may raise this error. The {@link renderHttpError error handler} would render
* corresponding error page then.
*
* @see HttpConfig.errorHandler
*/
export class HttpError extends Error implements Loggable {
/**
* HTTP status message.
*/
readonly statusMessage?: string | undefined;
/**
* Error details.
*
* This will be displayed on error page in addition to error code.
*/
readonly details?: string | undefined;
/**
* Arbitrary error reason.
*
* This is another error typically.
*/
readonly reason?: unknown | undefined;
/**
* Constructs HTTP status error.
*
* @param statusCode - HTTP status code.
* @param options - HTTP error options.
*/
constructor(readonly statusCode: number, options: HttpError.Options = {}) {
super(httpErrorMessage(statusCode, options));
this.statusMessage = options.statusMessage;
this.details = options.details;
this.reason = options.reason;
}
/**
* Performs additional message processing before it is logged.
*
* At output or default logging stage replaces this error with error message, details, and reason. Does nothing at
* other logging stages.
*
* @returns Either new loggable value representation, or nothing outside the output logging stage.
*/
toLog({ on = 'out' }: DueLog): unknown[] | void {
if (on !== 'out') {
return;
}
const report: unknown[] = [this.message];
const { details, reason } = this;
if (details) {
report.push(details);
}
if (reason) {
report.push(reason);
}
return report;
}
}
function httpErrorMessage(
statusCode: number,
{
statusMessage,
message = statusMessage ? `${statusCode} ${statusMessage}` : `${statusCode}`,
}: HttpError.Options,
): string {
return message;
}
export namespace HttpError {
/**
* Options for {@link HttpError HTTP error} construction.
*/
export interface Options {
/**
* HTTP status message.
*/
readonly statusMessage?: string | undefined;
/**
* Error message.
*
* @default Constructed by status code and status message.
*/
readonly message?: string | undefined;
/**
* Error details.
*
* This will be displayed on error page in addition to error code.
*/
readonly details?: string | undefined;
/**
* Arbitrary error reason.
*
* This is another error typically.
*/
readonly reason?: unknown | undefined;
}
}
|
proc7ts/hatsy
|
src/core/index.ts
|
<reponame>proc7ts/hatsy<gh_stars>1-10
/**
* @packageDocumentation
* @module @hatsy/hatsy/core
*/
export * from './dispatch-error';
export * from './error.means';
export * from './logging';
export * from './request-body.means';
export * from './request-capability';
export * from './request-context';
export * from './request-handler';
export * from './request-modification';
export * from './request-processor';
export * from './request-value-transformer';
|
proc7ts/hatsy
|
src/http/dispatch/dispatch-by-language.handler.spec.ts
|
<filename>src/http/dispatch/dispatch-by-language.handler.spec.ts
import { afterAll, beforeAll, beforeEach, describe, expect, it } from '@jest/globals';
import { silentLogger } from '@proc7ts/logger';
import { Logging } from '../../core';
import { TestHttpServer } from '../../testing';
import { Rendering } from '../render';
import { dispatchByLanguage } from './dispatch-by-language.handler';
describe('dispatchByLanguage', () => {
let server: TestHttpServer;
beforeAll(async () => {
server = await TestHttpServer.start();
});
afterAll(async () => {
await server.stop();
});
beforeEach(() => {
server.handleBy(
{
handleBy(handler) {
return Logging.logBy(silentLogger).for(handler);
},
},
Rendering
.for(dispatchByLanguage({
en({ renderJson }): void {
renderJson({ lang: 'en' });
},
['en-US']({ renderJson }): void {
renderJson({ lang: 'en-US' });
},
['*']({ renderJson }) {
renderJson({ lang: 'any' });
},
})),
);
});
it('dispatches by accepted language', async () => {
const response = await server.get(
'/test',
{
headers: { 'accept-language': 'en,*' },
},
);
expect(JSON.parse(await response.body())).toEqual({ lang: 'en' });
expect(response.headers.vary).toBe('Accept-Language');
});
it('dispatches by preferred language', async () => {
const response = await server.get(
'/test',
{
headers: { 'accept-language': 'en,en-US;*' },
},
);
expect(JSON.parse(await response.body())).toEqual({ lang: 'en-US' });
expect(response.headers.vary).toBe('Accept-Language');
});
it('dispatches to fallback', async () => {
const response = await server.get('/test');
expect(JSON.parse(await response.body())).toEqual({ lang: 'any' });
expect(response.headers.vary).toBe('Accept-Language');
});
it('sends with 406 (No Acceptable) when no matching handler found', async () => {
const response = await server.get(
'/test',
{
headers: { 'accept-language': 'de,*;q=0' },
},
);
expect(response.statusCode).toBe(406);
expect(response.statusMessage).toBe('Not Acceptable');
});
});
|
proc7ts/hatsy
|
src/impl/index.ts
|
export * from './read-all';
|
proc7ts/hatsy
|
src/http/dispatch/dispatch-by-accepted.handler.ts
|
<reponame>proc7ts/hatsy
import { httpMimeNegotiator } from '@hatsy/http-header-value/headers';
import type { RequestHandler, RequestHandlerMethod } from '../../core';
import { HttpError } from '../http-error';
import type { HttpMeans } from '../http.means';
import { addResponseHeader } from '../util';
/**
* Request processing handlers for accepted MIME types.
*
* @typeParam TMeans - Supported HTTP request processing means.
*/
export interface DispatchMimeTypes<TMeans extends HttpMeans = HttpMeans> {
/**
* Produces HTML.
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
readonly 'text/html'?: RequestHandlerMethod<this, TMeans> | undefined;
/**
* Produces JSON.
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
readonly 'application/json'?: RequestHandlerMethod<this, TMeans> | undefined;
/**
* Produces any content.
*
* This is a fallback handler typically.
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
readonly '*/*'?: RequestHandlerMethod<this, TMeans> | undefined;
/**
* Request processing method with MIME type as its key.
*
* MIME can be a wildcard like `image/*` or `* / *`.
*/
readonly [mimeType: string]: RequestHandlerMethod<this, TMeans> | undefined;
}
/**
* Dispatches request processing by requested MIME type.
*
* Performs [content negotiation] based on [Accept] header. Then calls handler based on negotiation results.
*
* Appends `Vary: Accept` header to the response.
*
* [content negotiation]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation
* [Accept]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept
*
* @param mimeTypes - Request processing handlers for accepted MIME types.
* @param fallback - Fallback request handler to call when negotiation failed. Issues 406 (Not Acceptable) by default.
*
* @returns New HTTP request processing handler.
*/
export function dispatchByAccepted<TMeans extends HttpMeans>(
mimeTypes: DispatchMimeTypes<TMeans>,
fallback: RequestHandler<TMeans> = () => Promise.reject(new HttpError(406)),
): RequestHandler<TMeans> {
const negotiator = httpMimeNegotiator(mimeTypes);
return async ({ request, response, next }) => {
const { accept = '*/*' } = request.headers;
const handler = negotiator(accept);
if (handler) {
addResponseHeader(response, 'Vary', 'Accept');
return next(handler.bind(mimeTypes));
}
return next(fallback);
};
}
|
proc7ts/hatsy
|
src/core/logging/request-logger.ts
|
<gh_stars>1-10
import type { Logger } from '@proc7ts/logger';
/**
* A logger to use during request processing.
*/
export interface RequestLogger extends Logger {
/**
* Logs error.
*
* @param args - Arbitrary arguments to log.
*/
error(...args: unknown[]): void;
/**
* Logs warning.
*
* @param args - Arbitrary arguments to log.
*/
warn(...args: unknown[]): void;
/**
* Logs informational message.
*
* @param args - Arbitrary arguments to log.
*/
info(...args: unknown[]): void;
/**
* Logs debug message.
*
* @param args - Arbitrary arguments to log.
*/
debug(...args: unknown[]): void;
/**
* Logs tracing message.
*
* This may lead to outputting of stack trace.
*
* @param args - Arbitrary arguments to log.
*/
trace(...args: unknown[]): void;
}
|
proc7ts/hatsy
|
src/core/logging/logger.means.ts
|
import type { RequestLogger } from './request-logger';
/**
* Request logger means.
*
* @typeParam TLogger - Request logger type.
*/
export interface LoggerMeans<TLogger extends RequestLogger = RequestLogger> {
/**
* A logger to use during request processing.
*/
readonly log: TLogger;
}
|
proc7ts/hatsy
|
src/http/dispatch/dispatch-by-method.handler.ts
|
import type { RequestHandler, RequestHandlerMethod } from '../../core';
import type { HttpMeans } from '../http.means';
/**
* Request processing handlers for HTTP request methods.
*
* @typeParam TMeans - Supported HTTP request processing means.
*/
export interface DispatchMethods<TMeans extends HttpMeans = HttpMeans> {
/**
* Request processing handler for HTTP DELETE.
*/
readonly delete?: RequestHandlerMethod<this, TMeans> | undefined;
/**
* Request processing handler for HTTP GET.
*
* It is also called for HTTP HEAD requests unless a [head] handler is also defined.
*/
readonly get?: RequestHandlerMethod<this, TMeans> | undefined;
/**
* Request processing handler for HTTP HEAD.
*/
readonly head?: RequestHandlerMethod<this, TMeans> | undefined;
/**
* Request processing handler for HTTP OPTIONS.
*/
readonly options?: RequestHandlerMethod<this, TMeans> | undefined;
/**
* Request processing handler for HTTP PATCH.
*/
readonly patch?: RequestHandlerMethod<this, TMeans> | undefined;
/**
* Request processing handler for HTTP POST.
*/
readonly post?: RequestHandlerMethod<this, TMeans> | undefined;
/**
* Request processing handler for HTTP PUT.
*/
readonly put?: RequestHandlerMethod<this, TMeans> | undefined;
/**
* Request handler method with lower-case HTTP method name as its key.
*/
readonly [method: string]: RequestHandlerMethod<this, TMeans> | undefined;
}
/**
* Dispatches request processing by HTTP request method.
*
* @typeParam TMeans - Supported HTTP route processing means.
* @param methods - A map of request processing handlers corresponding to HTTP request methods.
*
* @returns New HTTP request processing handler.
*/
export function dispatchByMethod<TMeans extends HttpMeans>(
methods: DispatchMethods<TMeans>,
): RequestHandler<TMeans> {
return async ({ request: { method }, next }) => {
const verb = method ? method.toLocaleLowerCase() : 'get';
const handler = methods[verb] || (verb === 'head' && methods.get);
if (handler) {
await next(handler.bind(methods));
}
};
}
|
proc7ts/hatsy
|
src/core/logging/logging.capability.ts
|
import { consoleLogger } from '@proc7ts/logger';
import { RequestCapability } from '../request-capability';
import type { RequestHandler } from '../request-handler';
import { requestExtension } from '../request-modification';
import type { LoggerMeans } from './logger.means';
import type { RequestLogger } from './request-logger';
/**
* Request logging capability.
*
* Provides {@link LoggerMeans request logger means} for handlers.
*
* @typeParam TInput - A type of request processing means required in order to apply this capability.
* @typeParam TLogger - Request logger type.
*/
export interface Logging<TInput = unknown, TLogger extends RequestLogger = RequestLogger>
extends RequestCapability<TInput, LoggerMeans<TLogger>> {
/**
* Configures a logging capability with the given logger.
*
* @typeParam TNewLogger - Request logger type.
* @param log - A logger to use for request processing.
*
* @returns New request logging capability.
*/
logBy<TNewLogger extends RequestLogger>(log: TNewLogger): Logging<TInput, TNewLogger>;
}
/**
* @internal
*/
class LoggingCapability<TInput, TLogger extends RequestLogger>
extends RequestCapability<TInput, LoggerMeans<TLogger>>
implements Logging<TInput, TLogger> {
readonly for: <TMeans extends TInput>(
handler: RequestHandler<TMeans & LoggerMeans<TLogger>>,
) => RequestHandler<TMeans>;
constructor(log: TLogger, byDefault = false) {
super();
if (byDefault) {
this.for = <TMeans extends TInput>(
handler: RequestHandler<TMeans & LoggerMeans<TLogger>>,
): RequestHandler<TMeans> => context => {
if ((context as Partial<LoggerMeans>).log) {
return context.next(handler);
}
return context.next(handler, requestExtension({ log }));
};
} else {
this.for = <TMeans extends TInput>(
handler: RequestHandler<TMeans & LoggerMeans<TLogger>>,
): RequestHandler<TMeans> => context => context.next(handler, requestExtension({ log }));
}
}
logBy<TNewLogger extends RequestLogger>(
log: TNewLogger,
): Logging<TInput, TNewLogger> {
return new LoggingCapability(log);
}
}
/**
* Request logging capability instance.
*
* Uses a global `console` as {@link LoggerMeans.log request logger}, unless the logger is present in request context
* already.
*/
export const Logging: Logging = (/*#__PURE__*/ new LoggingCapability<unknown, RequestLogger>(consoleLogger, true));
|
proc7ts/hatsy
|
src/core/error.means.ts
|
<reponame>proc7ts/hatsy<filename>src/core/error.means.ts
/**
* Error processing means.
*
* A context with these means is created once error is thrown by one of the handlers right before passing it to error
* handler.
*
* @typeParam TError - Error type.
*/
export interface ErrorMeans<TError = any> {
/**
* Error thrown.
*/
readonly error: TError;
}
|
proc7ts/hatsy
|
src/testing/index.ts
|
<gh_stars>1-10
export * from './test-http-server';
|
proc7ts/hatsy
|
src/http/util/add-response-header.ts
|
import { arrayOfElements, elementOrArray } from '@proc7ts/primitives';
import type { ServerResponse } from 'node:http';
/**
* Appends HTTP header value to server response.
*
* Avoids value duplication.
*
* @param response - HTTP response to add header to.
* @param name - Target HTTP header name.
* @param value - HTTP header value to add.
*/
export function addResponseHeader(response: ServerResponse, name: string, value: string): void {
const oldValues = arrayOfElements(response.getHeader(name)).map(String);
const newValues = elementOrArray(new Set<string>(oldValues).add(value))!;
response.setHeader(name, newValues);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.