Unexpected result in Javascript Kata on Codewars - javascript

Essentially I'm supposed to build a function that will give me the same output as the following test cases;
Test.assertSimilar(testit(0,1), 1, "")
Test.assertSimilar(testit(1,2), 3, "")
Test.assertSimilar(testit(10,20), 30, "")
//a*b?
Test.assertSimilar(testit(1,1), 1, "")
Test.assertSimilar(testit(1,3), 3, "")
This is what I've come up with;
function testit(a,b){
return b >= (2*a) ? a+b : a*b;
}
Essentially the logic is if b is greater than or equal to 2a than add a and b if not multiply a by b.
BUT the very last test case is returning 4 and I have no idea why that would happen. I'm just curious what I'm missing here or if there's some underlying principle I don't know of causing this to happen. Logically it seems like it should return 1*3 = 3.

Looking at the test cases, the logic you describe does not hold for the last testcase. Indeed 3 is greater than twice 1, so it would be an addition, and 1+3 is indeed 4. So you'll have to find another logic.
Although these test cases are not enough to really know for sure what the logic is, they do hold for a simple bit-wise OR operation:
const testit = (a, b) => a | b;
test(0,1, 1)
test(1,2, 3)
test(10,20, 30)
test(1,1, 1)
test(1,3, 3)
function test(a, b, expect) {
let result = testit(a, b);
console.log(`testit(${a},${b}) = ${result}, expect ${expect}`);
}

Related

javascript object related query [duplicate]

Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
Moderator note: Please resist the urge to edit the code or remove this notice. The pattern of whitespace may be part of the question and therefore should not be tampered with unnecessarily. If you are in the "whitespace is insignificant" camp, you should be able to accept the code as is.
Is it ever possible that (a== 1 && a ==2 && a==3) could evaluate to true in JavaScript?
This is an interview question asked by a major tech company. It happened two weeks back, but I'm still trying to find the answer. I know we never write such code in our day-to-day job, but I'm curious.
If you take advantage of how == works, you could simply create an object with a custom toString (or valueOf) function that changes what it returns each time it is used such that it satisfies all three conditions.
const a = {
i: 1,
toString: function () {
return a.i++;
}
}
if(a == 1 && a == 2 && a == 3) {
console.log('Hello World!');
}
The reason this works is due to the use of the loose equality operator. When using loose equality, if one of the operands is of a different type than the other, the engine will attempt to convert one to the other. In the case of an object on the left and a number on the right, it will attempt to convert the object to a number by first calling valueOf if it is callable, and failing that, it will call toString. I used toString in this case simply because it's what came to mind, valueOf would make more sense. If I instead returned a string from toString, the engine would have then attempted to convert the string to a number giving us the same end result, though with a slightly longer path.
I couldn't resist - the other answers are undoubtedly true, but you really can't walk past the following code:
var aᅠ = 1;
var a = 2;
var ᅠa = 3;
if(aᅠ==1 && a== 2 &&ᅠa==3) {
console.log("Why hello there!")
}
Note the weird spacing in the if statement (that I copied from your question). It is the half-width Hangul (that's Korean for those not familiar) which is an Unicode space character that is not interpreted by ECMA script as a space character - this means that it is a valid character for an identifier. Therefore there are three completely different variables, one with the Hangul after the a, one with it before and the last one with just a. Replacing the space with _ for readability, the same code would look like this:
var a_ = 1;
var a = 2;
var _a = 3;
if(a_==1 && a== 2 &&_a==3) {
console.log("Why hello there!")
}
Check out the validation on Mathias' variable name validator. If that weird spacing was actually included in their question, I feel sure that it's a hint for this kind of answer.
Don't do this. Seriously.
Edit: It has come to my attention that (although not allowed to start a variable) the Zero-width joiner and Zero-width non-joiner characters are also permitted in variable names - see Obfuscating JavaScript with zero-width characters - pros and cons?.
This would look like the following:
var a= 1;
var a‍= 2; //one zero-width character
var a‍‍= 3; //two zero-width characters (or you can use the other one)
if(a==1&&a‍==2&&a‍‍==3) {
console.log("Why hello there!")
}
IT IS POSSIBLE!
var i = 0;
with({
get a() {
return ++i;
}
}) {
if (a == 1 && a == 2 && a == 3)
console.log("wohoo");
}
This uses a getter inside of a with statement to let a evaluate to three different values.
... this still does not mean this should be used in real code...
Even worse, this trick will also work with the use of ===.
var i = 0;
with({
get a() {
return ++i;
}
}) {
if (a !== a)
console.log("yep, this is printed.");
}
Example without getters or valueOf:
a = [1,2,3];
a.join = a.shift;
console.log(a == 1 && a == 2 && a == 3);
This works because == invokes toString which calls .join for Arrays.
Another solution, using Symbol.toPrimitive which is an ES6 equivalent of toString/valueOf:
let i = 0;
let a = { [Symbol.toPrimitive]: () => ++i };
console.log(a == 1 && a == 2 && a == 3);
If it is asked if it is possible (not MUST), it can ask "a" to return a random number. It would be true if it generates 1, 2, and 3 sequentially.
with({
get a() {
return Math.floor(Math.random()*4);
}
}){
for(var i=0;i<1000;i++){
if (a == 1 && a == 2 && a == 3){
console.log("after " + (i+1) + " trials, it becomes true finally!!!");
break;
}
}
}
When you can't do anything without regular expressions:
var a = {
r: /\d/g,
valueOf: function(){
return this.r.exec(123)[0]
}
}
if (a == 1 && a == 2 && a == 3) {
console.log("!")
}
It works because of custom valueOf method that is called when Object compared with primitive (such as Number). Main trick is that a.valueOf returns new value every time because it's calling exec on regular expression with g flag, which causing updating lastIndex of that regular expression every time match is found. So first time this.r.lastIndex == 0, it matches 1 and updates lastIndex: this.r.lastIndex == 1, so next time regex will match 2 and so on.
This is possible in case of variable a being accessed by, say 2 web workers through a SharedArrayBuffer as well as some main script. The possibility is low, but it is possible that when the code is compiled to machine code, the web workers update the variable a just in time so the conditions a==1, a==2 and a==3 are satisfied.
This can be an example of race condition in multi-threaded environment provided by web workers and SharedArrayBuffer in JavaScript.
Here is the basic implementation of above:
main.js
// Main Thread
const worker = new Worker('worker.js')
const modifiers = [new Worker('modifier.js'), new Worker('modifier.js')] // Let's use 2 workers
const sab = new SharedArrayBuffer(1)
modifiers.forEach(m => m.postMessage(sab))
worker.postMessage(sab)
worker.js
let array
Object.defineProperty(self, 'a', {
get() {
return array[0]
}
});
addEventListener('message', ({data}) => {
array = new Uint8Array(data)
let count = 0
do {
var res = a == 1 && a == 2 && a == 3
++count
} while(res == false) // just for clarity. !res is fine
console.log(`It happened after ${count} iterations`)
console.log('You should\'ve never seen this')
})
modifier.js
addEventListener('message' , ({data}) => {
setInterval( () => {
new Uint8Array(data)[0] = Math.floor(Math.random()*3) + 1
})
})
On my MacBook Air, it happens after around 10 billion iterations on the first attempt:
Second attempt:
As I said, the chances will be low, but given enough time, it'll hit the condition.
Tip: If it takes too long on your system. Try only a == 1 && a == 2 and change Math.random()*3 to Math.random()*2. Adding more and more to list drops the chance of hitting.
It can be accomplished using the following in the global scope. For nodejs use global instead of window in the code below.
var val = 0;
Object.defineProperty(window, 'a', {
get: function() {
return ++val;
}
});
if (a == 1 && a == 2 && a == 3) {
console.log('yay');
}
This answer abuses the implicit variables provided by the global scope in the execution context by defining a getter to retrieve the variable.
This is also possible using a series of self-overwriting getters:
(This is similar to jontro's solution, but doesn't require a counter variable.)
(() => {
"use strict";
Object.defineProperty(this, "a", {
"get": () => {
Object.defineProperty(this, "a", {
"get": () => {
Object.defineProperty(this, "a", {
"get": () => {
return 3;
}
});
return 2;
},
configurable: true
});
return 1;
},
configurable: true
});
if (a == 1 && a == 2 && a == 3) {
document.body.append("Yes, it’s possible.");
}
})();
Alternatively, you could use a class for it and an instance for the check.
function A() {
var value = 0;
this.valueOf = function () { return ++value; };
}
var a = new A;
if (a == 1 && a == 2 && a == 3) {
console.log('bingo!');
}
EDIT
Using ES6 classes it would look like this
class A {
constructor() {
this.value = 0;
this.valueOf();
}
valueOf() {
return this.value++;
};
}
let a = new A;
if (a == 1 && a == 2 && a == 3) {
console.log('bingo!');
}
I don't see this answer already posted, so I'll throw this one into the mix too. This is similar to Jeff's answer with the half-width Hangul space.
var a = 1;
var a = 2;
var а = 3;
if(a == 1 && a == 2 && а == 3) {
console.log("Why hello there!")
}
You might notice a slight discrepancy with the second one, but the first and third are identical to the naked eye. All 3 are distinct characters:
a - Latin lower case A
a - Full Width Latin lower case A
а - Cyrillic lower case A
The generic term for this is "homoglyphs": different unicode characters that look the same. Typically hard to get three that are utterly indistinguishable, but in some cases you can get lucky. A, Α, А, and Ꭺ would work better (Latin-A, Greek Alpha, Cyrillic-A, and Cherokee-A respectively; unfortunately the Greek and Cherokee lower-case letters are too different from the Latin a: α,ꭺ, and so doesn't help with the above snippet).
There's an entire class of Homoglyph Attacks out there, most commonly in fake domain names (eg. wikipediа.org (Cyrillic) vs wikipedia.org (Latin)), but it can show up in code as well; typically referred to as being underhanded (as mentioned in a comment, [underhanded] questions are now off-topic on PPCG, but used to be a type of challenge where these sorts of things would show up). I used this website to find the homoglyphs used for this answer.
Yes, it is possible! 😎
» JavaScript
if‌=()=>!0;
var a = 9;
if‌(a==1 && a== 2 && a==3)
{
document.write("<h1>Yes, it is possible!😎</h1>")
}
The above code is a short version (thanks to #Forivin for its note in comments) and the following code is original:
var a = 9;
if‌(a==1 && a== 2 && a==3)
{
//console.log("Yes, it is possible!😎")
document.write("<h1>Yes, it is possible!😎</h1>")
}
//--------------------------------------------
function if‌(){return true;}
If you just see top side of my code and run it you say WOW, how?
So I think it is enough to say Yes, it is possible to someone that said to
you: Nothing is impossible
Trick: I used a hidden character after if to make a function that its name is similar to if. In JavaScript we can not override keywords so I forced to use this way. It is a fake if, but it works for you in this case!
» C#
Also I wrote a C# version (with increase property value technic):
static int _a;
public static int a => ++_a;
public static void Main()
{
if(a==1 && a==2 && a==3)
{
Console.WriteLine("Yes, it is possible!😎");
}
}
Live Demo
JavaScript
a == a +1
In JavaScript, there are no integers but only Numbers, which are implemented as double precision floating point numbers.
It means that if a Number a is large enough, it can be considered equal to four consecutive integers:
a = 100000000000000000
if (a == a+1 && a == a+2 && a == a+3){
console.log("Precision loss!");
}
True, it's not exactly what the interviewer asked (it doesn't work with a=0), but it doesn't involve any trick with hidden functions or operator overloading.
Other languages
For reference, there are a==1 && a==2 && a==3 solutions in Ruby and Python. With a slight modification, it's also possible in Java.
Ruby
With a custom ==:
class A
def ==(o)
true
end
end
a = A.new
if a == 1 && a == 2 && a == 3
puts "Don't do this!"
end
Or an increasing a:
def a
#a ||= 0
#a += 1
end
if a == 1 && a == 2 && a == 3
puts "Don't do this!"
end
Python
You can either define == for a new class:
class A:
def __eq__(self, who_cares):
return True
a = A()
if a == 1 and a == 2 and a == 3:
print("Don't do that!")
or, if you're feeling adventurous, redefine the values of integers:
import ctypes
def deref(addr, typ):
return ctypes.cast(addr, ctypes.POINTER(typ))
deref(id(2), ctypes.c_int)[6] = 1
deref(id(3), ctypes.c_int)[6] = 1
deref(id(4), ctypes.c_int)[6] = 1
print(1 == 2 == 3 == 4)
# True
It might segfault, depending on your system/interpreter.
The python console crashes with the above code, because 2 or 3 are probably used in the background. It works fine if you use less-common integers:
>>> import ctypes
>>>
>>> def deref(addr, typ):
... return ctypes.cast(addr, ctypes.POINTER(typ))
...
>>> deref(id(12), ctypes.c_int)[6] = 11
>>> deref(id(13), ctypes.c_int)[6] = 11
>>> deref(id(14), ctypes.c_int)[6] = 11
>>>
>>> print(11 == 12 == 13 == 14)
True
Java
It's possible to modify Java Integer cache:
package stackoverflow;
import java.lang.reflect.Field;
public class IntegerMess
{
public static void main(String[] args) throws Exception {
Field valueField = Integer.class.getDeclaredField("value");
valueField.setAccessible(true);
valueField.setInt(1, valueField.getInt(42));
valueField.setInt(2, valueField.getInt(42));
valueField.setInt(3, valueField.getInt(42));
valueField.setAccessible(false);
Integer a = 42;
if (a.equals(1) && a.equals(2) && a.equals(3)) {
System.out.println("Bad idea.");
}
}
}
This is an inverted version of #Jeff's answer* where a hidden character (U+115F, U+1160 or U+3164) is used to create variables that look like 1, 2 and 3.
var a = 1;
var ᅠ1 = a;
var ᅠ2 = a;
var ᅠ3 = a;
console.log( a ==ᅠ1 && a ==ᅠ2 && a ==ᅠ3 );
* That answer can be simplified by using zero width non-joiner (U+200C) and zero width joiner (U+200D). Both of these characters are allowed inside identifiers but not at the beginning:
var a = 1;
var a‌ = 2;
var a‍ = 3;
console.log(a == 1 && a‌ == 2 && a‍ == 3);
/****
var a = 1;
var a\u200c = 2;
var a\u200d = 3;
console.log(a == 1 && a\u200c == 2 && a\u200d == 3);
****/
Other tricks are possible using the same idea e.g. by using Unicode variation selectors to create variables that look exactly alike (a︀ = 1; a︁ = 2; a︀ == 1 && a︁ == 2; // true).
Rule number one of interviews; never say impossible.
No need for hidden character trickery.
window.__defineGetter__( 'a', function(){
if( typeof i !== 'number' ){
// define i in the global namespace so that it's not lost after this function runs
i = 0;
}
return ++i;
});
if( a == 1 && a == 2 && a == 3 ){
console.log( 'Oh dear, what have we done?' );
}
Honestly though, whether there is a way for it to evaluate to true or not (and as others have shown, there are multiple ways), the answer I'd be looking for, speaking as someone who has conducted hundreds of interviews, would be something along the lines of:
"Well, maybe yes under some weird set of circumstances that aren't immediately obvious to me... but if I encountered this in real code then I would use common debugging techniques to figure out how and why it was doing what it was doing and then immediately refactor the code to avoid that situation... but more importantly: I would absolutely NEVER write that code in the first place because that is the very definition of convoluted code, and I strive to never write convoluted code".
I guess some interviewers would take offense to having what is obviously meant to be a very tricky question called out, but I don't mind developers who have an opinion, especially when they can back it up with reasoned thought and can dovetail my question into a meaningful statement about themselves.
If you ever get such an interview question (or notice some equally unexpected behavior in your code) think about what kind of things could possibly cause a behavior that looks impossible at first glance:
Encoding: In this case the variable you are looking at is not the one you think it is. This can happen if you intentionally mess around with Unicode using homoglyphs or space characters to make the name of a variable look like another one, but encoding issues can also be introduced accidentally, e.g. when copying & pasting code from the Web that contains unexpected Unicode code points (e.g. because a content management system did some "auto-formatting" such as replacing fl with Unicode 'LATIN SMALL LIGATURE FL' (U+FB02)).
Race conditions: A race-condition might occur, i.e. a situation where code is not executing in the sequence expected by the developer. Race conditions often happen in multi-threaded code, but multiple threads are not a requirement for race conditions to be possible – asynchronicity is sufficient (and don't get confused, async does not mean multiple threads are used under the hood).
Note that therefore JavaScript is also not free from race conditions just because it is single-threaded. See here for a simple single-threaded – but async – example. In the context of an single statement the race condition however would be rather hard to hit in JavaScript.
JavaScript with web workers is a bit different, as you can have multiple threads. #mehulmpt has shown us a great proof-of-concept using web workers.
Side-effects: A side-effect of the equality comparison operation (which doesn't have to be as obvious as in the examples here, often side-effects are very subtle).
These kind of issues can appear in many programming languages, not only JavaScript, so we aren't seeing one of the classical JavaScript WTFs here1.
Of course, the interview question and the samples here all look very contrived. But they are a good reminder that:
Side-effects can get really nasty and that a well-designed program should be free from unwanted side-effects.
Multi-threading and mutable state can be problematic.
Not doing character encoding and string processing right can lead to nasty bugs.
1 For example, you can find an example in a totally different programming language (C#) exhibiting a side-effect (an obvious one) here.
Here's another variation, using an array to pop off whatever values you want.
const a = {
n: [3,2,1],
toString: function () {
return a.n.pop();
}
}
if(a == 1 && a == 2 && a == 3) {
console.log('Yes');
}
Okay, another hack with generators:
const value = function* () {
let i = 0;
while(true) yield ++i;
}();
Object.defineProperty(this, 'a', {
get() {
return value.next().value;
}
});
if (a === 1 && a === 2 && a === 3) {
console.log('yo!');
}
Using Proxies:
var a = new Proxy({ i: 0 }, {
get: (target, name) => name === Symbol.toPrimitive ? () => ++target.i : target[name],
});
console.log(a == 1 && a == 2 && a == 3);
Proxies basically pretend to be a target object (the first parameter), but intercept operations on the target object (in this case the "get property" operation) so that there is an opportunity to do something other than the default object behavior. In this case the "get property" action is called on a when == coerces its type in order to compare it to each number. This happens:
We create a target object, { i: 0 }, where the i property is our counter
We create a Proxy for the target object and assign it to a
For each a == comparison, a's type is coerced to a primitive value
This type coercion results in calling a[Symbol.toPrimitive]() internally
The Proxy intercepts getting the a[Symbol.toPrimitive] function using the "get handler"
The Proxy's "get handler" checks that the property being gotten is Symbol.toPrimitive, in which case it increments and then returns the counter from the target object: ++target.i. If a different property is being retrieved, we just fall back to returning the default property value, target[name]
So:
var a = ...; // a.valueOf == target.i == 0
a == 1 && // a == ++target.i == 1
a == 2 && // a == ++target.i == 2
a == 3 // a == ++target.i == 3
As with most of the other answers, this only works with a loose equality check (==), because strict equality checks (===) do not do type coercion that the Proxy can intercept.
Actually the answer to the first part of the question is "Yes" in every programming language. For example, this is in the case of C/C++:
#define a (b++)
int b = 1;
if (a ==1 && a== 2 && a==3) {
std::cout << "Yes, it's possible!" << std::endl;
} else {
std::cout << "it's impossible!" << std::endl;
}
Same, but different, but still same (can be "tested" multiple times):
const a = { valueOf: () => this.n = (this.n || 0) % 3 + 1}
if(a == 1 && a == 2 && a == 3) {
console.log('Hello World!');
}
if(a == 1 && a == 2 && a == 3) {
console.log('Hello World!');
}
My idea started from how Number object type equation works.
An ECMAScript 6 answer that makes use of Symbols:
const a = {value: 1};
a[Symbol.toPrimitive] = function() { return this.value++ };
console.log((a == 1 && a == 2 && a == 3));
Due to == usage, JavaScript is supposed to coerce a into something close to the second operand (1, 2, 3 in this case). But before JavaScript tries to figure coercing on its own, it tries to call Symbol.toPrimitive. If you provide Symbol.toPrimitive JavaScript would use the value your function returns. If not, JavaScript would call valueOf.
I think this is the minimal code to implement it:
i=0,a={valueOf:()=>++i}
if (a == 1 && a == 2 && a == 3) {
console.log('Mind === Blown');
}
Creating a dummy object with a custom valueOf that increments a global variable i on each call. 23 characters!
This one uses the defineProperty with a nice side-effect causing global variable!
var _a = 1
Object.defineProperty(this, "a", {
"get": () => {
return _a++;
},
configurable: true
});
console.log(a)
console.log(a)
console.log(a)
By overriding valueOf in a class declaration, it can be done:
class Thing {
constructor() {
this.value = 1;
}
valueOf() {
return this.value++;
}
}
const a = new Thing();
if(a == 1 && a == 2 && a == 3) {
console.log(a);
}
What happens is that valueOf is called in each comparison operator. On the first one, a will equal 1, on the second, a will equal 2, and so on and so forth, because each time valueOf is called, the value of a is incremented.
Therefore the console.log will fire and output (in my terminal anyways) Thing: { value: 4}, indicating the conditional was true.
As we already know that the secret of loose equality operator (==) will try to convert both values to a common type. As a result, some functions will be invoked.
ToPrimitive(A) attempts to convert its object argument to a primitive
value, by invoking varying sequences of A.toString and A.valueOf
methods on A.
So as other answers using Symbol.toPrimitive, .toString, .valueOf from integer. I would suggest the solution using an array with Array.pop like this.
let a = { array: [3, 2, 1], toString: () => a.array.pop() };
if(a == 1 && a == 2 && a == 3) {
console.log('Hello World!');
}
In this way, we can work with text like this
let a = { array: ["World", "Hello"], toString: () => a.array.pop() };
if(a == "Hello" && a == "World") {
console.log('Hello World!');
}
Surprisingly, yes. The == loose equality operator in JS calls the valueOf() method of the object that's being compared. Therefore, you can create a class that returns an internal value, then increments that interval value every time it's called. Like this:
class AClass {
constructor(initalVal) {
this.val = initalVal;
}
valueOf() {
return this.val++;
}
}
const a = new AClass(1);
console.log(a==1 && a==2 && a==3)
I know that there are a lot of other answers to this question, but this is how you'd do it with ES6 syntax.
Note: If you don't want this to happen, then you should use the === operator to check for strict instead. Like this:
class AClass {
constructor(initalVal) {
this.val = initalVal;
}
valueOf() {
return this.val++;
}
}
const a = new AClass(1);
console.log(a===1 && a===2 && a===3)
Yes, you can Do that, see the following JavaScript code:
let a = 0 // Create a variable and give it a value
if( a !== 1 && a !== 2 && a !== 3 )
{
console.log("true")
}
Explanation of the solution:
Simply , we add the not equal sign
before the == sign so that we tell the language that these values are
not equal to the value in the variable

How to fix a recursive hcf function?

I tried to make an HCF function in javascript using recursive functions as given in the code below. But somehow this only works for exact multiples of numbers (like 2,4 ; 52,104 etc). Co-prime numbers also gives 'undefined'. Please help me fix the bug.
I have tried substituting a local scope variable c = a % b. But this doesn't work out either.
The code:
function hcf(a, b) {
if (b == 1){
return 1;
} else if (a % b == 0){
return b;
} else {
hcf(a,a % b);
}
}
Test cases:
hcf(4,2);
hcf(108,52);
hcf(9,4);
Expected Outcomes:
2
4
1
Actual Outcomes:
2 [Correct]
undefined [Incorrect]
undefined [Incorrect]
The recursive case needs a return statement.

Sorting array based on multiple values of the same attribute in Javascript

Is there a more efficient way to sort an array based on multiple values of the same attribute in Javascript? I have the following function:
var p1 = [];
var p2 = [];
var p3 = [];
for (var i = 0; i < contentData.length; i++) {
if (contentData[i].priority === 1) {
p1.push(contentData[i]);
}
else if (contentData[i].priority === 2) {
p2.push(contentData[i]);
}
else if (contentData[i].priority === 3) {
p3.push(contentData[i]);
}
}
p1.sort(sortByDateDesc);
p2.sort(sortByDateDesc);
p3.sort(sortByDateDesc);
contentData = p1;
Array.prototype.push.apply(contentData, p2);
Array.prototype.push.apply(contentData, p3);
First I need to sort the array by its priority attribute, and then by its date attribute, which is done in the function sortByDateDesc. Can this be done in a more efficient way?
Thanks!
Sample array:
var data1 = {"title": "His face looks like the best chair", "text": "So there’s this really hot kid in my creative writing class. And everyone knows I like him." +
"But one day, he walked in looking like a freaking GQ model, and I accidentally out loud whispered “Shit, his face looks like the best chair” and the girl who sits " +
"in front of me turned around and said “WTH, that’s freaky and gross” and she moved her seat." +
"She gives me weird looks every time she sees me now.", "url": "http://www.catfacts.co", "user": "Kash Muni", "timestamp": Date.now(), "read":0, "priority":2};
sortByDateDesc function:
function sortByDateDesc(a, b) {
if (a.timestamp > b.timestamp)
return -1;
if (b.timestamp > a.timestamp)
return 1;
return 0;
}
You can use the || in the custom callback function. Something like this:
contentData.sort( (a, b) => a.priority - b.priority || b.timestamp - a.timestamp );
Only when a.priority - b.priority is zero (they are equal) will the second part of the expression be evaluated, which exactly when you want the date to play a role.
Swap a.timestamp and b.timestamp if the date order has to be ascending instead.
You are on the right track with your sortByDate function, which is passed in to the .sort() method as the "CompareFunction".
The CompareFunction that you provide will be passed two parameters, which are by-convention called "a" and "b", and must provide an answer which denotes their relative position:
If 'a comes before b' or if 'a is less than b' then return an answer < 0.
If 'a comes after b' or if 'a is greater than b' then return an answer > 0.
If 'a and b are equal' then you can return the answer 0.
It is entirely up to you how the CompareFunction deals with those objects. You might only compare a single property, compare multiple properties, or even perform complex processing within your function (but don't).
For comparisons which are numeric in nature, you can arithmetically determine the answer.
E.g.
function sortNumbersInAscendingOrder(a, b) {
return a - b;
}
If a > b then a - b results in a positive answer, which states that 'a comes after b'.
Comparing strings is a bit different as the comparison operators return a boolean value. However, you don't actually need to provide all three variants of answer from your CompareFunction - you are allowed to favour one of your objects and say that it comes first even when they're the same. This allows you to sort strings simply using the ternary operator.
E.g.
function sortStringsAlphabeticalOrder(a, b) {
// Note: this is a case sensitive sort!
return (a <= b) ? -1 : 1;
}
As usual, the Mozilla docs provide an excellent technical answer:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Logic concerning negative num inputs being converted to positive num inputs

Maybe I'm asking google all the wrong questions but I scoured the internet and could not find posts similar to my unique problem.
This is a simple coding challenge from FreeCodeCamp:
I need to work on the function abTest(a,b) where when a OR b is less than 0, the function will exit with the value of undefined. This is because we run the value a and b through a square root function. And you cannot take the square root of a negative number. Below is the code.
// Setup
function abTest(a, b) {
if (a < 0) {
a = -a;
return undefined;
} else if (b < 0) {
b = -b;
return undefined;
}
return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
}
// Change values below to test your code
abTest(2,2);
This code I used above works fine. However I have to specify that when a or b is < 0, a is assigned -a and b is assigned -b. Why is this necessary? In addition I want to convert this into a Switch statement, but I run into this problem of negative num values. Below are two switch statements I wrote but when using negative num input the abTest(-2,2) or abTest(2,-2) does not return the value undefined.
My First Switch Statement
switch (a,b) {
case a<0 || b<0:
return undefined;
}
My Second Switch Statement
switch (a,b) {
case a < 0:
a = -a;
console.log(undefined);
break;
case b < 0:
b = -b;
console.log(undefined);
break;
}
Where is this hole in my logic concerning switch statements and negative num values?
Thank you guys,
There should be no need to convert a = -a unless there is something wrong with freecodecamp. Just returning the value of undefined would/should produce the exact same result as changing a variable and then still returning undefined. To simplify your code you could also combine the if and else if statements like so
function abTest(a, b) {
if (a < 0 || b < 0){
return undefined;
} else {
return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
}
}
hope this helps

Range using recursion, how to output a new array Javascript

How do you output a new array using recursion without declaring an empty array outside of the function? Another way of doing it will be creating an inner function and then return newFunction(), but it is not allowed as the task is to call the function itself. Here's what I have so far:
var newArr=[];
var range = function(x, y) {
if(x === y-1){
return newArr;
}
if(x < y){
newArr.push(x+1);
newArr = range(x+1,y);
}
else{
newArr.push(x-1);
newArr = range(x-1,y);
}
return newArr;
};
range(2,10) //[3,4,5,6,7,8,9]
So the key to this kind of thinking is understanding that you should be creating a lot of arrays.
Looking at a slightly different example...
A factorial is a number which goes backwards, through positive integers, multiplying each term with the term below it, and is written like 5!.
These are helpful when you find yourself asking questions like:
"How many permutations of ____ are there?"
"Given these 5 things, how many permutations can I arrange them in, from left to right?"
5! // =>
5 x 4 x 3 x 2 x 1 // =>
120
You could see how we could build a loop and set a variable for a counter, and a variable for the total, and multiply the current total by the current value of the counter we're decrementing.
But instead of doing that, we can try to use recursion.
First, think about how we could simplify that 5 x 4 x ... into one repeated step.
Really, 2! is 2 x 1. 3! is 3 x 2 x 1, which happens to be 3 x 2!.
So the general case might be something like: n! == n x (n - 1)!
So I might write a generalized function which does something like this:
// DO NOT RUN THIS FUNCTION!
function factorial (n) {
return n * factorial(n - 1);
}
So if I run factorial(5) and use my imagination, we can see that the program is doing something like:
factorial(5)
=> return 5 * factorial(5-1)
=> return 4 * factorial(4-1)
=> return 3 * factorial(3-1)
=> ...
Can you see any problems with the function as-is?
I said at the beginning that factorials (in this simplified case) are over positive integers.
How does my function know to stop when the integers stop being positive?
It doesn't, currently. Which is why the above implementation attempts to run forever, and will freeze the browser, while it tries to, until it gets thousands or tens of thousands of functions deep, before it says that you've reached the maximum depth of the call stack and explodes.
What we really need is a condition or a set of conditions, which we use to determine when we're done.
This is a base-case.
if (shouldStop(n)) {
return defaultValue;
}
Or in our case:
function factorial (n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
Now, when we run the function, we have:
factorial(5)
=> 5 * factorial(5 - 1)
=> 4 * factorial(4 - 1)
=> 3 * factorial(3 - 1)
=> 2 * factorial(2 - 1)
=> 1
=> 2 * 1
=> 3 * 2
=> 4 * 6
=> 5 * 24
=> 120
This is recursion.
And because of where the call is (returned at the very end of whatever branch you're in) it's a special kind of recursion (tail recursion), which allows some languages to optimize the code, replacing the function call with the contents of the function call, and thus skip adding to the call-stack like the first version (future versions of JS will support this power).
In more modern JS, I might rewrite it to look something like
const factorial = n => n <= 1 ? 1 : factorial(n - 1);
So now, what about other cases?
Well, sometimes, you need to make sure you're passing more things in.
Think about what your problem is, and what kinds of counters or flags or collectors you need, in order to do your job.
Here's one:
function makeNumberString (current, max, initialString) {
var str = initialString || ""; // maybe I don't have one yet
var currentString = str.concat(current.toString());
if (current > max) {
return initialString;
}
return makeNumberString(current + 1, max, currentString);
}
makeNumberString(0, 9); // "0123456789"
There are other ways of filling that function out, to make it do the same thing.
Note that currentString there is always a brand new string, made by joining the string that I was given with the new value I was passed. I'm not actually modifying the original string, but creating a new copy [HINT!!].
I hope that helps you.
you can simply do like this;
var range = (x,y,a=[]) => (++x < y && (a = range(x,y,a.concat(x))),a),
arr = range(2,10);
console.log(arr);
Note that the returned array is a parameter of the function and is passed to successive recursive calls.
There are many ways to skin this cat.
The simple way: create an array with the first value in it, then
concatenate the remaining values to it.
var range = function(x,y){
return x+1 >= y ? [] : [x+1].concat(range(x+1, y));
}
console.log(JSON.stringify(range(1, 10)));
The array is being constructed from right to left. Notice how the
recursive call to range is not the last thing the function does
before it returns: concatenation of the array follows.
We can also rewrite the function to be tail recursive with an accumulator as a parameter.
var range2 = function(x,y,a){
a = a || [];
return x+1 >= y ? a : range2(x+1, y, a.concat(x+1));
}
console.log(JSON.stringify(range2(1, 10)));
Now the call to range2 is the last thing the function does before
it returns. ES6 compliant JS engines are required to
optimise
calls in tail position (in strict mode) by discarding the execution
context from the stack.
Notice how we're now constructing the array from left to right.
You can avoid the extra parameter by using a helper function.
I've used an inner function, but it doesn't have to be.
var range3 = function(x,y){
var r = function(x,y,a){
return x+1 >= y ? a : r(x+1, y, a.concat(x+1));
}
return r(x, y, []);
}
console.log(JSON.stringify(range3(1, 10)));
Tail recursive using continuation passing style.
var range4 = function(x,y){
var r = function(x,y,c){
return x+1 >= y ? c([]) : r(x+1, y, function(a){
return c([x+1].concat(a));
});
}
return r(x, y, function(a){return a;});
}
console.log(JSON.stringify(range4(1, 10)));
Notice the similarity with the original range: the array is
constructed in reverse. This is trickier to get your head around and
may be something you never need, but it doesn't hurt to be aware of
it.
Try this:
function rangeRecursive(start, end) {
if(start === end){
return end;
} else if(start > end){
return [];
} else {
return [start].concat(rangeRecursive(++start, end));
}
}
console.log(rangeRecursive(4, 15));

Categories

Resources