Extracting middle of string - JavaScript - javascript

I am trying to write an algorithm for this in JavaScript but I am getting a str.length is not a function...
function extractMiddle(str) {
var position;
var length;
if(str.length() % 2 == 1) {
position = str.length() / 2;
length = 1;
} else {
position = str.length() / 2 - 1;
length = 2;
}
result = str.substring(position, position + length)
}
extractMiddle("handbananna");

Because string length is not a function, it's a property.
function extractMiddle(str) {
var position;
var length;
if(str.length % 2 == 1) {
position = str.length / 2;
length = 1;
} else {
position = str.length / 2 - 1;
length = 2;
}
return str.substring(position, position + length)
}
console.log(extractMiddle("handbananna"));

Here is an another way to do this:
function extractMiddle(str) {
return str.substr(Math.ceil(str.length / 2 - 1), str.length % 2 === 0 ? 2 : 1);
}

// the most amazing
const getMiddle = s => s.substr(s.length - 1 >>> 1, (~s.length & 1) + 1);
// should return "dd"
console.log(getMiddle('middle'))
// >>> is an unsigned right shift bitwise operator. It's equivalent to division by 2, with truncation, as long as the length of the string does not exceed the size of an integer in Javascript.
// About the ~ operator, let's rather start with the expression n & 1. This will tell you whether an integer n is odd (it's similar to a logical and, but comparing all of the bits of two numbers). The expression returns 1 if an integer is odd. It returns 0 if an integer is even.
// If n & 1 is even, the expression returns 0.
// If n & 1 is odd, the expression returns 1.
// ~n & 1 inverts those two results, providing 0 if the length of the string is odd, and 1 if the length of the sting is even. The ~ operator inverts all of the bits in an integer, so 0 would become -1, 1 would become -2, and so on (the leading bit is always the sign).
// Then you add one, and you get 0+1 (1) characters if the length of the string is odd, or 1+1 (2) characters if the length of the string is even.
#author by jacobb
the link of the source is: https://codepen.io/jacobwarduk/pen/yJpAmK

That seemed to fix it!
function extractMiddle(str) {
var position;
var length;
if(str.length % 2 == 1) {
position = str.length / 2;
length = 1;
} else {
position = str.length / 2 - 1;
length = 2;
}
result = str.substring(position, position + length)
console.log(result);
}
https://jsfiddle.net/sd4z711y/

The first 'if' statement is to get the odd number while the 'else if' is to get the even number.
function getMiddle(s)
{
if (s.length % 2 == 1) {
return s.substring((s.length / 2)+1, (s.length / 2))
} else if (s.length % 2 == 0) {
return s.substring((s.length / 2)-1, (s.length / 2)+1)
}
}
console.log(getMiddle("handers"));
console.log(getMiddle("test"));

Here is my solution :-
function pri(word) {
if (!word) return 'word should have atleast one character';
let w = [...word].reduce((acc, val) => (val == ' ' ? acc : (acc += val)));
let res = '';
let length = word.length;
let avg = length / 2;
let temp = avg % 2;
if (temp == 0) {
res += word.charAt(avg - 1) + word.charAt(avg);
} else {
res += word.charAt(avg);
}
return res;
}
console.log(pri("Lime")); // even letter
console.log(pri("Apple")); // odd letter
console.log(pri("Apple is Fruit")); // String sequence with space
console.log(pri("")); // empty string

here is my solution
function getMiddle(s){
let middle = Math.floor(s.length/2);
return s.length % 2 === 0
? s.slice(middle-1, middle+1)
: s.slice(middle, middle+1);
}

function extractMiddle(s) {
return s.substr(Math.ceil(s.length / 2 - 1), s.length % 2 === 0 ? 2 : 1);
}
extractMiddle("handbananna");

str.length is a property. Just get rid of the parentheses. Example:
if (str.length == 44) {

length is a property of string, not a function. Do this instead:
str.length % 2 === 1
Also, use I suggest favoring === over ==

Since length is not a function, there is no need to use ().

function getMiddle(str) {
if(str.length % 2 === 0 ) {
return str.substr(str.length/2-1, 2);
} else {
return str.charAt(Math.floor(str.length/2));
}
}
console.log(getMiddle("middbkbcdle"));

Related

Optimizing and finding edge cases that I might have missed - 2 coding interview questions

Background - I took an online coding test and was presented with questions similar to this, I did rather poorly on it compared to the hidden grading criteria and I was hoping to get another pair of eyes to look at it and maybe help point out some of my mistakes.
Practice Test questions -
Task: Given an integer inject the number 5 into it to make the largest possible integer
Conditions: (-80000...80000) range needed to handle
Expected input: int
Expected output: int
Testcase: -999 -> -5999
80 -> 850
var lrgInt = function(num) {
var stringInt = num.toString();
for (let i = 0; i < stringInt.length; i++) {
if (stringInt.charAt(i) === "-") {
return parseInt([stringInt.slice(0, 1), '5', stringInt.slice(1)].join(''));
}else if (stringInt.charAt(i) < 5) {
return parseInt([stringInt.slice(0, i), '5', stringInt.slice(i)].join(''));
}
}
return parseInt([stringInt.slice(0, stringInt.length), '5', stringInt.slice(stringInt.length)].join(''));
};
Task: Determine the number of operations done on a number following the conditions to reduce it to 0.
Conditions:
- If the number is odd, subtract 1
- If the number is even, divide by 2
Expected input: int
Expected output: int
var operations = 0;
var numberOfSteps = function(num) {
if (num === 0){
return operations;
}else if (num % 2 == 0) {
operations++;
return numberOfSteps(num/2);
} else {
operations++;
return numberOfSteps(num-1);
}
};
For the second question, you could add one plus the result of recursion with the adjusted number without having a global counter.
function numberOfSteps(number) {
if (!number) return 0;
if (number % 2) return 1 + numberOfSteps(number - 1);
return 1 + numberOfSteps(number / 2);
}
console.log(numberOfSteps(5)); // 5 4 2 1 0
For the first question, we make the observation that if the number is positive, we want to inject the 5 before the first digit less than 5, but if it's negative then we want to inject it before the first digit greater than 5. For the second problem, we can just use a simple while loop.
function largestNum(num) {
if (num == 0) {
// this edge case is weird but I'm assuming this is what they want
return 50;
}
var negative = num < 0;
var numAsStr = Math.abs(num).toString();
var inj = -1;
for (var i = 0; i < numAsStr.length; i++) {
var cur = parseInt(numAsStr[i], 10);
if ((!negative && cur < 5) || (negative && cur > 5)) {
// we found a place to inject, break
inj = i;
break;
}
}
if (inj == -1) {
// didn't inject anywhere so inject at the end
inj = numAsStr.length;
}
return (
(negative ? -1 : 1) *
parseInt(numAsStr.substr(0, inj) + "5" + numAsStr.substr(inj))
);
}
function numSteps(num) {
var steps = 0;
while (num != 0) {
if (num % 2) {
// it's odd
num--;
} else {
num /= 2;
}
steps++;
}
return steps;
}

Create a function middle()that returns the middle character/s of a word. If a word has even number of characters, return the middle two characters

var str = ""
var position
var length
function middle(str) {
if ((str % 2) == 0) {
position = str.length / 2;
length = 2;
} else {
position = (str.length + 1) / 2;
length = 1;
}
return str.substring(position, position + length);
}
middle("mynameis")
So here is my question, thank you in advance!
It just doesn't return anything. Any kind of help is appreciated.
There are few things that need to change:
Unless you're just typing this into the console, nothing will display anywhere,
so I put the function calls in a console.log() statement.
In your if statement, you need str.length instead of str.
JavaScript string (and array) methods are zero-based, meaning the first
character of a string is at index 0 as opposed to 1 as you might guess from
the word "first." Because of this, I changed
position = str.length / 2 to position = str.length / 2 - 1 and
position = (str.length + 1) / 2 to position = (str.length - 1) / 2.
(Not mandatory) Try to no use unnecessary global variables. Unless you
need to use str, position, or length somewhere else in the program,
put their declarations inside the function. In fact, the str variable
will not be used or changed by the function at all because str is the
name of a parameter of the function.
The code in the snippet below implements these changes.
function middle(str) {
var position, length;
if ((str.length % 2) == 0) {
position = str.length / 2 - 1;
length = 2;
} else {
position = (str.length - 1) / 2;
length = 1;
}
return str.substring(position, position + length);
}
console.log(middle("mynameis")); // am
console.log(middle("abc")); // b
console.log(middle("abcd")); // bc
I think the most understandable solution will be. No magic) All you need - understand substring and length method.
function Middle(str){
let a; // difine new variable, we will use it to return new string with charaster
if (str.length % 2 === 0) {
a = str.substring(str.length/2-1, str.length/2 + 1)
} else {
a = str.substring(str.length/2, str.length/2 + 1)
}
return a;
}
function Middle(str) {
let p;
if(str.length % 2 == 1) {
p = str.length / 2;
return str.substring(p, p + 1)
}
p = str.length / 2 - 1;
return str.substring(p, p + 2)
}

Sum a negative number's digits

'Write a function named sumDigits which takes a number as input and
returns the sum of each of the number's decimal
digits.'
How can I sum the digits with the first digit being negative?
For example: sumDigits(-32); // -3 + 2 = -1;
I was able to solve it partially.
function sumDigits(number) {
return Math.abs(number).toString().split("").reduce(function(a, b) {
return parseInt(a) + parseInt(b);
}, 0);
}
console.log( sumDigits(-32) );
Simple math and recursion make short work of this problem.
Recall that when you divide a number by 10, the remainder is its rightmost decimal digit and the integer part of the quotient is the number formed by the remaining digits. In other words:
let n = 5678;
console.log(n % 10); // => 8
console.log(Math.floor(n / 10)); // => 567
With this in mind, summing a number's digits is a straightforward recursive procedure:
Procedure(n)
Divide n by 10.
Set digit to the remainder.
Set n to the integer part of the quotient.
If n = 0, return digit.
Otherwise, return digit + Procedure(n)
Keeping the sign for the leftmost digit adds a small amount of complexity, but not much. Here's how it looks in JavaScript:
function digitSum(n, sign=1) {
if (n < 0) {
sign = -1; // Save the sign
n = Math.abs(n);
}
const digit = n % 10; // Remainder of |n÷10|
n = Math.floor(n / 10); // Integer part of |n÷10|
if (n === 0) {
return sign * digit; // No digits left, return final digit with sign
}
return digit + digitSum(n, sign); // Add digit to sum of remaining digits
}
console.log(digitSum(32)); // => 5
console.log(digitSum(-32)); // => -1
Here is a way to do it with Array.prototype.reduce().
Stringify the input and split it on each character.
Iterate over the characters with reduce.
Initialize the accumulator with a sum of 0 and a multiplier of 1.
If the first character is a -, set the multiplier to -1
For the subsequent characters, multiply the digit with the multiplier and add it to the sum. Then set the multiplier back to 1 so the next digits will only be multiplied by 1.
const sumDigits = x => [...`${x}`].reduce(({ sum, mult }, x, i) => {
return i === 0 && x === '-' ? { sum: 0, mult: -1 } : { sum: sum + mult * x, mult: 1 };
}, { sum: 0, mult: 1 }).sum;
console.log(sumDigits(-32)); // -1
console.log(sumDigits(32)); // 5
console.log(sumDigits(5555)); // 20
Here's a way you can do it without String conversion -
const sumDigits = (n = 0) =>
n < 0
? n > -10
? n
: (-n % 10) + sumDigits (n / 10 >> 0)
: n < 10
? n
: (n % 10) + sumDigits (n / 10 >> 0)
console.log(sumDigits(-321))
// (-3 + 2 + 1)
// => 0
console.log(sumDigits(321))
// (3 + 2 + 1)
// => 6
The same answer using imperative style -
const sumDigits = (n = 0) =>
{ if (n < 0)
if (n > -10)
return n
else
return (-n % 10) + sumDigits (n / 10 >> 0)
else
if (n < 10)
return n
else
return (n % 10) + sumDigits (n / 10 >> 0)
}
console.log(sumDigits(-321))
// (-3 + 2 + 1)
// => 0
console.log(sumDigits(321))
// (3 + 2 + 1)
// => 6
An approach that does not require converting to a string adapted from another answer by #NinaScholz to a closely related question (for those that are bitwise shift operator challenged).
Converts the number to its absolute value, loops with modulus operator to sum the remainder after dividing by 10 until a ones value remains, and then subtracts the leftmost digit if the original number was negative.
const sumDigits = (n) => {
const negative = !!(n < 0);
let sum = 0;
let num = negative ? Math.abs(n) : n;
while (num) {
if (negative && num <= 10) {
sum -= num % 10;
} else {
sum += num % 10;
}
num = Math.floor(num / 10);
}
return sum;
};
console.log(sumDigits(-32));
// -1
You could take a different method for separating the digits and keep the first one with a possible sign.
'-32'.match(/-?\d/g)
returns
['-3', '2']
function sumDigits(number) {
return number.toString().match(/-?\d/g).reduce(function(a, b) {
return a + +b;
}, 0);
}
console.log(sumDigits(-32));
First, "decimal digits" means only the characters to the right of the decimal point. Converting the number to a string sets you up as JavaScript strings are arrays of characters. So, then it's just a matter of splitting out the decimal digits then summing them by iterating that array, then converting back to a number type.
//'Write a function named sumDigits which takes a number as input and returns the sum of each of the number's decimal digits.'
var a = 10.12345;
var b = -1012345;
function sumDigits(x){
var result = 0;
x = x.toString();
x = x.split('.')[1];
if (x == null){
//there's not decimal digits to sum!
return "there's not decimal digits to sum!"
}
for (var i = 0; i < x.length; i++) {
if (digit >= 0 && digit <= 9) { //just in case, probably unnecessary
var digit = Number(x[i]);
result = result + digit;
}
}
//if you care about negative uncomment this
//if(x[0] === "-"){
// result = result * -1;
//}
return result;
}
console.log(sumDigits(a));
console.log(sumDigits(b));
// try this to get the sum of negatives:
const sumOfNegative = (numbers) => {
let sum = 0;
numbers.forEach((number) => {
if (number < 0) {
sum += number;
}
});
return sum;
};

How to "round" number, by putting zeros after the 2nd digit in javascript

I would like to "round" an integer number, by swapping all the digits after the 2nd digit to zeros. Additionally, if the number has only 1 digit, then don't do anything, and if the number has 2 digits, then swap the 2nd digit to a 0.
Example:
3 => 3
22 => 20
754 => 750
8912 => 8900
Can this be achieved without truncating the number as a string, and then rebuilding the number with zeros?
You don't need to truncate the number as a string, it can be easily achieved via mathematical calculation. Also, changing number to string and then doing any operation will be an added overhead which is not required in this case.
Refer the code below, it's quite straight forward.
Hope this helps.
function changeNumber(num){
if(Math.floor(num/10) == 0){
return num;
} else if(Math.floor(num/1000) == 0){
return Math.floor(num/10)*10;
}
else{
return Math.floor(num/100)*100
}
}
console.log(changeNumber(3));
console.log(changeNumber(22));
console.log(changeNumber(754));
console.log(changeNumber(8923));
That will work with every base-10 number.
All is about a simple math operation: number - [rest of (number / base-10 of number)]
function round(n) {
if(n < 10) return n;
var d = getTenBase(n.toString().length - 1);
return n - (n % (10 * d));
}
function getTenBase(l) {
var d = 1;
for(var i = 2; i < l; i++) {
d *= 10;
}
return d;
}
console.log(round(3));
console.log(round(22));
console.log(round(768));
console.log(round(1657));
you can just find length and first two character after that take zero with valid length and concat both
var str = '8912';
var n = str.length;
if(n == 1)
{
print(str);
} else if(n==2) {
var strFirst = str.substring(0,1);
var str2 = '0';
var res = strFirst.concat(str2);
} else if(n>2) {
var strFirst = str.substring(0,2);
var i;
var strsec ='0';
for (i = 0; i < n-3; i++) {
strsec += 0 ;
}
var res = strFirst.concat(strsec);
}
print(res);

Change base of a number in JavaScript using a given digits array

I was required to make a method to convert integer from base ten to some another base in JavaScript, and it should also support providing your custom digits array. For example,
toBase(10, 2 ["A","B"])// returns 'BABA'
and if digits array is not provided, it should work as JavaScript 'toString' method
var a = 10;
a.toString(2);//returns '1010'
I have wrote a function to convert an integer to another base from base 10 number, with an option of providing digits array -
function toBase(number, radix, digits)
{
radix = radix || 10;
digits = digits || "0123456789abcdefghijklmnopqrstuvwxyz".split("").slice(0, radix)
if (radix > digits.length) {
var msg = "Not enough digits to represent the number '" + number + "' in base " + radix;
throw Error(msg);
}
if (number === 0) return digits[0];
var a = []
while (number) {
a.splice(0, 0, digits[number % radix])
number = parseInt(number / radix);
}
return a.join("");
}
This function works fine for me, but I want to know if is there any better way to do it? Thanks.
You can just use the native toString method and then replace the output with those from the digits array:
function toBase(number, radix, digits) {
if (digits && digits.length >= radix)
return number.toString(radix).replace(/./g, function(d) {
return digits[ parseInt(d, radix) ];
});
else
return number.toString(radix);
}
A method that might be slightly faster than the way you have is to bit shift. This works most easily when radix is a power of 2, here is an example
function toBase(x, radix, A) {
var r = 1, i = 0, s = '';
radix || (radix = 10); // case no radix
A || (A = '0123456789abcdefghijklmnopqrstuvwxyz'.split('')); // case no alphabet
if (A.length < radix) throw new RangeError('alphabet smaller than radix');
if (radix < 2) throw new RangeError('radix argument must be at least 2');
if (radix < 37) return useBergisMethod(x, radix, A); // this is arguably one of the fastest ways as it uses native `.toString`
if (x === 0) return A[0]; // short circuit 0
// test if radix is a power of 2
while (radix > r) {
r = r * 2;
i = i + 1;
}
if (r === radix) { // radix = 2 ^ i; fast method
r = r - 1; // Math.pow(2, i) - 1;
while (x > 0) {
s = A[x & r] + s;
x >>= i; // shift binary
}
return s; // done
}
return methodInOriginalQuestion(x, radix, A); // else not a power of 2, slower method
}
/*
toBase(74651278, 64, '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzáé');
"4SnQE"
// check reverse
var i, j = 0, s = '4SnQE', a = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzáé';
for (i = 0; i < s.length; ++i) j *= 64, j += a.indexOf(s[i]);
j; // 74651278, correct
*/

Categories

Resources