NodeJs note app delete function is not working? - arrays

I am building a Nodejs Note app and I am very new at this, so here the delete function doesn't work it, deletes everything from the array and I want to delete only title
There are two file app.js and note.js.
Here's the content of app.js file
if (command === "add") {
var note = notes.addNote(argv.title, argv.body);
if (note) {
console.log("Note created");
console.log("__");
console.log(`Title: ${note.title}`);
console.log(`Body: ${note.body}`);
} else {
console.log("The title has already exist")
}
} else if (command === "delete") {
var noteRemoved = notes.delNote(argv.title)
var message = noteRemoved ? "Note has been removed" : "Note not found";
console.log(message)
}
Here's the note.js content
var fetchNotes = function () {
try {
var noteString = fs.readFileSync("notes-data.json")
return JSON.parse(noteString);
} catch (e) {
return [];
}
};
var saveNotes = function (notes) {
fs.writeFileSync("notes-data.json", JSON.stringify(notes));
};
var addNote = function (title, body) {
var notes = fetchNotes();
var note = {
title,
body
};
var duplicateNotes = notes.filter(function (note) {
return note.title === title;
});
if (duplicateNotes.length === 0) {
notes.push(note);
saveNotes(notes);
return note;
};
}
var delNote = function (title) {
var notes = fetchNotes();
var filteredNotes = notes.filter(function (note) {
note.title !== title;
});
saveNotes(filteredNotes);
return notes.length !== filteredNotes.length
}

You miss return statement in delNote filter function
var filteredNotes = notes.filter(function (note) {
return note.title !== title;
});
or we can use es6 syntax:
const filteredNotes = notes.filter(note => note.title !== title);

You need to add return note.title !== title; in delNote function.

Related

Drift chat opening in every page

I have drift's async script code in the index.html file of the react app.
<script>
"use strict";
!function () {
var t = window.driftt = window.drift = window.driftt || [];
if (!t.init) {
if (t.invoked) return void (window.console && console.error && console.error("Drift snippet included twice."));
t.invoked = !0, t.methods = ["identify", "config", "track", "reset", "debug", "show", "ping", "page", "hide", "off", "on"],
t.factory = function (e) {
return function () {
var n = Array.prototype.slice.call(arguments);
return n.unshift(e), t.push(n), t;
};
}, t.methods.forEach(function (e) {
t[e] = t.factory(e);
}), t.load = function (t) {
var e = 3e5, n = Math.ceil(new Date() / e) * e, o = document.createElement("script");
o.type = "text/javascript", o.async = !0, o.crossorigin = "anonymous", o.src = "https://js.driftt.com/include/" + n + "/" + t + ".js";
var i = document.getElementsByTagName("script")[0];
i.parentNode.insertBefore(o, i);
};
}
}();
drift.SNIPPET_VERSION = '0.3.1';
drift.load('----api----');
drift.on('ready', api => {
api.widget.hide();
})
</script>
The issue is, it is getting popped up in every page of the app whereas I want it only when I click a button(onClick)
The function to trigger onClick :
openDriftChat = () =>{
const { setDriftState } = this.props;
if (window.drift.api) {
//this needs to happen only once but currently happening on every page load
if (!this.props.driftInit) {
if (localStorage.token) {
var tokenBase64 = localStorage.token.split(".")[1];
var tokenBase64_1 = tokenBase64.replace("-", "+").replace("_", "/");
var token = JSON.parse(window.atob(tokenBase64_1));
window.drift.identify(token.email, {
email: token.email,
nickname: token.name
});
setDriftState(true);
}
}
window.drift.api.openChat();
}
}
I basically want it pop up only when I call the function.
Hello I had the same issue:
To hide the welcome message use the following css code
iframe#drift-widget.drift-widget-welcome-expanded-online {
display: none !important;
}
iframe#drift-widget.drift-widget-welcome-expanded-away {
display: none !important;
}
The welcome message will only be shown when your drift button. Some extra info:
To hide the drift button icon use the following js code
drift.on('ready', function (api) {
api.widget.hide()
drift.on('message', function (e) {
if (!e.data.sidebarOpen) {
api.widget.show()
}
})
drift.on('sidebarClose', function (e) {
if (e.data.widgetVisible) {
api.widget.hide()
}
})
})
To call for the sidebar from a specific button use the following
Javascript
(function () {
var DRIFT_CHAT_SELECTOR = '.drift-open-chat'
function ready(fn) {
if (document.readyState != 'loading') {
fn();
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', fn);
} else {
document.attachEvent('onreadystatechange', function () {
if (document.readyState != 'loading')
fn();
});
}
}
function forEachElement(selector, fn) {
var elements = document.querySelectorAll(selector);
for (var i = 0; i < elements.length; i++)
fn(elements[i], i);
}
function openSidebar(driftApi, event) {
event.preventDefault();
driftApi.sidebar.open();
return false;
}
ready(function () {
drift.on('ready', function (api) {
var handleClick = openSidebar.bind(this, api)
forEachElement(DRIFT_CHAT_SELECTOR, function (el) {
el.addEventListener('click', handleClick);
});
});
});
})();
HTML
<a class="drift-open-chat">Open Chat</a>
I hope this helps someone out there.
PS: The above javascript code must be included after you have initialized your drift widget.
You need to disable that through the application: turn off the Playbooks.
Here is the link to do so: https://app.drift.com/playbooks
Hope it helps.

How to append a JSON to another JSON

I am trying to append the new object in the for loop to the request JSON.
this is not working :
setCapabilities('default',['1','2','3'])
export function
setCapabilities(kaiId:number|"default"|"defaultLeft"|"defaultRight",capabilitiesArr:string[]){
var request:object = {
type:'setCapabilities',
kaiId:kaiId
};
capabilitiesArr.forEach(element => {
var obj = {
element:true
}
console.log(obj)
});
}
This is also not working :
export function setCapabilities(kaiId:number|"default"|"defaultLeft"|"defaultRight",capabilitiesArr:string[]){
var request:object = {
type:'setCapabilities',
kaiId:kaiId
};
capabilitiesArr.forEach(element => {
var obj[element]=true
console.log(obj)
});
}
I want the output to be as :
console.log(request)
{
type:'setCapabilities',
kaiId:'default',
'1':true,
'2':true,
'3':true
}
I've updated the code in javascript for browser to run the code snippet, but you can convert it to typescript for your use
function setCapabilities(kaiId, capabilitiesArr) {
var request = {
type: 'setCapabilities',
kaiId: kaiId
}
var obj = Object.assign({}, request)
capabilitiesArr.forEach(element => {
obj[element] = true
});
console.log(obj)
}
setCapabilities('default',['1','2','3'])
In typescript use below code
function setCapabilities(kaiId:number|"default"|"defaultLeft"|"defaultRight",capabilitiesArr:string[]) {
var request:object = {
type: 'setCapabilities',
kaiId: kaiId
}
var obj = {...request}
capabilitiesArr.forEach(element => {
obj[element] = true
});
console.log(obj)
}

A function does not wait for another function to execute

This is my service
var validateEmailService=function (validateEmailUrl,validateEmailParameters,email) {
var url=validateEmailUrl +'?';
angular.forEach(validateEmailParameters,function (value,key) {
url=url +key +'='+ value.parameter +'&';
});
url=url+'email='+email;
$http.get(url).then(function (value) {
var result = value;
var smtpCheck = result.data.smtp_check;
var mxRecordsCheck = result.data.mx_found;
// console.log(smtpCheck ,mxRecordsCheck);
if (smtpCheck === true && mxRecordsCheck === true){
//console.log('In');
return true;
}
//console.log('Out');
});
};
var sendEmailService=function (sendEmailApiUrl,emailData,config,email,firstName,lastName) {
emailData = JSON.stringify(emailData);
emailData = emailData.replace("%%Email%%", email);
emailData = emailData.replace("%%FirstName%%", firstName);
emailData = emailData.replace("%%LastName%%", lastName);
emailData = JSON.parse(emailData);
$http.post(sendEmailApiUrl, emailData, config);
};
return {
validateEmailService: validateEmailService,
sendEmailService: sendEmailService
};
And I have called these functions here in the controller
var validate = emailService.validateEmailService(validateEmailUrl, validateEmailParameters,$scope.patient.Email);
if (validate === true) {
emailService.sendEmailService(sendEmailApiUrl, emailData, config,$scope.patient.Email,$scope.patient.givenName,$scope.patient.familyName);
messagingService.showMessage("info", "REGISTRATION_LABEL_SAVED");
$state.go("patient.edit", {
patientUuid: $scope.patient.uuid
});
}
else {
alert('Email does not exist');
}
So when the if statement is executed validate does not contain anything and it automatically goes to the else part even when validate should be true.
You should use the promise instead, the $http.get is asynchronous
var validateEmailService=function (validateEmailUrl,validateEmailParameters,email) {
var url=validateEmailUrl +'?';
angular.forEach(validateEmailParameters,function (value,key) {
url=url +key +'='+ value.parameter +'&';
});
url=url+'email='+email;
// IMPORTANT PART: USE RETURN
return $http.get(url).then(function (value) {
var result = value;
var smtpCheck = result.data.smtp_check;
var mxRecordsCheck = result.data.mx_found;
// console.log(smtpCheck ,mxRecordsCheck);
if (smtpCheck === true && mxRecordsCheck === true){
//console.log('In');
return true;
}
//console.log('Out');
});
};
And then in your controller:
emailService.validateEmailService(validateEmailUrl, validateEmailParameters,$scope.patient.Email).then(function(validate){
if (validate === true) {
emailService.sendEmailService(sendEmailApiUrl, emailData, config,$scope.patient.Email,$scope.patient.givenName,$scope.patient.familyName);
messagingService.showMessage("info", "REGISTRATION_LABEL_SAVED");
$state.go("patient.edit", {
patientUuid: $scope.patient.uuid
});
} else {
alert('Email does not exist');
}
})
Also, see this link about promises

Angularsjs cannot find service function

My filterProducts function makes a call to findIntersection which is present but I get an error findIntersection is undefined.
angular.module('BrandService', [])
.service('BrandService', function ($filter, DataService) {
var productDb;
var products;
return {
filterProducts(brands, priceRange) {
var filteredProducts = [];
var brandProducts = [];
var priceProducts = [];
var productsArray = [];
var brandChecked = false;
var priceChecked = false;
angular.forEach(brands, function (brand) {
if (brand.checked) {
brandChecked = true;
angular.extend(brandProducts,
$filter('filter')(productDb, { 'brand': brand.name }));
}
if (brandChecked) {
productsArray.push(brandProducts);
console.log('brandProducts = ', brandProducts)
}
});
angular.forEach(priceRange, function (price) {
if (price.checked) {
priceChecked = true;
let filteredProductDb = productDb.filter((prod) => {
return (prod.price >= price.low && prod.price <= price.high);
});
angular.extend(priceProducts, filteredProductDb);
}
});
if (priceChecked) {
productsArray.push(priceProducts);
// console.log('priceProducts = ', priceProducts)
}
if (!brandChecked && !priceChecked) {
filteredProducts = products;
} else {
if (productsArray.length > 1) {
filteredProducts = findIntersection(productsArray);
} else {
filteredProducts = productsArray[0];
}
}
return filteredProducts;
},
findIntersection(productsArray) {
console.log('findIntersection called')
var filteredProducts = [];
var filteredSet = new Set();
for(var i=0; i < productsArray.length - 1; i++) {
var products1 = productsArray[i];
var products2 = productsArray[i+1];
angular.forEach(products1, function(product1) {
angular.forEach(products2, function(product2) {
if(product1._id == product2._id) {
filteredSet.add(product1);
}
});
});
}
filteredProducts = Array.from(filteredSet);
return filteredProducts;
}
}
})
My filterProducts function makes a call to findIntersection which is present but I get an error findIntersection is undefined.
My filterProducts function makes a call to findIntersection which is present but I get an error findIntersection is undefined.
You are returning a javascript object with properties. You are not defining global functions.
You need to store the service returned before :
var service = { findProducts: ... , findIntersection: ... };
return service;
And instead of calling findIntersection, call service.findIntersection.
You have to make a reference to local object.
Simply change this: filteredProducts = findIntersection(productsArray);
to this: filteredProducts = this.findIntersection(productsArray);

How to push a JSON object to an array in AngularJS

I need to push a JSON object to AngularJS and need to check before if the value for one of the objects exist. I need to overwrite the data.
$scope.setData = function(survey, choice) {
keepAllData.push({
'surveyId': survey.id,
'choiceId': choice.id
});
console.log(keepAllData);
toArray(keepAllData);
alert(JSON.stringify(toArray(keepAllData)));
$scope.keepAllDatas.push({
'surveyId': survey.id,
'choiceId': choice.id
});
var items = ($filter('filter')(keepAllDatas, {
surveyId: survey.id
}));
}
function toArray(obj) {
var result = [];
for (var prop in obj) {
var value = obj[prop];
console.log(prop);
if (typeof value === 'object') {
result.push(toArray(value));
console.log(result);
} else {
result.push(value);
console.log(result);
}
}
return result;
}
If the survey id exists in keepalldata, I need to change the recent value with choiceid. Is it possible to do with AngularJS?
Try with this: Before pushing data you have to check if the survey id exists or not. If it exists you have to update choice with the corresponding survey id, otherwise you can push directly.
$scope.setData = function(survey, choice) {
var item = $filter('filter')(keepAllData, {
surveyId: survey.id
});
if (!item.length) {
keepAllData.push({
'surveyId': survey.id,
'choiceId': choice.id
});
} else {
item[0].choiceId = choice.id;
}
console.log(keepAllData);
}
Demo
$scope.keepAllDatas = [];
$scope.setData = function(survey, choice) {
if($scope.keepAllDatas.length == 0) {
$scope.keepAllDatas.push({'surveyId':survey.id,'choiceId':choice.id});
}
else {
var items = ($filter('filter')( $scope.keepAllDatas, {surveyId: survey.id }));
for (var i = items.length - 1; i >= 0; i--) {
// alert(items[i].surveyId);
if(items[i].surveyId == survey.id) {
console.log($scope.keepAllDatas.indexOf(survey.id));
$scope.keepAllDatas.splice($scope.keepAllDatas.indexOf(survey.id),1);
console.log("Removed data")
}
}
$scope.keepAllDatas.push({'surveyId':survey.id, 'choiceId':choice.id});
console.log( $scope.keepAllDatas)
// alert(items[0].surveyId);
}
}

Resources