JavaScript: Invalid destructuring target - javascript

Here is the code:
function BinarySearchNode(key) {
let node = {};
node.key = key;
node.lft = null;
node.rgt = null;
node.log = () => {
console.log(node.key);
}
node.get_node_with_parent = (key) => {
let parent = null;
while (this) {
if (key == this.key) {
return [this, parent];
}
if (key < this.key) {
[this, parent] = [this.lft, this];
} else {
[this, parent] = [this.rgt, this];
}
}
return [null, parent];
}
return node;
}
My Firefox is 44.0 and it throws a SyntaxError for these lines:
if (key < this.key) {
[this, parent] = [this.lft, this];
} else {
I tried to understand what exactly is wrong here by reading this blogpost and the MDN. Unfortuntely, I am still missing it :(

this is not a variable, but a keyword and cannot be assigned to. Use a variable instead:
node.get_node_with_parent = function(key) {
let parent = null;
let cur = this; // if you use an arrow function, you'll need `node` instead of `this`
while (cur) {
if (key == cur.key) {
return [cur, parent];
}
if (key < cur.key) {
[cur, parent] = [cur.lft, cur];
} else {
[cur, parent] = [cur.rgt, cur];
}
}
return [null, parent];
}

Related

How fix warning "Expected to return a value in arrow function array-callback-return"

This is my code:
form.listPrice.map(list => {
if (list.id === listId) {
form.active = true
listPrice = parseInt(list.price)
if (list.offerPrice) {
listofferPrice = parseInt(list.offerPrice)
} else {
listofferPrice = null
}
}
})
And here:
n.listPrice.map(list => {
if (list.id === listPrice) {
valid = true;
n.active = true;
n.showPrice.price = list.price;
n.showPrice.offerPrice = list.offerPrice;
n.ladder = list.ladder;
}
And this output the same warning:
Expected to return a value in arrow function array-callback-return
You are using .map incorrectly. .map should be used only when you want to construct a new array from an old array, but your code is not doing that - you're only carrying out side-effects - the setting of form.active and listofferPrice.
The first step would be to use forEach or for..of instead, eg:
for (const list of form.listPrice) {
if (list.id === listId) {
form.active = true
listPrice = parseInt(list.price)
if (list.offerPrice) {
listofferPrice = parseInt(list.offerPrice)
} else {
listofferPrice = null
}
}
}
But since it looks like you're trying to find a possible single matching value in the array, .find would be more appropriate:
const found = form.listPrice.find(list => list.id === listId);
if (found) {
form.active = true
listPrice = parseInt(found.price)
if (found.offerPrice) {
listofferPrice = parseInt(found.offerPrice)
} else {
listofferPrice = null
}
}
const found = n.listPrice.find(list => list.id === listPrice);
if (found) {
valid = true;
n.active = true;
n.showPrice.price = found.price;
n.showPrice.offerPrice = found.offerPrice;
n.ladder = found.ladder;
}

Get a value of a HashTable

I was making a HashTable to have as an example and have it saved for any problem, but I ran into a problem trying to implement a method that returns true or false in case the value belongs to the HashTable, since it is inside a arrays of objects as comment in the code.
I have tried for loops, .map and for of, but it always fails, if someone could help me.
function HashTable () {
this.buckets = [];
this.numbuckets = 35;
}
HashTable.prototype.hash = function (key) {
let suma = 0;
for (let i = 0; i < key.length; i++) {
suma = suma + key.charCodeAt(i);
}
return suma % this.numbuckets;
}
HashTable.prototype.set = function (key, value) {
if (typeof key !== "string") {
throw new TypeError ("Keys must be strings")
} else {
var index = this.hash(key);
if(this.buckets[index] === undefined) {
this.buckets[index] = {};
}
this.buckets[index][key] = value;
}
}
HashTable.prototype.get = function (key) {
var index = this.hash(key);
return this.buckets[index][key];
}
HashTable.prototype.hasKey = function (key) {
var index = this.hash(key);
return this.buckets[index].hasOwnProperty(key)
}
HashTable.prototype.remove = function (key) {
var index = this.hash(key);
if (this.buckets[index].hasOwnProperty(key)) {
delete this.buckets[index]
return true;
}
return false;
}
HashTable.prototype.hasValue = function (value) {
let result = this.buckets;
result = result.flat(Infinity);
return result // [{Name: Toni}, {Mame: Tino}, {Answer: Jhon}]
}
You can use Object.values() to get the values of all the propertyies in the bucket.
function HashTable() {
this.buckets = [];
this.numbuckets = 35;
}
HashTable.prototype.hash = function(key) {
let suma = 0;
for (let i = 0; i < key.length; i++) {
suma = suma + key.charCodeAt(i);
}
return suma % this.numbuckets;
}
HashTable.prototype.set = function(key, value) {
if (typeof key !== "string") {
throw new TypeError("Keys must be strings")
} else {
var index = this.hash(key);
if (this.buckets[index] === undefined) {
this.buckets[index] = {};
}
this.buckets[index][key] = value;
}
}
HashTable.prototype.get = function(key) {
var index = this.hash(key);
return this.buckets[index][key];
}
HashTable.prototype.hasKey = function(key) {
var index = this.hash(key);
return this.buckets[index].hasOwnProperty(key)
}
HashTable.prototype.remove = function(key) {
var index = this.hash(key);
if (this.buckets[index].hasOwnProperty(key)) {
delete this.buckets[index]
return true;
}
return false;
}
HashTable.prototype.hasValue = function(value) {
return this.buckets.some(bucket => Object.values(bucket).includes(value));
}
let h = new HashTable;
h.set("Abc", 1);
h.set("Def", 2);
console.log(h.hasValue(1));
console.log(h.hasValue(3));

add is not a function

I have no idea why I'm getting this error, I'm using trie.js from github and trying to use the add function, but it says that trie.add isn't a function.
var longestWord = function(words) {
console.log('test');
let trie = new Trie();
trie.add("test");
console.log(trie);
};
longestWord('testing');
function Trie() {
this.head = {
key : ''
, children: {}
}
}
Trie.prototype.add = function(key) {
var curNode = this.head
, newNode = null
, curChar = key.slice(0,1);
key = key.slice(1);
while(typeof curNode.children[curChar] !== "undefined"
&& curChar.length > 0){
curNode = curNode.children[curChar];
curChar = key.slice(0,1);
key = key.slice(1);
}
while(curChar.length > 0) {
newNode = {
key : curChar
, value : key.length === 0 ? null : undefined
, children : {}
};
curNode.children[curChar] = newNode;
curNode = newNode;
curChar = key.slice(0,1);
key = key.slice(1);
}
};
Trie.prototype.search = function(key) {
var curNode = this.head
, curChar = key.slice(0,1)
, d = 0;
key = key.slice(1);
while(typeof curNode.children[curChar] !== "undefined" && curChar.length > 0){
curNode = curNode.children[curChar];
curChar = key.slice(0,1);
key = key.slice(1);
d += 1;
}
if (curNode.value === null && key.length === 0) {
return d;
} else {
return -1;
}
}
Trie.prototype.remove = function(key) {
var d = this.search(key);
if (d > -1){
removeH(this.head, key, d);
}
}
function removeH(node, key, depth) {
if (depth === 0 && Object.keys(node.children).length === 0){
return true;
}
var curChar = key.slice(0,1);
if (removeH(node.children[curChar], key.slice(1), depth-1)) {
delete node.children[curChar];
if (Object.keys(node.children).length === 0) {
return true;
} else {
return false;
}
} else {
return false;
}
}
All the code I added myself is before function Trie(). The rest of it is from this github repo: https://gist.github.com/alexandervasyuk/b12c3d2c306539decb2a#file-trie-js
You are calling new Trie before adding prototypes to it.
This is working version:
https://jsbin.com/jokekuw/3/edit?js,output
var longestWord = function(words) {
console.log('test');
let trie = new Trie();
trie.add("test");
};
function Trie() {
this.head = {
key : ''
, children: {}
}
}
Your code should be moved to after the Trie declaration and prototype initialization.
The Trie constructor function (Trie) declaration will be hoisted to the top of the code block. Your code can therefore be successful in instantiating a new object with it. However, at the time you try to use the object, the Trie prototype has not yet been initialized. The prototype initialization statements are just ordinary statements, so they will be executed after your call to longestWord().
Thus if you move everything of yours that is currently before function Trie ... to the end of the overall code block, it should work (barring other errors).

Ember.computed.apply() shared getter/setter

Beginning with Ember 1.12, the below code block generates a deprecation warning because of changes to encourage using distinct getters and setters. I understand the concept, but I'm not sure how to refactor something that uses Ember.computed.apply() in such a way that these deprecation warning are resolved.
var args = this.constructor.primaryKeys.concat(function(_, setValue) {
var keyNames = this.constructor.primaryKeys;
if (setValue === undefined) {
var key, value;
for (var i = 0; i < keyNames.length; i++) {
key = keyNames[i];
value = this.get(key);
if (!Ember.isNone(value)) {
return value;
}
}
} else {
if (this.get('primaryKey') !== setValue) {
this.set(keyNames[0], setValue);
}
return setValue;
}
});
var primaryKey = Ember.computed.apply(Ember, args);
Twiddle demonstrating the problem
Solution:
var keyNames = this.constructor.primaryKeys;
var args = this.constructor.primaryKeys.concat({
get: function() {
var key, value;
for (var i = 0; i < keyNames.length; i++) {
key = keyNames[i];
value = this.get(key);
if (!Ember.isNone(value)) {
return value;
}
}
},
set: function(key, _, setValue) {
if (this.get('primaryKey') !== setValue) {
this.set(keyNames[0], setValue);
}
return setValue;
}
});
var primaryKey = Ember.computed.apply(Ember, args);
Ember.defineProperty(this, 'primaryKey', primaryKey);

How does Javascript evaluate the right parenthesis?

I'm working on a calculator that takes an expression such as (5+4) and evaluates it by passing the buttons pressed to an array, and then building a parse tree from the data in the array.
What's interesting/strange, is that my code won't push the value of the right parenthesis to the array. Here is my code, could someone help me out?
The console.log activeButton shows that is the value of the button being pressed, but even when I placed calcArray.push() outside the if statements it would not push ) to an array.
$(document).ready(function(){
var calcArray = new Array();
$("input").click(function(){
var activeButton = this.value;
console.log(activeButton);
if(!isNaN(activeButton))
{
calcArray.push(parseInt(activeButton));
console.log(calcArray);
}
else if(activeButton === "=")
{
evaluate(buildTree(calcArray));
calcArray = [];
}
else
{
calcArray.push(activeButton);
}
});
});
The BuildTree code:
function BinaryTree(root) {
this.root = root;
this.activeNode = root;
}
function Node(element){
this.element = element;
this.parent;
this.rightChild;
this.leftChild;
this.setLeft = function(node){
this.leftChild = node;
node.parent = this;
};
this.setRight = function(node){
this.rightChild = node;
node.parent = this;
};
}
//methods
var buildTree = function(array)
{
var tree = new BinaryTree(new Node(null));
for(var i = 0; i < array.length; i++)
{
var newNode = new Node(array[i]);
if(array[i] == "(")
{
newNode.element = null;
tree.activeNode.setLeft(newNode);
tree.activeNode = newNode;
}
else if(array[i] == "+" || array[i] == "-" || array[i] == "/" || array[i] == "*")
{
tree.activeNode.element = newNode.element;
tree.activeNode.setRight(new Node(null));
tree.activeNode = tree.activeNode.rightChild;
}
else if(array[i] == ")")
{
if(tree.activeNode.parent == null)
{
;
}
else
{
tree.activeNode = tree.activeNode.parent;
tree.root = tree.activeNode;
}
}
else
{
tree.activeNode.element = newNode.element;
tree.activeNode = tree.activeNode.parent;
}
}
return tree.activeNode;
}
var evaluate = function(node){
var newNode1, newNode2;
newNode1 = new Node(null);
newNode1.parent = node;
newNode2 = new Node(null);
newNode2.parent = node;
if(node.leftChild == null && node.rightChild == null)
return node.element;
else{
newNode1.element = evaluate(node.leftChild);
newNode2.element = evaluate(node.rightChild);
if(newNode1.parent.element == "+")
{
return Number(newNode1.element) + Number(newNode2.element);
}
if(newNode1.parent.element == "-")
{
return newNode1.element - newNode2.element;
}
if(newNode1.parent.element == "*")
{
return newNode1.element * newNode2.element;
}
else
{
return newNode1.element / newNode2.element;
}
}
};
I just tried this out using your code and it worked fine passing the value as a string:
function pushButton (value) {
var activeButton = value;
console.log(activeButton);
if(!isNaN(activeButton))
{
calcArray.push(parseInt(activeButton));
console.log(calcArray);
}
else if(activeButton === "=")
{
evaluate(buildTree(calcArray));
calcArray = [];
}
else
{
calcArray.push(activeButton);
}
};
You aren't ever printing out the array in the last case (which is where the right paren would go), so are you sure it's not on the array and you just aren't seeing the visual feedback?
If so, we need to see more of your code. Try and setup a jsfiddle.

Categories

Resources