class UnrepeatedRandomInteger {
constructor(min, max) {
this.min = min;
this.max = max;
this.range = [];
this.defaultRange = [];
const makeRange = () => {
const range = [];
for(let i = this.min; i <= this.max; i++) {
range.push(i);
}
this.range = range;
this.defaultRange = range;
};
makeRange();
}
random() {
const index = Math.floor( Math.random() * this.range.length );
const victim = this.range[index];
const newRange = this.range.filter(item => item !== victim);
this.range = newRange;
return victim;
}
restore() {
this.range = this.defaultRange;
}
emptify() {
this.defaultRange.forEach(item => {
console.log('i am dying slowly...', this.range);
console.log('i am gonna be dropped now and never after! ', this.random());
console.log('\n\n');
});
}
}
const input = document.querySelector('input');
const pattern = /^\d+(\.?)\d*$/g;
const allowedCodes = [8, 9, 27, 35, 36, 37, 38, 39, 46, 110, 188];
input.addEventListener('input', onInput);
function onInput(e) {
const value = this.value;
if( !(value.match(pattern) || allowedCodes.some(code => code === e.keyCode)) ) {
this.value = value.slice(0, -1);
}
}
function isNum(pretendent) {
return typeof pretendent === "number" && !Number.isNaN(pretendent);
}
function validate(list) {
if( list.every( (item) => isNum(item) ) ) {
return true;
}
console.log('All provided arguments should be numbers!');
return false;
}
const operations = {
addTwo: (a, b) => a + b,
substractTwo: (a, b) => a - b,
divideTwo: (a, b) => a / b,
multiplyTwo: (a, b) => a * b
};
function take(fNum) {
if ( !isNum(fNum) ) {
console.log('You are supposed to provide number!');
return;
}
return {
add: (...args) => validate(args) && args.reduce(operations.addTwo, fNum),
substract: (...args) => validate(args) && args.reduce(operations.substractTwo, fNum),
divide: (...args) => validate(args) && args.reduce(operations.divideTwo, fNum),
multiply: (...args) => validate(args) && args.reduce(operations.multiplyTwo, fNum)
};
}
// validation patterns
const fname = /^[a-z ]{5,}$/i;
const sname = /^[a-z ]{5,}$/i;
const email = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$/;
const phone = /^\+7[0-9]{10}$/;
const patterns = {
name: fname,
surname: sname,
email,
phone,
mobilePhone: phone,
workPhone: phone
};
// forms
const forms = [
{ name: 'Ivan Ivanov', email: 'ivan@test.co', phone: '+79212753690' },
{ name: 'III', email: 'ivan@test', phone: '11111' },
{ name: 'Ivan Ivanov', email: 'ivan@test.co', phone: '+79212753690', mobilePhone: '+79212753690'},
{},
{ name: 'Ivan Ivanov', email: 'ivan@test.co', phone: '+79212753690', mobilePhone: 'фывыафывафыв'},
{ name: 'Ivan Ivanov', email: 'ivan@test.co', phone: '+79212753690', mobilePhone: '+79212753690', workPhone: 'asfdadsfd', surname: ''},
{ surname: 'Ivan Ivanov', mobilePhone: 'фывафыва', name: 'Ivan Ivanov', email: 'ivan@test.co', phone: '+79212753690', workPhone: '+79212753690'
}
];
validateAll(forms, patterns);
function validateAll(forms, patterns) {
return forms.map( form => validate(form, patterns) );
}
function validate(form, patterns) {
const keys = Object.keys(form);
const errors = [];
if(!keys.length) return {target: {}, errors: ['empty form is provided']};
keys.forEach(key => {
if( !patterns[key].test(form[key]) ) {
errors.push(`${key} value is invalid`);
}
});
return {
target: JSON.stringify(form),
errors
};
}
.createClass()
уже или скоро deprecatedconst trunk = {
listItem1: 1,
listItem2: {
subListItem: 1,
subListItem2: {
subsubListItem1: 1,
subsubListItem2: 2
}
},
listItem3: 3
};
const ones = [];
traverse(trunk, 'root');
function traverse(obj, path) {
for(let key in obj) {
const newPath = path + ' > ' + key;
if (obj[key].constructor.name === "Object") {
// console.log(newPath);
return traverse(obj[key], newPath);
}
if(obj[key] == "1") {
ones.push(newPath);
}
}
console.log('properties\' pathes which value is equal to 1 \n\n' , ones);
}
arr1.fill().forEach((el, idx) => {
console.log(idx, el);
});
function forEach(arr, fn) {
var i, len = arr.length;
for(i = 0; i < len; i++) {
fn(arr[i], i, arr);
}
}
function map(arr, fn) {
var i, len = arr.length, result = [];
for(i = 0; i < len; i++) {
result.push(fn(arr[i], i, arr));
}
return result;
}
const combine = (names, lastNames) =>
names.map(name =>
lastNames.map(lastName => name + ' ' + lastName)
);
combine(['John', 'Kenny', 'Mark'], ['Jackson', 'Duglas', 'Kirk']);
// types
const types = {
UPDATE_FIELD: 'UPDATE_FIELD',
};
//types
// operations
const updateField = (value, error) => (
{ type: types.UPDATE_FIELD, value, error }
);
// reducer
const initialState = {
values: {email: '', password: ''},
errors: { email: '', password: '' }
};
function someFormReducer(state = initialState, action) {
switch(action.type) {
case types.UPDATE_FIELD: {
return {
values: { ...state.values, ...action.value },
errors: { ...state.errors, ...action.error };
}
}
return state;
}
// reducer
// так примерно выглядит global store
{
...
...
form: {
login: {
values: {
email: '',
password: '',
},
errors: {
email: '',
password: ''
}
},
}
}
// так примерно выглядит global store
import React from 'react';
import { validateEmail, validatePassword } from 'someValidateLibrary';
import { connect } from 'react-redux';
import { browserHistory } from 'react-router';
import { updateField } from 'path to operations file (action creators)'
class SomeForm extends React.Component {
handleValueChange = (e) => {
const field = e.target.name;
let error = '';
if(field === 'email' && !validateEmail(field)) {
error = "You email is so bad, seriously!";
}
else if (!validationPassword(field) ) {
error = "Your password is sucks!"
}
this.props.dispatch(
updateField(
{ field: e.target.value.trim() },
{ field: error.trim() }
)
);
}
proccessForm = () => {
const { errors } = this.props;
// если ошибок больше нет, то переход на другой роут
if(!errors.email && !errors.password) {
browserHistory.push('/home');
} else {
// your code here
}
}
render() {
const { values, errros } = this.props;
return (
// some ui
<form onSubmit={this.proccessForm}>
<p class="form-field">
<input
type="email"
name="email"
onChange={this.handleValueChange}
value={values.email}
/>
<span>{errors.email}</span>
</p>
<p class="form-field">
<input
type="text"
name="password"
onChange={this.handleValueChange}
value={values.password}
/>
<span>{errors.password}</span>
</p>
<button
type="submit"
disabled={!values.email && !values.password}>
submit
</button>
</form>
);
}
}
const mapStateToProps = ({ form: { login } }) => (
{ values: login.values, errors: login.errors }
);
connect(mapDispatchToProps)(SomeForm);