const digits = {Z:2000, M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1};
function roman2arabic(str){
if (!/^[IVXLCDMZ]+$/i.test(str)) throw new Error('Incorrect roman number format: ' + str)
return str.toUpperCase().split('').reduce(function(r,v,i,arr){
const [ a, b, c ] = [ digits[arr[i]], digits[arr[i+1]], digits[arr[i+2]]];
if (b && c && a <= b && b < c)
throw new Error('Incorrect roman number format: ' + str);
return b > a ? r - a : r + a;
}, 0)
}
function arabic2roman(num){
if (!/^\-?\d+$/.test(num+'')) throw new Error('Can`t convert that arabic numeric to roman: ' + num)
if (num < 1) return '';
let result = '';
for (let key in digits)
while ( num >= digits[key] ) {
result += key;
num -= digits[key];
}
return result;
}
function calculator(string){
let badChars = [];
string = string.replace(/[^IVXLCDMZ\d+\-*\/]/gi, chr => {
if (chr !== ' ') badChars.push(chr);
return '';
});
if (badChars.length > 0)
throw Error('Символы не допустимы: ' + badChars.join(' '));
let isRoman = /^[IVXLCDMZ]+$/i,
vars = string.split(/[+\-*\/]/g),
action = string.match(/[+\-*\/]/)[0];
if (vars.length !== 2)
throw Error("Должно быть лишь два операнда");
let r = vars.reduce((s,v)=> s + isRoman.test(v),0);
if (r === 1)
throw Error("Оба числа должны быть либо римскими, либо арабскими, исправьте выражение: " + string);
else if (r === 2)
vars = vars.map(v=>roman2arabic(v));
else if (vars.reduce((s,v) => s + /^\d+$/.test(v)) < 2)
throw Error("Приведенные операнды не допустимы, проверьте выражение: " + string);
if (vars.some(v => v < 1 || v > 10))
throw Error("Допустимо значение операндов лишь от 1 до 10 включительно")
let result = Math.floor(eval(vars.join(action)))
return r === 0 ? result.toString() : arabic2roman(result)
}
module.exports = calculator;
function* routes(coords, limit){
coords = coords.sort( (a,b) => a - b );
for (let i = 1; i < coords.length; i++)
if (coords[i] - coords[i-1] > limit){
yield coords.splice(0, i);
i = 1;
}
if (coords.length > 0) yield coords;
}
let arr = [1 , 3 , 10 , 11 , 18 , 5], x = 2;
for (let route of routes(arr,x))
console.log(`Path found: ${route.join(', ')}`)
function* genz( n ){
for ( let i = n-1; i > 1; i--){
let a = n - i;
if (a < i) yield [i,a]
for (let d of [...genz(a)])
if (!d.some(value => value >= a || value >= i)) yield [i, ...d]
}
}
//pretty print
console.log([...genz(13)].map(v=>v.join(' + ')).join('\r\n'), '\r\n');
export type Some = {
p1?: string,
p2?: string
}
function isEmpty(o: Object): boolean{
return Object.keys(o).length === 0
}
let a: Some = {},
b: Some = {p1: "Value"}
console.log(`Object <a>${ isEmpty(a) ? '' : ' not ' } empty`);
// Object <a> empty
console.log(`Object <b>${ isEmpty(b) ? '' : ' not ' } empty`);
// Object <b> not empty
date.match(/\d+/g).map(Number) // Array(2017, 5, 16, 13, 45)
let regexpr = /(\d{4})-(\d{2})-(\d{2})\s(\d\d):(\d\d)/
Optional chaining not valid on the left-hand side of an assignment
let object = {}; object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment
function Juice(kind, price){
let kind = kind; // это будет приватным свойством
this.price = price; // публичное свойство
this.kind = () => kind; //это публичный метод
this.hello = function(){
console.log(`Thats ${kind} juice`)
}
}
Juice.prototype.world = function(){
//приватное свойство kind тут не доступно, потому обратимся к публичному методу
console.log(`Juice kind: ${this.kind()}`)
}
// шаблон "фабрика"
Juice.apple = ( price ) => new Juice('apple', price);
Juice.orange = ( price ) => new Juice('orange', price);
let littleAppleJuice = Juice.apple(100),
hugeBananaJuice = new Juice('banana', 500);
littleAppleJuice.hello();
littleBananaJuice.world();
using System;
public class FibonacciNumber{
private byte index;
private decimal number;
public FibonacciNumber(int i){
if (i <= 0)
i = 0;
this.index = (byte) i;
this.number = i > 0 ? Fibonacci.getNumber(i) : 0;
}
public FibonacciNumber next(){
return new FibonacciNumber(index+1);
}
public FibonacciNumber prev(){
return new FibonacciNumber(index - 1);
}
public int Index {
get {
return (int) index;
}
}
public decimal Number{
get {
return number;
}
}
}
public class Fibonacci
{
private static double A = Math.Pow(5, 0.5);
private static double B = (A + 1) / 2;
private static double LNb = Math.Log(B);
public static int getIndex(decimal number){
return (int) Math.Round(Math.Log((double)((decimal) Fibonacci.A * number)) / Fibonacci.LNb);
}
public static decimal getNumber(int n){
return (decimal) Math.Round( Math.Pow(Fibonacci.B, n) / Fibonacci.A );
}
public static FibonacciNumber find(decimal number){
return new FibonacciNumber(Fibonacci.getIndex(number));
}
}
public class Program
{
public static void Main()
{
FibonacciNumber fib = Fibonacci.find(100000);
Console.WriteLine(fib.Index);
Console.WriteLine(fib.Number);
Console.WriteLine(fib.next().Number);
}
}
changeAlert: function() {
console.log(789);
return new Promise((resolve, reject)=>{
let timerId = setTimeout(() => {
if (this.alertArr.length > 0) {
this.alertCurrent = this.alertArr[0];
console.log(this.alertCurrent);
} else {
this.alertCurrent = null;
}
this.alertArr.splice(0, 1);
resolve()
if (false) reject("error description");
}, 5000);
})
}