Loop through JSON & Compare time - javascript

What i'm trying to accomplish is to loop through this JSON, and compare the "start_time" and "end_time" to ensure the times don't overlap. I'm having trouble implementing this.
I found this: validate two times but none of it makes any sense nor is it using JSON but it's the closest i've found. Could I use jQuery to do this?
{
"Line_1":{
"artist":"Audien",
"day":"1",
"start_time":"13:00",
"end_time":"14:00",
"stage":"main"
},
"Line_2":{
"artist":"Slushii",
"day":"1",
"start_time":"13:30",
"end_time":"14:30",
"stage":"eclipse"
},
"Line_3":{
"artist":"DJ Snake",
"day":"1",
"start_time":"15:00",
"end_time":"16:00",
"stage":"main"
},
"Line_4":{
"artist":"Marshmello",
"day":"2",
"start_time":"14:15",
"end_time":"15:15",
"stage":"horizon"
}
}
Expected output:
Audien & Slushii Conflict!
DJ Snake Does not Conflict with anyone!
Marshmello Does not Conflict with anyone!
*Notice Days 1 & 2

Here is a rather verbose prototype for your learning purposes. It uses moment.js and twix.js.
Demo: https://jsfiddle.net/JAAulde/5v7yksk3/4/
HTML for prototype code:
<ul id="output"></ul>
JS for prototye code
var data = {
"Line_1":{
"artist":"Audien",
"day":"1",
"start_time":"13:00",
"end_time":"14:00",
"stage":"main"
},
"Line_2":{
"artist":"Slushii",
"day":"1",
"start_time":"13:30",
"end_time":"14:30",
"stage":"eclipse"
},
"Line_3":{
"artist":"DJ Snake",
"day":"1",
"start_time":"15:00",
"end_time":"16:00",
"stage":"main"
},
"Line_4":{
"artist":"Marshmello",
"day":"2",
"start_time":"14:15",
"end_time":"15:15",
"stage":"horizon"
}
},
tmp_day = '2000-01-01',
outer_key,
outer,
inner_key,
inner,
tmp_range,
checked = {},
conflict_found = {},
conflicts = [],
i;
for (outer_key in data) {
if (Object.prototype.hasOwnProperty.call(data, outer_key)) {
outer = data[outer_key];
tmp_range = moment(tmp_day + 'T' + outer.start_time).twix(tmp_day + 'T' + outer.end_time);
checked[outer_key] = true;
for (inner_key in data) {
if (Object.prototype.hasOwnProperty.call(data, inner_key) &&
outer_key !== inner_key &&
!checked[inner_key]
) {
inner = data[inner_key];
if (outer.day === inner.day &&
(
tmp_range.contains(tmp_day + 'T' + inner.start_time) ||
tmp_range.contains(tmp_day + 'T' + inner.end_time)
)
) {
conflict_found[outer_key] = true;
conflict_found[inner_key] = true;
conflicts.push([
outer_key,
inner_key
]);
}
}
}
}
}
// Output:
document.getElementById('output').innerHTML = '';
for (i = 0; i < conflicts.length; i++) {
document.getElementById('output').innerHTML += '<li><strong>' + data[conflicts[i][0]].artist + '</strong> conflicts with <strong>' + data[conflicts[i][1]].artist + '</strong></li>';
}
for (outer_key in data) {
if (Object.prototype.hasOwnProperty.call(data, outer_key) &&
!conflict_found[outer_key]
) {
document.getElementById('output').innerHTML += '<li><strong>' + data[outer_key].artist + '</strong> does not conflict with anyone</li>';
}
}

My solution:
var json = {
"Line_1":{
"artist":"Audien",
"day":"1",
"start_time":"13:00",
"end_time":"14:00",
"stage":"main"
},
"Line_2":{
"artist":"Slushii",
"day":"1","start_time":"13:30",
"end_time":"14:30",
"stage":"eclipse"
},
"Line_3":{
"artist":"DJ Snake",
"day":"1",
"start_time":"15:00",
"end_time":"16:00",
"stage":"main"
},
"Line_4":{
"artist":"Marshmello",
"day":"2",
"start_time":"17:15",
"end_time":"15:15",
"stage":"horizon"
}
};
function timeToDate(timeStr) {
var whateverDate = '01/01/1980 ';
return Date.parse(whateverDate + timeStr);
}
for (item in json) {
var st = json[item].start_time;
var et = json[item].end_time;
var datesCorrect = (timeToDate(st) < timeToDate(et)) ? 'true' : 'false';
console.log(item + ' dates correct: ' + datesCorrect);
};
Demo: https://jsfiddle.net/dhf89twr/1/

Related

jQuery widget method not being detected

For the life of me I cannot see the suttle difference between copied code. The _getMiscData method in a child widget apparently doesn't exist according to the parent widget. Can someone explain this?
I tried different method names in case I was using a reserved word. I tried private and public method with same result.
$(function() {
$.widget("custom.textquestion", $.custom.base, {
_create: function() {
this.element.data("_getControlValue", this.getControlValue());
},
getControlValue: function() {
this.element.attr("usersanswer", this.getResponseJSON());
},
_getAnswerSelection: function(answer) {
var qname = this._getQuestionName();
var type = this.getType();
return '<div class="radio span6"><label><input type="text" class="answerfield" name="optradio-' + qname + '" value="' + answer.answertext + '"></label></div>'
},
_getAnswersDiv: function(answers) {
// DIV is required for wrapping around list of answers
// so that they can be added all at once.
var answerdivs = '<div class="answerlist">'
for (k = 0; k < answers.length; k++) {
answerdivs += this._getAnswerSelection(answers[k]);
}
answerdivs += '</div>';
return answerdivs;
},
_getPopulatedEditor: function(answers) {
var editanswerdiv = "";
for (p = 0; p < answers.length; p++) {
editanswerdiv += '<label>Default</label><input type="text" onblur="savequestiondata()" identifier="' + answers[p].answerid + '" name="editanswer' + this._getQuestionName(this.options.questioncontrol) + '" size="20" value="' + answers[p].answertext + '"/><br/>'
}
return editanswerdiv;
},
_getAnswersJSON: function(div) {
var answers = [];
$(div).find("input[name='editanswer" + this._getQuestionName(this.options.questioncontrol) + "']").each(function(i, u) {
var answer = {
answerid: $(this).attr('identifier'),
answertext: $(this).val(),
answerorder: 0,
rating: 0
};
answers.push(answer);
});
return answers;
},
_setAnswerJSON: function(answer) {
answer = answer.replace(/['"]+/g, '');
this.options.questioncontrol.find("input[name='optradio-" + this._getQuestionName() + "']").val(answer);
return true;
},
getResponseJSON: function() {
qname = this._getQuestionName();
console.log("The control name is " + qname);
var answer = this.options.questioncontrol.find("input[name='optradio-" + qname + "']").val();
console.log("The answer is " + answer);
return answer;
},
_refresh: function() {
qname = this._getQuestionName(this.options.questioncontrol);
// Create the divs for the answer block, then
// append to this question as the list of answers.
var answers = this._getStoredData().data.answers;
var answerhtml = this._getAnswersDiv(answers);
this.options.questioncontrol.find(".answer-list").html("");
this.options.questioncontrol.find(".answer-list").append(answerhtml);
// Get the explanation text and add to control.
var explanation = this._getStoredData().data.explanation;
this.options.questioncontrol.find(".explanation").text(explanation);
// Populate the editor controls with the answers that
// are already stored - ready for editing.
var editanswerhtml = this._getPopulatedEditor(answers);
this.options.questioncontrol.find(".editanswers").html("");
this.options.questioncontrol.find(".editanswers").append(editanswerhtml);
this.options.questioncontrol.find(".notes").text(explanation);
},
_getQuestionText: function(div) {
var qtext;
$(div).find("input[name='questiontextedit']").each(function() {
qtext = $(this).val();
});
return qtext;
},
_getMiscData: function() {
var info = [this.options.questioncontrol.find(".email-mask").val()];
return info;
},
_setOtherData: function(info) {
if (info.emailmask == "true")
this.options.questioncontrol.find(".email-mask").attr("checked", "checked");
else
this.options.questioncontrol.find(".email-mask").attr("checked", "");
},
_getExplanationText: function(div) {
var etext = $(div).find(".notes").val();
return etext;
}
});
});
$(function() {
$.widget("custom.base", {
// default options
options: {
questioncontrol: this,
questiondata: null,
_storedData: [],
},
_create: function() {
},
_refresh: function() {
},
getEditedAnswers: function(div) {
// Get the set of answers that were edited.
if (!div)
div = this.options.questioncontrol;
var answersresult = this._getAnswersJSON(div);
var question = this._getQuestionText(div);
var typename = this.getType();
var qname = this._getQuestionName(this.options.questioncontrol);
var pagenumber = this._getStoredData(qname).data.pagenumber;
var order = this._getStoredData(qname).data.order;
var explanation = this._getExplanationText(div);
var otherdata = this._getMiscData();
var result = {
title: question,
type: typename,
pageid: pagenumber,
qname: qname,
answers: answersresult,
questionorder: order,
explanation: explanation,
otherdata: otherdata
};
return result;
},
getType: function() {
return $(this.options.questioncontrol).attr('id');
},
setData: function(questiondata) {
// Set the title for the question. I.e, the text
// for the question.
this.options.questioncontrol.find(".questiontitle").text(questiondata.title);
this.options.questioncontrol.find("input[name='questiontextedit']").val(questiondata.title);
this.options.questioncontrol.find(".notes").text(questiondata.explanation);
// Store the data into datastore.
var stored = 0;
if (this._getStoredData(questiondata.qname) == null) {
this.options._storedData.push({
qname: questiondata.qname,
data: questiondata
});
} else {
var datastored = this._getStoredData(questiondata.qname);
datastored.data = questiondata;
}
if (questiondata.otherdata)
this._setOtherData(questiondata.otherdata);
this._refresh();
},
setAnswer: function(answer) {
this._setAnswerJSON(answer);
},
_getQuestionName: function() {
return this.options.questioncontrol.find('.questionname').val();
},
_getStoredData: function() {
var qname = this._getQuestionName(this.options.questioncontrol);
for (p = 0; p < this.options._storedData.length; p++) {
if (this.options._storedData[p].qname == qname)
return this.options._storedData[p];
}
return null;
},
});
});
The custom.base widget shouldn't return with "this.getMiscData is not a function"

How can I delete Items from json string without using $.grep

I have a cart variable and I am storing the cart inside it like this.
[{"course_id":"24","doc_id":"211","doc_title":"PDF Notes","doc_price":"500"},{"course_id":"25","doc_id":"217","doc_title":"PDF Notes","doc_price":"500"},{"course_id":"25","doc_id":"218","doc_title":"PDF Solved Past Papers","doc_price":"500"},{"course_id":"26","doc_id":"224","doc_title":"PDF Solved Past Papers","doc_price":"595"}]
I created a RemoveFromCart function. It works in simple JQUERY But it is not working in Framework 7 because of $.grep. Is there any other way I can do it without using $.grep?
This is my Function
function removeFromCart(course_id, doc_id) {
var x = confirm("Are you sure you want to remove this item from your cart?");
if (x) {
$$('#cart_body').html('');
existing_cart = localStorage.getItem("cart");
if (existing_cart == '') {
existing_cart = [];
} else {
existing_cart = JSON.parse(existing_cart);
}
existing_cart = $.grep(existing_cart, function (data, index) {
return data.doc_id != doc_id
});
ex_cart = JSON.stringify(existing_cart);
localStorage.setItem('cart', ex_cart);
existing_cart = localStorage.getItem("cart");
if (existing_cart == '') {
existing_cart = [];
} else {
existing_cart = JSON.parse(existing_cart);
}
if (existing_cart !== null && existing_cart.length > 0) {
var total = '';
$$('#cart_div').show();
existing_cart.forEach(function (arrayItem) {
var text = '';
text = '<li class="item-content"><div class="item-inner"><div class="item-title">' + arrayItem.doc_title + '</div><div class="item-after">' + arrayItem.course_id + '</div><div class="item-after">' + arrayItem.doc_price + '</div><div class="item-after"><i class="icon icon-cross" onclick="removeFromCart(' + arrayItem.course_id + ',' + arrayItem.doc_id + ')"></i></div></div></li>';
total = Number(total) + Number(arrayItem.doc_price);
$$('#cart_body').append(text);
});
text = '<tr><td></td><td class="text-center"><b>Total: </b></td><td class="text-center">' + total + '</td><td></td></tr>';
$$('#cart_body').append(text);
} else {
$$('#cart_div').hide();
text = '<p>Your cart is empty.</p>';
$$('#cart_body').append(text);
}
} else {
return false;
}
}
Instead of:
$.grep(existing_cart, function ...
You can use:
existing_cart.filter(function ...
var new_courses = existing_cart.map( v=> {
if(v.doc_id != doc_id)
return v
}).filter( v=> {return v})
// new_courses does not contain the course with doc_id
map loops through each member of an array. filter removes members not returned in map.

how to write this code best way,which has so many if conditions in javascript?

I am get where condition(value) from getcondition(req, Sequelize)
code is:
options.where = getcondition(req, Sequelize);
options.include = [{
model: hp_builders,
required: true
}, { .... },{ .... }]
hp_property.findAndCountAll(options, {
subQuery: false
}).then(function(result) {
res.json(result);
});
so for different requests .i have to assign different value in options.where = getcondition(req, Sequelize);
so how can i write in an effective manner for getcondition(req, Sequelize);
my getcondition(req, Sequelize) function code is:
function getcondition(req, Sequelize) {
var condition = JSON.parse(req.query.selector);
if (condition.hasOwnProperty("city_id")) {
if (condition.hasOwnProperty("Inhibition")){
console.log(JSON.stringify(condition));
return {
$and: [{
hp_city_id: condition.city_id
},
Sequelize.literal("`hp_property`.`hp_property_inhibition_status_id` IN (" + condition.Inhibition + ")"),
]
}
}
if (condition.hasOwnProperty("bedrooms") && condition.hasOwnProperty("budgetPrice")) {
var budgetPrice = condition.budgetPrice.split(",");
var minRange = budgetPrice[0];
var maxRange = budgetPrice[1];
return {
$and: [{
hp_city_id: condition.city_id
},
Sequelize.literal("`hp_unit_details`.`hp_unit_type_id` IN (" + condition.bedrooms + ")"),
Sequelize.literal("`hp_unit_details.hp_unit_prices`.`price_per_sqft` * `hp_unit_details`.`property_size` BETWEEN " + minRange + " AND " + maxRange)
]
}
}
if (condition.hasOwnProperty("bedrooms") && !condition.hasOwnProperty("budgetPrice")) {
return {
$and: [{
hp_city_id: condition.city_id
},
Sequelize.literal("`hp_unit_details`.`hp_unit_type_id` IN (" + condition.bedrooms + ")")
]
}
} else if (condition.hasOwnProperty("budgetPrice") && !condition.hasOwnProperty("bedrooms")) {
var budgetPrice = condition.budgetPrice.split(",");
var minRange = budgetPrice[0];
var maxRange = budgetPrice[1];
return {
$and: [{
hp_city_id: condition.city_id
},
Sequelize.literal("`hp_unit_details.hp_unit_prices`.`price_per_sqft` * `hp_unit_details`.`property_size` BETWEEN " + minRange + " AND " + maxRange)
]
}
}
return {
hp_city_id: condition.city_id
}
}
else if (condition.hasOwnProperty("id")) {
if (condition.hasOwnProperty("Inhibition")){
console.log(JSON.stringify(condition));
return {
$and: [{
hp_builders_id: condition.id
},
Sequelize.literal("`hp_property`.`hp_property_inhibition_status_id` IN (" + condition.Inhibition + ")"),
]
}
}
if (condition.hasOwnProperty("bedrooms") && condition.hasOwnProperty("budgetPrice")) {
var budgetPrice = condition.budgetPrice.split(",");
var minRange = budgetPrice[0];
var maxRange = budgetPrice[1];
return {
$and: [{
hp_builders_id: condition.id
},
Sequelize.literal("`hp_unit_details`.`hp_unit_type_id` IN (" + condition.bedrooms + ")"),
Sequelize.literal("`hp_unit_details.hp_unit_prices`.`price_per_sqft` * `hp_unit_details`.`property_size` BETWEEN " + minRange + " AND " + maxRange)
]
}
}
if (condition.hasOwnProperty("bedrooms") && !condition.hasOwnProperty("budgetPrice")) {
return {
$and: [{
hp_builders_id: condition.id
},
Sequelize.literal("`hp_unit_details`.`hp_unit_type_id` IN (" + condition.bedrooms + ")")
]
}
} else if (condition.hasOwnProperty("budgetPrice" && !condition.hasOwnProperty("bedrooms"))) {
var budgetPrice = condition.budgetPrice.split(",");
var minRange = budgetPrice[0];
var maxRange = budgetPrice[1];
return {
$and: [{
hp_builders_id: condition.id
},
Sequelize.literal("`hp_unit_details.hp_unit_prices`.`price_per_sqft` * `hp_unit_details`.`property_size` BETWEEN " + minRange + " AND " + maxRange)
]
}
}
return {
hp_builders_id: condition.id
}
} else if (condition.hasOwnProperty("location_id")) {
console.log(JSON.stringify(req.query.selector) + ".....");
return {
hp_location_id: condition.location_id
}
}
}
Split in function and store conditions and function pointer in an array
var conditions = [
{
keys: [
{"key": "id", required:true}
{"key": "price", required:false}
],
function: fn1
},
{
keys: [
{"key": "id", required:false}
{"key": "price", required:false}
],
function: fn2
}
];
function checkKey(obj, id, required)
{
if(required)
return obj.hasOwnProperty(id);
else
return !obj.hasOwnProperty(id);
}
function checkKeys(obj, keys)
{
var condition = true;
for(var i = 0; i < keys.length; i++)
{
condition &= checkKey(obj, keys[i].key, keys[i].required);
}
return condition;
}
for(var i = 0; i < conditions.length; i++)
{
if(checkKeys(obj, conditions[i].keys))
return conditions[i].function(obj);
}
There are awesome JavaScript switch Statements. Use them when you have such terrible conditions.
UPD: Example of using switch:
function getcondition(req, Sequelize) {
const condition = JSON.parse(req.query.selector);
switch (true) {
case (condition.hasOwnProperty('city_id')): {
// ...
}
case (condition.hasOwnProperty('id')): {
// ...
}
case (condition.hasOwnProperty('location_id')): {
// ...
}
}
}
Note that the switch-case will break at the first occurance of any true statement. So, be careful while using break and return statements.
Using switch statements could actually help but in your case most conditions are too complicated. For syntax, follow this link : W3Schools javascript switch
What you could do in term of good practices would be creating sub_functions called in each condition. You can also gather a few tasks in your sub-functions and add if statements. This will lighten your function.
In term of good practices however, your sub-functions should not be redundant, try and choose carefully so that each function you write has a different purpose than the others.
EDIT : I previously said that your function should only have one return statement. This is not entirely true, as this convention can sometime make the code less easy to understand. That being said, it is a question of personal taste. A good compromise would be to put a return statement at the beginning of the function for error cases, and use another return statement at the end for classic result return.
You could also use pattern matching. See this link : Pattern matching with javascript.
i tried like this but i want more less and good code,plase give some other corrections
function getcondition1(req, Sequelize) {
var condition = JSON.parse(req.query.selector);
if (condition.hasOwnProperty("city_id")) {
return comparison(condition,"city_id","hp_city_id");
}
else if (condition.hasOwnProperty("id")) {
return comparison(condition,"id","hp_builders_id");
}
else if (condition.hasOwnProperty("location_id")) {
return comparison(condition,"location_id","hp_location_id");
}
}
function comparison(condition,id,dbId){
var obj={};
var andCondition=[];
var subCondition={};
if (condition.hasOwnProperty("Inhibition")){
subCondition[dbId]=condition.id;
andCondition.push(subCondition,Sequelize.literal("`hp_property`.`hp_property_inhibition_status_id` IN (" + condition.Inhibition + ")"));
obj['$and']=andCondition;
return obj;
}
if (condition.hasOwnProperty("bedrooms") && condition.hasOwnProperty("budgetPrice")) {
var budgetPrice = condition.budgetPrice.split(",");
var minRange = budgetPrice[0];
var maxRange = budgetPrice[1];
subCondition[dbId]=condition.id;
andCondition.push(subCondition,Sequelize.literal("`hp_unit_details`.`hp_unit_type_id` IN (" + condition.bedrooms + ")"),Sequelize.literal("`hp_unit_details.hp_unit_prices`.`price_per_sqft` * `hp_unit_details`.`property_size` BETWEEN " + minRange + " AND " + maxRange));
obj['$and']=andCondition;
return obj;
}
if (condition.hasOwnProperty("bedrooms") && !condition.hasOwnProperty("budgetPrice")) {
subCondition[dbId]=condition.id;
andCondition.push(subCondition,Sequelize.literal("`hp_unit_details`.`hp_unit_type_id` IN (" + condition.bedrooms + ")"))
obj['$and']=andCondition;
return obj;
} else if (condition.hasOwnProperty("budgetPrice") && !condition.hasOwnProperty("bedrooms")) {
var budgetPrice = condition.budgetPrice.split(",");
var minRange = budgetPrice[0];
var maxRange = budgetPrice[1];
subCondition[dbId]=condition.id;
andCondition.push(subCondition,Sequelize.literal("`hp_unit_details.hp_unit_prices`.`price_per_sqft` * `hp_unit_details`.`property_size` BETWEEN " + minRange + " AND " + maxRange))
obj['$and']=andCondition;
return obj;
}
obj[dbId] =condition.id
return obj;
}

SyntaxError: let is a reserved identifier on firefox

I am using those code below
'use strict';
jQuery(document).ready(function($) {
function CMB2ConditionalsInit(context) {
if(typeof context === 'undefined') {
context = 'body';
}
$('[data-conditional-id]', context).each(function(i, e) {
var $e = $(e),
id = $e.data('conditional-id'),
value = $e.data('conditional-value');
var $element = $('[name="' + id + '"]'),
$parent = $e.parents('.cmb-row:first').hide();
$e.data('conditional-required', $e.prop('required')).prop('required', false);
$element
.on('change', function(evt){
let conditionValue = CMB2ConditionalsStringToUnicode(evt.currentTarget.value);
if(typeof value === 'undefined') {
CMB2ConditionalToggleRows('[data-conditional-id="' + id + '"]', ($element.val() ? true : false));
} else {
CMB2ConditionalToggleRows('[data-conditional-id="' + id + '"]:not([data-conditional-value="' + conditionValue + '"])', false);
CMB2ConditionalToggleRows('[data-conditional-id="' + id + '"][data-conditional-value="' + conditionValue + '"]', true);
CMB2ConditionalToggleRows('[data-conditional-id="' + id + '"][data-conditional-value*=\'"' + conditionValue + '"\']', true);
}
});
if($element.length === 1) {
$element.trigger('change');
} else {
$element.filter(':checked').trigger('change');
}
});
}
function CMB2ConditionalsStringToUnicode(string){
let result = '', map = ["Á", "Ă","Ắ","Ặ","Ằ","Ẳ","Ẵ","Ǎ","Â","Ấ","Ậ","Ầ","Ẩ","Ẫ","Ä","Ǟ","Ȧ","Ǡ","Ạ","Ȁ","À","Ả","Ȃ","Ā","Ą","Å","Ǻ","Ḁ","Ⱥ","Ã","Ꜳ","Æ","Ǽ","Ǣ","Ꜵ","Ꜷ","Ꜹ","Ꜻ","Ꜽ","Ḃ","Ḅ","Ɓ","Ḇ","Ƀ","Ƃ","Ć","Č","Ç","Ḉ","Ĉ","Ċ","Ƈ","Ȼ","Ď","Ḑ","Ḓ","Ḋ","Ḍ","Ɗ","Ḏ","Dz","Dž","Đ","Ƌ","DZ","DŽ","É","Ĕ","Ě","Ȩ","Ḝ","Ê","Ế","Ệ","Ề","Ể","Ễ","Ḙ","Ë","Ė","Ẹ","Ȅ","È","Ẻ","Ȇ","Ē","Ḗ","Ḕ","Ę","Ɇ","Ẽ","Ḛ","Ꝫ","Ḟ","Ƒ","Ǵ","Ğ","Ǧ","Ģ","Ĝ","Ġ","Ɠ","Ḡ","Ǥ","Ḫ","Ȟ","Ḩ","Ĥ","Ⱨ","Ḧ","Ḣ","Ḥ","Ħ","Í","Ĭ","Ǐ","Î","Ï","Ḯ","İ","Ị","Ȉ","Ì","Ỉ","Ȋ","Ī","Į","Ɨ","Ĩ","Ḭ","Ꝺ","Ꝼ","Ᵹ","Ꞃ","Ꞅ","Ꞇ","Ꝭ","Ĵ","Ɉ","Ḱ","Ǩ","Ķ","Ⱪ","Ꝃ","Ḳ","Ƙ","Ḵ","Ꝁ","Ꝅ","Ĺ","Ƚ","Ľ","Ļ","Ḽ","Ḷ","Ḹ","Ⱡ","Ꝉ","Ḻ","Ŀ","Ɫ","Lj","Ł","LJ","Ḿ","Ṁ","Ṃ","Ɱ","Ń","Ň","Ņ","Ṋ","Ṅ","Ṇ","Ǹ","Ɲ","Ṉ","Ƞ","Nj","Ñ","NJ","Ó","Ŏ","Ǒ","Ô","Ố","Ộ","Ồ","Ổ","Ỗ","Ö","Ȫ","Ȯ","Ȱ","Ọ","Ő","Ȍ","Ò","Ỏ","Ơ","Ớ","Ợ","Ờ","Ở","Ỡ","Ȏ","Ꝋ","Ꝍ","Ō","Ṓ","Ṑ","Ɵ","Ǫ","Ǭ","Ø","Ǿ","Õ","Ṍ","Ṏ","Ȭ","Ƣ","Ꝏ","Ɛ","Ɔ","Ȣ","Ṕ","Ṗ","Ꝓ","Ƥ","Ꝕ","Ᵽ","Ꝑ","Ꝙ","Ꝗ","Ŕ","Ř","Ŗ","Ṙ","Ṛ","Ṝ","Ȑ","Ȓ","Ṟ","Ɍ","Ɽ","Ꜿ","Ǝ","Ś","Ṥ","Š","Ṧ","Ş","Ŝ","Ș","Ṡ","Ṣ","Ṩ","Ť","Ţ","Ṱ","Ț","Ⱦ","Ṫ","Ṭ","Ƭ","Ṯ","Ʈ","Ŧ","Ɐ","Ꞁ","Ɯ","Ʌ","Ꜩ","Ú","Ŭ","Ǔ","Û","Ṷ","Ü","Ǘ","Ǚ","Ǜ","Ǖ","Ṳ","Ụ","Ű","Ȕ","Ù","Ủ","Ư","Ứ","Ự","Ừ","Ử","Ữ","Ȗ","Ū","Ṻ","Ų","Ů","Ũ","Ṹ","Ṵ","Ꝟ","Ṿ","Ʋ","Ṽ","Ꝡ","Ẃ","Ŵ","Ẅ","Ẇ","Ẉ","Ẁ","Ⱳ","Ẍ","Ẋ","Ý","Ŷ","Ÿ","Ẏ","Ỵ","Ỳ","Ƴ","Ỷ","Ỿ","Ȳ","Ɏ","Ỹ","Ź","Ž","Ẑ","Ⱬ","Ż","Ẓ","Ȥ","Ẕ","Ƶ","IJ","Œ","ᴀ","ᴁ","ʙ","ᴃ","ᴄ","ᴅ","ᴇ","ꜰ","ɢ","ʛ","ʜ","ɪ","ʁ","ᴊ","ᴋ","ʟ","ᴌ","ᴍ","ɴ","ᴏ","ɶ","ᴐ","ᴕ","ᴘ","ʀ","ᴎ","ᴙ","ꜱ","ᴛ","ⱻ","ᴚ","ᴜ","ᴠ","ᴡ","ʏ","ᴢ","á","ă","ắ","ặ","ằ","ẳ","ẵ","ǎ","â","ấ","ậ","ầ","ẩ","ẫ","ä","ǟ","ȧ","ǡ","ạ","ȁ","à","ả","ȃ","ā","ą","ᶏ","ẚ","å","ǻ","ḁ","ⱥ","ã","ꜳ","æ","ǽ","ǣ","ꜵ","ꜷ","ꜹ","ꜻ","ꜽ","ḃ","ḅ","ɓ","ḇ","ᵬ","ᶀ","ƀ","ƃ","ɵ","ć","č","ç","ḉ","ĉ","ɕ","ċ","ƈ","ȼ","ď","ḑ","ḓ","ȡ","ḋ","ḍ","ɗ","ᶑ","ḏ","ᵭ","ᶁ","đ","ɖ","ƌ","ı","ȷ","ɟ","ʄ","dz","dž","é","ĕ","ě","ȩ","ḝ","ê","ế","ệ","ề","ể","ễ","ḙ","ë","ė","ẹ","ȅ","è","ẻ","ȇ","ē","ḗ","ḕ","ⱸ","ę","ᶒ","ɇ","ẽ","ḛ","ꝫ","ḟ","ƒ","ᵮ","ᶂ","ǵ","ğ","ǧ","ģ","ĝ","ġ","ɠ","ḡ","ᶃ","ǥ","ḫ","ȟ","ḩ","ĥ","ⱨ","ḧ","ḣ","ḥ","ɦ","ẖ","ħ","ƕ","í","ĭ","ǐ","î","ï","ḯ","ị","ȉ","ì","ỉ","ȋ","ī","į","ᶖ","ɨ","ĩ","ḭ","ꝺ","ꝼ","ᵹ","ꞃ","ꞅ","ꞇ","ꝭ","ǰ","ĵ","ʝ","ɉ","ḱ","ǩ","ķ","ⱪ","ꝃ","ḳ","ƙ","ḵ","ᶄ","ꝁ","ꝅ","ĺ","ƚ","ɬ","ľ","ļ","ḽ","ȴ","ḷ","ḹ","ⱡ","ꝉ","ḻ","ŀ","ɫ","ᶅ","ɭ","ł","lj","ſ","ẜ","ẛ","ẝ","ḿ","ṁ","ṃ","ɱ","ᵯ","ᶆ","ń","ň","ņ","ṋ","ȵ","ṅ","ṇ","ǹ","ɲ","ṉ","ƞ","ᵰ","ᶇ","ɳ","ñ","nj","ó","ŏ","ǒ","ô","ố","ộ","ồ","ổ","ỗ","ö","ȫ","ȯ","ȱ","ọ","ő","ȍ","ò","ỏ","ơ","ớ","ợ","ờ","ở","ỡ","ȏ","ꝋ","ꝍ","ⱺ","ō","ṓ","ṑ","ǫ","ǭ","ø","ǿ","õ","ṍ","ṏ","ȭ","ƣ","ꝏ","ɛ","ᶓ","ɔ","ᶗ","ȣ","ṕ","ṗ","ꝓ","ƥ","ᵱ","ᶈ","ꝕ","ᵽ","ꝑ","ꝙ","ʠ","ɋ","ꝗ","ŕ","ř","ŗ","ṙ","ṛ","ṝ","ȑ","ɾ","ᵳ","ȓ","ṟ","ɼ","ᵲ","ᶉ","ɍ","ɽ","ↄ","ꜿ","ɘ","ɿ","ś","ṥ","š","ṧ","ş","ŝ","ș","ṡ","ṣ","ṩ","ʂ","ᵴ","ᶊ","ȿ","ɡ","ᴑ","ᴓ","ᴝ","ť","ţ","ṱ","ț","ȶ","ẗ","ⱦ","ṫ","ṭ","ƭ","ṯ","ᵵ","ƫ","ʈ","ŧ","ᵺ","ɐ","ᴂ","ǝ","ᵷ","ɥ","ʮ","ʯ","ᴉ","ʞ","ꞁ","ɯ","ɰ","ᴔ","ɹ","ɻ","ɺ","ⱹ","ʇ","ʌ","ʍ","ʎ","ꜩ","ú","ŭ","ǔ","û","ṷ","ü","ǘ","ǚ","ǜ","ǖ","ṳ","ụ","ű","ȕ","ù","ủ","ư","ứ","ự","ừ","ử","ữ","ȗ","ū","ṻ","ų","ᶙ","ů","ũ","ṹ","ṵ","ᵫ","ꝸ","ⱴ","ꝟ","ṿ","ʋ","ᶌ","ⱱ","ṽ","ꝡ","ẃ","ŵ","ẅ","ẇ","ẉ","ẁ","ⱳ","ẘ","ẍ","ẋ","ᶍ","ý","ŷ","ÿ","ẏ","ỵ","ỳ","ƴ","ỷ","ỿ","ȳ","ẙ","ɏ","ỹ","ź","ž","ẑ","ʑ","ⱬ","ż","ẓ","ȥ","ẕ","ᵶ","ᶎ","ʐ","ƶ","ɀ","ff","ffi","ffl","fi","fl","ij","œ","st","ₐ","ₑ","ᵢ","ⱼ","ₒ","ᵣ","ᵤ","ᵥ","ₓ"];
for(let i = 0; i < string.length; i++){
if(jQuery.inArray(string[i], map) === -1) {
result += string[i]
} else {
result += "\\\\u" + ("000" + string[i].charCodeAt(0).toString(16)).substr(-4);
}
}
return result;
};
function CMB2ConditionalToggleRows(obj, showOrHide){
var $elements = (obj instanceof jQuery) ? obj : $(obj);
return $elements.each(function(i, e) {
let $e = $(e);
$e.prop('required', showOrHide && $e.data('conditional-required'));
$e.parents('.cmb-row:first').toggle(showOrHide);
});
}
CMB2ConditionalsInit('#post');
});
But it is giving me error below
After searched stackoverflow, I got that it will not work on firefox. Is there any way to fix it?
BTW, other browser working fine. Thanks in advance.
As you can see the let keyword isn't supported on FF yet: https://kangax.github.io/compat-table/es6/
You will need to change it to var, or transpile your code with babel

Why does this loop seem convoluted and verbose? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
The loop below builds an HTML string using the object literal obj_fav, which holds a list of favorites.
Because the HTML string can be appended in multiple places, ns_tag namespaces the DOM ids to make sure they are unique.
This is somewhat besides the point. I feel the loop has poor logic. It works fine, but I find it hard to read and feel that is is poorly written. But I can't put my finger on why that is.
// $A.someIndex() implements array.prototype.some
// create favorite pane strings
$A.someIndex(obj_fav, function (val) {
previous_id = current_id;
current_id = this.A.ns_tag + selector + val.tag;
// new tag found, close previous and open new
if ((previous_id === undefined) || (previous_id !== current_id)) {
// populate tag array
this.A['tag_array' + selector].push(current_id);
tag_string = tag_string + this.composeTag(current_id, selector);
if (previous_id !== undefined) {
favorite_string += '</div>';
}
favorite_string = favorite_string +
'<div class="bookmark_page toggle_display_none" id = "' + current_id + '_page">';
}
// add set of favorites between page tags
favorite_string += this.composeFavorite(val, selector);
}, this);
this snippet is contained in this klass:
/*******************************************************************************
**SArcmarks
*/
var SArcmarks = $A.klass({
Name: 'SArcmarks',
// namespacing helps to prevent name clashes // base_location_id_subdivisions // there are 2 prefixes and one suffix
A: {
// namespace suffix base: 'udt' loc: null,
ns_tag: 'udt_',
ns_tag1: 'udt_1_',
tag_array: [],
tag_array1: [],
prev_page_el: null,
prev_tag_el: null,
but_text: null,
// toggles
toggle_display_none: 'toggle_display_none',
toggle_display_inline: 'toggle_display_inline',
toggle_tag_active: 'toggle_tag_active',
toggle_tag_lazy: 'toggle_tag_lazy',
// morphing
class_a: null
},
E: {
hold_arcmarks: '#hold_arcmarks',
hold_tags: '#hold_tags',
aba_but_del: '#aba_but_del',
bookmark_link: '#bookmark_link'
},
/******************************************************************************/
update: function (obj_fav, fav_el, tag_el) {
var favorite_string = '',
tag_string = '',
current_id,
previous_id,
selector;
if (fav_el) {
selector = 1;
} else {
selector = '';
}
// create favorite pane strings
$A.someIndex(obj_fav, function (val) {
previous_id = current_id;
current_id = this.A.ns_tag + selector + val.tag;
// new tag found, close previous and open new
if ((previous_id === undefined) || (previous_id !== current_id)) {
// populate tag array
this.A['tag_array' + selector].push(current_id);
tag_string = tag_string + this.composeTag(current_id, selector);
if (previous_id !== undefined) {
favorite_string += '</div>';
}
favorite_string = favorite_string +
'<div class="bookmark_page toggle_display_none" id = "' + current_id + '_page">';
}
// add set of favorites between page tags
favorite_string += this.composeFavorite(val, selector);
}, this);
// close last tag
favorite_string = favorite_string + '</div>';
// if atleast one favorite/tag
if (this.A['tag_array' + selector][0]) {
if (!fav_el) {
this.E.hold_arcmarks.innerHTML = favorite_string;
} else {
fav_el.innerHTML = favorite_string;
}
if (!tag_el) {
this.E.hold_tags.innerHTML = tag_string;
} else {
tag_el.innerHTML = tag_string;
}
this.initPane(selector);
this.flip($A.el('#' + this.A['tag_array' + selector][0]));
}
},
/******************************************************************************/
composeFavorite: function (val, selector) {
// add selector
if (val.favicon === null) {
val.favicon = 'arcmarks/images/image_null_50.png';
}
return '<div class = "am_hold" id = "' + val.id + selector + '">' +
'<img name="bo_im" id="' + $A.addU(val.id + selector, 'a') +
'" class="bookmark_image" src="' + val.favicon + '">' +
'<a target="_blank" name="bookmark_link" class="bookmark_link" href = "' +
val.url + '" id="' + $A.addU(val.id + selector, 'b') + '">' + val.title + '</a>' +
'</div>';
},
/******************************************************************************/
composeTag: function (current_id, selector) {
// selector
return '<p class="single_tag toggle_tag_lazy" id = "' + current_id + '">' +
current_id.slice(this.A['ns_tag' + selector].length) + '</p>';
},
/******************************************************************************/
// add listeners to tag(<p>) elements
initPane: function (selector) {
$A.someIndex(this.A['tag_array' + selector], function (val) {
var self = this;
$A.el('#' + val).addEventListener("click", function () {
self.flip(this);
});
}, this);
},
/******************************************************************************/
// flip page(<div>) | tag(<p>) given a tag
flip: function (tag_element) {
var page_element = $A.el('#' + tag_element.id + '_page');
$A.addClass(page_element, this.A.toggle_display_inline);
$A.addClass(tag_element, this.A.toggle_tag_active);
if (this.A.prev_page_el && (tag_element.id !== this.A.prev_tag_el.id)) {
$A.addClass(this.A.prev_page_el, this.A.toggle_display_none);
$A.addClass(this.A.prev_tag_el, this.A.toggle_tag_lazy);
}
this.A.prev_page_el = page_element;
this.A.prev_tag_el = tag_element;
$A.log(page_element);
},
// insert favorite(<div>) given user input
insertFavorite: function (obj_fav) {
var tag_id = this.A.ns_tag + obj_fav.tag,
div_el,
html_string = this.composeFavorite(obj_fav),
page_el = $A.el('#' + tag_id + '_page');
div_el = $A.HTMLToElement(html_string);
if (!page_el) {
page_el = this.insertTagAndPage(tag_id);
}
$A.eachChild(page_el, function (iter) {
if (iter === null) {
page_el.appendChild(div_el);
return true;
}
if (div_el.id < iter.id) {
page_el.insertBefore(div_el, iter);
return true;
}
if (iter === page_el.lastChild) {
page_el.appendChild(div_el);
return true;
}
});
this.flip($A.el('#' + tag_id));
return div_el;
},
/******************************************************************************/
// insert page(<div>) | tag(<p>) given a tag id
insertTagAndPage: function (tag) {
var par_el,
div_el,
hold_tags_el,
hold_arcmarks_el,
self = this;
hold_tags_el = this.E.hold_tags;
hold_arcmarks_el = this.E.hold_arcmarks;
par_el = $A.createElement('p');
par_el.innerHTML = tag.slice(this.A.ns_tag.length);
par_el.className = "single_tag";
par_el.id = tag;
// insert the tag(<p>)
$A.eachChild(hold_tags_el, function (iter) {
if (iter === null) {
hold_tags_el.appendChild(par_el);
return true;
}
if (par_el.id < iter.id) {
hold_tags_el.insertBefore(par_el, iter);
return true;
}
if (iter === hold_tags_el.lastChild) {
hold_tags_el.appendChild(par_el);
return true;
}
});
par_el.addEventListener("click", function () {
self.flip(this);
});
div_el = $A.createElement('div');
div_el.className = "bookmark_page";
div_el.id = tag + "_page";
div_el.style.display = "";
// insert the page(<div>);
$A.eachChild(hold_arcmarks_el, function (iter) {
if (iter === null) {
hold_arcmarks_el.appendChild(div_el);
return true;
}
if (div_el.id < iter.id) {
hold_arcmarks_el.insertBefore(div_el, iter);
return true;
}
if (iter === hold_arcmarks_el.lastChild) {
hold_arcmarks_el.appendChild(div_el);
return true;
}
});
return div_el;
},
/******************************************************************************/
// delete a favorite(<div>) given a link
deleteFavorite: function (link_el) {
var self = this,
div_el = link_el.parentNode;
$(div_el).toggle("explode", function () {
if (div_el.previousSibling === null &&
div_el.nextSibling === null) {
self.deleteTagAndPage(div_el);
}
$A.removeElement(div_el);
});
},
/******************************************************************************/
// delete tag(<p>) and page(<div>) given a favorite sub-element
deleteTagAndPage : function (div_el) {
var page_el = div_el.parentNode,
tag_el = $A.el('#' + page_el.id.slice(0, -5)),
hold_el = $A.el("#hold_tags");
$A.removeElement(tag_el);
$A.removeElement(page_el);
$A.eachChild(hold_el, function (iter_el) {
if (iter_el) {
this.flip(iter_el);
return true;
}
}, this);
},
/******************************************************************************/
morph: function (callback) {
var i = 0,
button = this.E.aba_but_del;
if (this.A.but_text === 'Done') {
this.A.but_text = 'Delete';
this.A.class_a = 'bookmark_link';
while (this.E.bookmark_link[i]) {
this.E.bookmark_link[i].removeEventListener("click", callback);
this.E.bookmark_link[i].className = this.A.class_a;
i += 1;
}
button.innerHTML = this.A.but_text;
} else {
this.A.but_text = 'Done';
this.A.class_a = 'bookmark_delete';
while (this.E.bookmark_link[i]) {
this.E.bookmark_link[i].addEventListener("click", callback);
this.E.bookmark_link[i].className = this.A.class_a;
i += 1;
}
button.innerHTML = this.A.but_text;
}
}
}, true);

Categories

Resources