Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function solve(input) {
- let text = input.shift();
- const isValidIndex = (index) => {
- return index >= 0 && index < text.length;
- };
- const replace = (currentChar, newChar) => {
- while (text.search(currentChar) !== -1) {
- text = text.replace(currentChar, newChar)
- }
- return text;
- }
- const cut = (startIndex, endIndex) => {
- startIndex = Number(startIndex);
- endIndex = Number(endIndex);
- if (isValidIndex(startIndex) && isValidIndex(endIndex)) {
- text = text.substring(0, startIndex) + text.substring(endIndex + 1);
- return text;
- } else {
- return 'Invalid indexes!';
- }
- }
- const make = (type) => {
- type === 'Upper'
- ? text = text.toUpperCase()
- : text = text.toLowerCase();
- return text;
- }
- const check = (string) => {
- return text.search(string) !== -1
- ? `Message contains ${string}`
- : `Message doesn't contain ${string}`;
- }
- const sum = (startIndex, endIndex) => {
- startIndex = Number(startIndex);
- endIndex = Number(endIndex);
- if (isValidIndex(startIndex) && isValidIndex(endIndex)) {
- return [...text.substring(startIndex, endIndex + 1)]
- .reduce((acc, current) => {
- return acc + current.charCodeAt(0);
- }, 0)
- } else {
- return 'Invalid indexes!';
- }
- }
- const cmdParser = {
- replace,
- make,
- cut,
- check,
- sum
- };
- input
- .forEach(line => {
- if (line !== 'Finish') {
- const tokens = line.split(' ');
- const cmd = tokens.shift().toLowerCase();
- console.log(
- cmdParser[cmd](...tokens)
- );
- }
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement