isset equivalent in javascript to find palindrome - javascript

I created a script in PHP to find a palindrome, but when I try to do the same in JavaScript, then it is not working as expected. It's not just a matter of checking if the string that is reversed matches, but any order of the string has to be checked as well.
In other words, "mom" should return as true, "mmo" should return as true, "omm" should return as true, etc..., which is what the PHP script does, but the JS script below doesn't even work for the first iteration for the string "mom"
The following is the PHP script:
<?php
function is_palindrom($str) {
$str_array = str_split($str);
$count = array();
foreach ($str_array as $key) {
if(isset($count[$key])) {
$count[$key]++;
} else {
$count[$key] = 1;
}
}
$odd_counter = 0;
foreach ($count as $key => $val) {
if(($val % 2) == 1) {
$odd_counter++;
}
}
return $odd_counter <= 1;
}
echo is_palindrom('mom') ? "true" : "false";
The following is what I have tried in JS:
var count = [];
var strArr = [];
var oddCounter = 0;
var foreach_1 = function(item, index) {
console.log("count[index]: " + count[index]);
if (typeof count[index] !== "undefined") {
count[index]++;
} else {
count[index] = 1;
}
};
var foreach_2 = function(item, index) {
console.log("item: " + item + " item % 2: " + eval(item % 2));
if (eval(item % 2) == 1) {
oddCounter++;
}
console.log("oddCounter: " + oddCounter);
return oddCounter <= 1;
};
var isPalindrom = function(str) {
strArr = str.split("");
console.log(strArr);
strArr.forEach(foreach_1);
console.log(count);
count.forEach(foreach_2);
};
I believe it is failing where I try to replicate isset in javascript, with the following code:
if (typeof count[index] !== "undefined") {
As a result, I have tried to write my own isset function, but still the same result, it is not working:
var isset = function(obj) {
if (typeof obj === "undefined" || obj === null) {
return false;
} else {
return true;
}
};
With the following function being called:
if (isset(count[index])) {
count[index]++;
} else {
count[index] = 1;
}
As usual, any help would be appreciated and thanks in advance
BTW, it's killing me that I cannot remember the word for several revisions or iterations of something - I know that it starts with "re"

My attempt:
let p1 = `No 'x' in Nixon.`
let p2 = `Was it a car or a cat I saw?`
let p3 = `A man, a plan, a canal, Panama!`
function is_palindrome (str) {
const normalize = str => str.replace(/[.,:;`'"!?\/#$%\^&\*{}=\-_~()\s]/g, '').toLowerCase()
const reverse = str => [...str].reverse().join('')
return normalize(str) === reverse(normalize(str))
? true
: false
}
console.log(is_palindrome(p1))
console.log(is_palindrome(p2))
console.log(is_palindrome(p3))

First, thank you for all the comments.
Second, I ran a var_dump on the count array in the PHP file and this was the result:
array (size=2)
'm' => int 2
'o' => int 1
Which lead me to understand that count in js has to be an object for this work and I would have to create indexes of the object, depending on the string entered.
One thing lead to another and a complete re-write, but it works, along with a spell checker - see link at the bottom for complete code:
var count = {};
var strArr = [];
var oddCounter = 0;
var objKeys = [];
var splitString;
var reverseArray;
var joinArray;
var url = "test-spelling.php";
var someRes = "";
var mForN = function(obj, strArr) {
for (var y = 0; y < strArr.length; y++) {
// console.log("obj[strArr[" + y + "]]: " + obj[strArr[y]]);
if (isset(obj[strArr[y]])) {
obj[strArr[y]]++;
} else {
obj[strArr[y]] = 1;
}
}
return obj;
};
var mForN_2 = function(obj, objKeys) {
for (var z = 0; z < objKeys.length; z++) {
/* console.log(
"obj[objKeys[z]]: " +
obj[objKeys[z]] +
" obj[objKeys[z]] % 2: " +
eval(obj[objKeys[z]] % 2)
); */
if (eval(obj[objKeys[z]] % 2) == 1) {
oddCounter++;
}
// console.log("oddCounter: " + oddCounter);
}
return oddCounter <= 1;
};
var isset = function(obj) {
if (typeof obj === "undefined" || obj === null) {
return false;
} else {
return true;
}
};
var isPalindrom = function(str) {
// reverse original string
splitString = str.split("");
reverseArray = splitString.reverse();
joinArray = reverseArray.join("");
var checking = checkSpellingOfStr(str);
if (str == joinArray) {
strArr = str.split("");
// console.log("strArr: " + strArr);
objKeys = makeObjKeys(count, strArr);
// console.log("filled count before mForN: " + JSON.stringify(count));
// create array of keys in the count object
objKeys = Object.keys(count);
// console.log("objKeys: " + objKeys);
count = mForN(count, strArr);
// console.log("count after mForN: " + JSON.stringify(count));
return mForN_2(count, objKeys);
} else {
return 0;
}
};
var makeObjKeys = function(obj, arr) {
for (var x = 0; x < arr.length; x++) {
obj[arr[x]] = null;
}
return obj;
};
var checkSpellingOfStr = function(someStr) {
var formData = {
someWord: someStr
};
$.ajax({
type: "GET",
url: url,
data: formData,
success: function(result) {
if (!$.trim(result)) {
} else {
console.log(result);
$("#checkSpelling").html(result);
}
}
});
};
Start everything with the following call:
isPalindrom("mom") ? demoP.innerHTML = "is pal" : demoP.innerHTML = "is not pal";
In my example, I have a form and I listen for a button click as follows:
var palindromeTxt = document.getElementById("palindromeTxt").value;
var btn = document.getElementById("button");
btn.addEventListener("click", function (event) {
isPalindrom(palindromeTxt) ? demoP.innerHTML = "is pal" : demoP.innerHTML = "is not pal";
});
The following is the php for spell check:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(!empty($_REQUEST['someWord']))
{
$someWord = $_REQUEST['someWord'];
}
$pspell_link = pspell_new("en");
if (pspell_check($pspell_link, $someWord)) {
echo trim($someWord) . " is a recognized word in the English language";
} else {
echo "Your word is either misspelled or that is not a recognized word";
}
You will need pspell installed on your server, as well as adding extension=pspell.so to your php.ini
This is what I did, to get it running locally on my mac:
cd /Users/username/Downloads/php-5.6.2/ext/pspell
/usr/local/bin/phpize
./configure --with-php-config=/usr/local/php5-5.6.2-20141102-094039/bin/php-config --with-pspell=/opt/local/
make
cp ./modules/* /usr/local/php5-5.6.2-20141102-094039/lib/php/extensions/no-debug-non-zts-20131226
sudo apachectl restart
check your phpinfo file and you should see the following:
pspell
PSpell Support enabled
Live example

Related

In Javascript function onLoadPopulate() is not working?

function onLoadPopulate() {
var grid = $("#grid0");
var numberOfRecords = grid.getGridParam("records");
var dataFromGrid = grid.jqGrid('getGridParam', 'data');
var count=0;
var link;
if(numberOfRecords>0){
numberOfRecords=endNo;
count=begNo-1;
}
for ( ; count < numberOfRecords; count++) {
var program = dataFromGrid[count].program;
var programVal="";
var programs = program.replace(/\s/g,'').split(',');
for ( var i = 0; i< programs.length;i++) {
if (programs[i] == "FS") {
if (programVal == "") {
programVal = 'DOG';
} else {
programVal = programVal.concat(",DOG");
}
} else if (programs[i] == "TF") {
console.log("in TF");
if (programVal == "") {
programVal = 'CAT';
} else {
programVal = programVal.concat(",CAT");
}
}
grid.jqGrid('setCell', count + 1, 'program',
programVal);
}
}
TEST DATA:
program = FS, TF
result i'm getting : DOG but
the result i need : DOG,CAT
When it is doing else if Even if programs[i] = TF it is skipping if loop inside.
Can anyone help with this JavaScript function?
I can't figure it out what is wrong.
issue with input data consisted of special characters i used following replace and it worked
.replace(/[^a-z0-9,\s]/gi,'').replace(/[_\s]/g,'').split(',')

Is there a javascript library that does spreadsheet calculations without the UI

I am working on a project that needs an excel like calculation engine in the browser. But, it doesn't need the grid UI.
Currently, I am able to do it by hiding the 'div' element of Handsontable. But, it isn't elegant. It is also a bit slow.
Is there a client side spreadsheet calculation library in javascript that does something like this?
x = [ [1, 2, "=A1+B1"],
[2, "=SUM(A1,A2"),3] ];
y = CalculateJS(x);
##############
y: [[1, 2, 3],
[2,3,3]]
I'm not aware of any (although I haven't really looked), but if you wish to implement your own, you could do something along these lines (heavily unoptimized, no error checking):
functions = {
SUM: function(args) {
var result = 0;
for (var i = 0; i < args.length; i++) {
result += parseInt(args[i]);
}
return result;
}
};
function get_cell(position) {
// This function returns the value of a cell at `position`
}
function parse_cell(position) {
cell = get_cell(position);
if (cell.length < 1 || cell[0] !== '=')
return cell;
return parse_token(cell.slice(1));
}
function parse_token(tok) {
tok = tok.trim();
if (tok.indexOf("(") < 0)
return parse_cell(tok);
var name = tok.slice(0, tok.indexOf("("));
if (!(name in functions)) {
return 0; // something better than this?
}
var arguments_tok = tok.slice(tok.indexOf("(") + 1);
var arguments = [];
while (true) {
var arg_end = arguments_tok.indexOf(",");
if (arg_end < 0) {
arg_end = arguments_tok.lastIndexOf(")");
if (arg_end < 0)
break;
}
if (arguments_tok.indexOf("(") >= 0 && (arguments_tok.indexOf("(") < arg_end)) {
var paren_amt = 1;
arg_end = arguments_tok.indexOf("(") + 1;
var end_tok = arguments_tok.slice(arguments_tok.indexOf("(") + 1);
while (true) {
if (paren_amt < 1) {
var last_index = end_tok.indexOf(",");
if (last_index < 0)
last_index = end_tok.indexOf(")");
arg_end += last_index;
end_tok = end_tok.slice(last_index);
break;
}
if (end_tok.indexOf("(") > 0 && (end_tok.indexOf("(") < end_tok.indexOf(")"))) {
paren_amt++;
arg_end += end_tok.indexOf("(") + 1;
end_tok = end_tok.slice(end_tok.indexOf("(") + 1);
} else {
arg_end += end_tok.indexOf(")") + 1;
end_tok = end_tok.slice(end_tok.indexOf(")") + 1);
paren_amt--;
}
}
}
arguments.push(parse_token(arguments_tok.slice(0, arg_end)));
arguments_tok = arguments_tok.slice(arg_end + 1);
}
return functions[name](arguments);
}
Hopefully this will give you a starting point!
To test in your browser, set get_cell to function get_cell(x) {return x;}, and then run parse_cell("=SUM(5,SUM(1,7,SUM(8,111)),7,8)"). It should result in 147 :)
I managed to do this using bacon.js. It accounts for cell interdependencies. As of now, it calculates values for javascript formula instead of excel formula by using an eval function. To make it work for excel formulae, all one has to do is replace eval with Handsontable's ruleJS library. I couldn't find a URI for that library... hence eval.
https://jsfiddle.net/sandeep_muthangi/3src81n3/56/
var mx = [[1, 2, "A1+A2"],
[2, "A2", "A3"]];
var output_reference_bus = {};
var re = /\$?[A-N]{1,2}\$?[1-9]{1,4}/ig
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split('');
function convertToCellRef(rows, cols) {
var alphabet_index = rows+1,
abet = "";
while (alphabet_index>0) {
abet = alphabet[alphabet_index%alphabet.length-1]+abet;
alphabet_index = Math.floor(alphabet_index/alphabet.length);
}
return abet+(cols+1).toString();
}
function getAllReferences(value) {
if (typeof value != "string")
return null;
var references = value.match(re)
if (references.length == 0)
return null;
return references;
}
function replaceReferences(equation, args) {
var index = 0;
return equation.replace(re, function(match, x, string) {
return args[index++];
});
}
//Assign an output bus to each cell
mx.forEach(function(row, row_index) {
row.forEach(function(cell, cell_index) {
output_reference_bus[convertToCellRef(row_index, cell_index)] = Bacon.Bus();
})
})
//assign input buses based on cell references... and calculate the result when there is a value on all input buses
mx.forEach(function(row, row_index) {
row.forEach(function(cell, cell_index) {
if ((all_refs = getAllReferences(cell)) != null) {
var result = Bacon.combineAsArray(output_reference_bus[all_refs[0]]);
for (i=1; i<all_refs.length; i++) {
result = Bacon.combineAsArray(result, output_reference_bus[all_refs[i]]);
}
result = result.map(function(data) {
return eval(replaceReferences(cell, data));
})
result.onValue(function(data) {
console.log(convertToCellRef(row_index, cell_index), data);
output_reference_bus[convertToCellRef(row_index, cell_index)].push(data);
});
}
else {
if (typeof cell != "string")
output_reference_bus[convertToCellRef(row_index, cell_index)].push(cell);
else
output_reference_bus[convertToCellRef(row_index, cell_index)].push(eval(cell));
}
})
})
output_reference_bus["A2"].push(20);
output_reference_bus["A1"].push(1);
output_reference_bus["A1"].push(50);

Code Challenge: Rename filenames if duplicates are present

I'm working through a coding challenge I found online. I have the first test case passing but failing the second. I'm trying to decide if the second test case I'm failing is a typo or not.
Here is the question:
You are given an array of desired filenames in the order of their
creation. Since two files cannot have equal names, the one which comes
later will have an addition to its name in a form of (k), where k is
the smallest positive integer such that the obtained name is not used
yet.
Return an array of names that will be given to the files.
Test Cases:
1 - Passing:
INPUT: ["doc", "doc", "image", "doc(1)", "doc"]
OUTPUT: ["doc", "doc(1)", "image", "doc(1)(1)", "doc(2)"]
2 - Failing:
INPUT: ["a(1)","a(6)","a","a","a","a","a","a","a","a","a","a"]
OUTPUT: ["a(1)","a(6)","a","a(2)","a(3)","a(4)","a(5)","a(7)","a(8)","a(9)","a(10)","a(11)"]
Here is my code that passes the first Spec:
function fileNaming(names) {
var finalArr = [],
obj = {};
names.forEach(function(val){
if(obj[val] === undefined){
if(finalArr.indexOf(val) === -1){
finalArr.push(val);
obj[val] = 0;
} else {
obj[val] = 1;
finalArr.push(val + "(" + obj[val] + ")" );
}
} else {
finalArr.push( val + "(" + (++obj[val]) + ")");
}
});
return finalArr;
}
Question:
In the second test spec, why isn't there an "a(1)(1)" like there is a "doc(1)(1)" Is this a typo?
If anyone has suggestions on improvining my approach or alternative approaches I would greatly appreciate your feedback.
Here's a simpler approach. The idea is to store both the original and the generated name in the hashtable:
f = function(xs) {
var c = {}, t = (x, n) => x + "(" + n + ")";
return xs.map(function(x) {
var n = c[x] || 0;
c[x] = n + 1;
if(!n)
return x;
while(c[t(x, n)])
n++;
c[t(x, n)] = 1;
return t(x, n);
});
};
q = ["doc", "doc", "image", "doc(1)", "doc", "doc"];
document.write('<pre>'+JSON.stringify(f(q)));
q = ["a(1)","a(6)","a","a","a","a","a","a","a","a","a","a"]
document.write('<pre>'+JSON.stringify(f(q)));
Here's my approach :
def fileNaming(names):
uniq = []
for i in range(len(names)):
if names[i] not in uniq:
uniq.append(names[i])
else:
k = 1
while True:
if (names[i] + "(" + str(k) + ")") in uniq:
k += 1
else:
uniq.append(names[i] + "(" + str(k) + ")")
break
return uniq
with arrray approch
//var arr=["doc", "doc", "image", "doc(1)", "doc"];
var arr=["a(1)","a(6)","a","a","a","a","a","a","a","a","a","a"];
var arr1=new Array();
for (var r in arr)
{
if(arr1.indexOf(arr[r])>-1)
{
var ind=1;
while(arr1.indexOf(arr[r]+'('+ind+')')>-1)
{
ind++;
}
var str=arr[r]+'('+ind+')';
arr1.push(str);
}
else
{
arr1.push(arr[r]);
}
}
document.write("INPUT:"+arr+"</br>");
document.write("OUTPUT:"+arr1);
This was my beginner approach:
const renameFiles = arr => {
const fileObj = {};
let count = 0;
const renamed = arr.map(currentFile => {
if (!Object.keys(fileObj).includes(currentFile)) {
fileObj[currentFile] = count;
return currentFile;
} else {
count++;
if (Object.keys(fileObj).includes(`${currentFile}(${count})`)) {
count++;
return `${currentFile}(${count})`;
} else return `${currentFile}(${count})`;
}
});
return renamed;
};
Here is a working c++ impl.
#include <map>
#include <string>
using namespace std;
string makeName(string n, int i)
{
string ret = n + "(";
ret += std::to_string(i);
ret += ")";
return ret;
}
std::vector<std::string> fileNaming(std::vector<std::string> names)
{
map<string, int> lookup;
vector<string> outNames;
for (auto name : names)
{
auto f = lookup.find(name);
if (f != lookup.end())
{
int index = 1;
while (lookup.find(makeName(name, index)) != lookup.end())
{
index++;
}
name = makeName(name, index); // reassign
}
lookup[name] = 1;
outNames.push_back(name);
}
return outNames;
}
Here is my approach in Javascript:
function fileNaming(names) {
for (i in names) {
if (names.slice(0,i).includes(names[i])) {
j = 1
while (names.slice(0,i).includes(names[i]+"("+j.toString()+")")) {j++}
names[i] += "(" + j.toString() + ")"}}
return names
}

Profiling Javascript in PyV8

I have a JS codebase running within PyV8. Now I'd like to improve its performance, but there don't seem to be any hooks to enable the V8 profiler. In an older trunk version of PyV8 there are some options referencing the profiler but I don't find any documentation on it. Do you have any idea on how to profile in PyV8 without me having to rewrite the Python-to-JS wrapper?
Do you know of any JS-only-framework that uses monkey patching in order to generate a timing profile? It's not a big deal if there is some overhead involved - better than not having a profile at all.
At the end I've found the hint I needed in the book 'Pro Javascript Design Patterns': Use a closure together with func.apply to apply instrumentation on functions. Unfortunately, the JS way of decorating functions is not quite as clean as Python's - but hey, it works and I get the information I need to drill down into the code's performance characteristics.
profile.js
function mod_profiler() {
var profile_by_function_name = {};
var total_time = 0;
var time_counting_for_function = null;
function get_function_name(func) {
var result = func.toString();
result = result.substr('function '.length);
result = result.substr(0, result.indexOf('('));
return result;
}
function update_profile(function_name, elapsed_time) {
var profile = profile_by_function_name[function_name];
if (profile === undefined) {
profile = {calls:0, elapsed_time:0};
profile_by_function_name[function_name] = profile;
}
profile.calls += 1;
profile.elapsed_time += elapsed_time;
if (time_counting_for_function === function_name) {
total_time += elapsed_time;
}
}
function profile(func) {
function profiled() {
var function_name = get_function_name(func);
if (time_counting_for_function === null) {
time_counting_for_function = function_name;
}
var start_time = new Date().getTime()
var result = func.apply(undefined, arguments);
var elapsed_time = new Date().getTime() - start_time;
update_profile(function_name, elapsed_time);
if (time_counting_for_function === function_name) {
time_counting_for_function = null;
}
return result;
}
return profiled;
}
function get_formatted_result() {
function get_whitespace(length) {
var result = "";
for (var i = 0; i < length; i++) {
result += " ";
}
return result;
}
var function_names = Object.keys(profile_by_function_name);
var function_names_sorted_by_elapsed_time = function_names.sort(function (a,b) {
var elapsed_a = profile_by_function_name[a].elapsed_time;
var elapsed_b = profile_by_function_name[b].elapsed_time;
if (elapsed_a < elapsed_b) {
return 1;
}
if (elapsed_a > elapsed_b) {
return -1;
}
return 0;
});
var max_name_length = 0;
for (var i = 0; i < function_names_sorted_by_elapsed_time.length; i++) {
if (function_names_sorted_by_elapsed_time[i].length > max_name_length) {
max_name_length = function_names_sorted_by_elapsed_time[i].length;
}
}
var result = "\n" + get_whitespace(max_name_length) + " " + "#calls\telapsed\t% of total\n";
for (var i = 0; i < function_names_sorted_by_elapsed_time.length; i++) {
if (total_time === 0) {
break;
}
var function_name = function_names_sorted_by_elapsed_time[i];
var percentage_elapsed = profile_by_function_name[function_name].elapsed_time * 100 / total_time;
if (percentage_elapsed < 0.3) {
break;
}
result += function_name + ":" + get_whitespace(max_name_length - 1 - function_name.length) + profile_by_function_name[function_name].calls + "\t" + profile_by_function_name[function_name].elapsed_time + "\t" + percentage_elapsed.toFixed(2) + "\n";
}
result += "==========\n";
result += "total time accounted for [ms]: " + total_time;
return result;
}
return {
profile: profile,
get_formatted_result: get_formatted_result
}
}
my_module_1.js
function mod_1(profiler_param) {
var profiler = profiler_param;
function my_private_func() {
return "hello world2";
}
if (typeof(profiler) === 'object' && profiler !== null) {
render_user_menu = profiler.profile(render_user_menu);
} //private functions need the instrumentation to be added manually or else they're not included in the profiling.
function my_public_func1() {
return "hello world";
}
function my_public_func2(input1, input2) {
return my_private_func() + input1 + input2;
}
//public functions get the instrumentations automatically as long as they're called from outside the module
var public_function_by_names = {
my_public_func1: my_public_func1
my_public_func2: my_public_func2
}
var result = {};
var public_function_names = Object.keys(public_function_by_names);
for (var i = 0; i < public_function_names.length; i++) {
var func = public_function_by_names[public_function_names[i]];
if (typeof(profiler) === 'object' && profiler !== null) {
result[public_function_names[i]] = profiler.profile(func);
}
else {
result[public_function_names[i]] = func;
}
}
return result;
}
PyV8 side
with X4GEJSContext(extensions=['profile', 'my_module_1']) as ctx:
if self.enable_profiling == True:
ctx.eval("var profiler = mod_profiler();")
ctx.eval("var mod1 = mod_1(profiler);")
#note: you can pass profiler to as many modules as you want and they get instrumented together.
logging.info(ctx.eval("mod1.my_public_func_1() + mod1.my_public_func_2('a', 3);"))
logging.info(ctx.eval("profiler.get_formatted_result();"))
else:
ctx.eval("var mod1 = mod_1();") #it still works without the profiler
Output
"hello worldhelloworld2a3"
#calls elapsed % of total
my_public_func1: 1 31 50.00
my_public_func2: 1 31 50.00
my_private_func: 1 31 50.00
==========
total time accounted for [ms]: 62

overwriting a property in a string

Is there someone out there who can help me with this function. What it suppose to do is set a property in a string and this string is split firstly by a colon (:) for each control and the it checks if there is an id matching and if there is it then checks if there is a property matching if there is a property overwrite the value but my function doesn't seem to overwrite the property it just returns the original string. can someone help
var cookieValue = 'id=1&state=normal&theme=purple:id=2&state=maximized&theme=pink:id=3&state=maximized&theme=black';
var setProperties = function (cookie, id, prop, prop_value) {
var windows = cookie.split(':');
var result = $.each(windows, function(index, value) {
var temp1 = [];
if(value.indexOf(id) > -1) {
var temp2 = [];
var properties = value.split('&');
var result2 = $.each(properties, function(index, value) {
if(value.indexOf(prop) > -1) {
temp3 = [];
temp3 = value.split('=');
temp3[1] = prop_value;
temp2.push(temp3.join('='));
}else {
temp2.push(value);
}
return temp2.join('&')
});
temp1.push(result2.join('&'));
return temp1
}
else{
temp1.push(value);
}
return temp1;
})
return alert(result.join(':'));
}
setProperties(cookieValue, '2', 'theme', 'black');
Try:
function setProperties(cookie, id , name, value) {
var sections = $.map(cookie.split(":"), function (section) {
var pairs, found = false;
if (section.indexOf("id=" + id) === 0) {
pairs = $.map(section.split("&"), function (pair) {
if (pair.indexOf(name + "=") === 0) {
found = true;
return name + "=" + value;
} else {
return pair;
}
});
if (!found) {
pairs.push(name + "=" + value);
}
return pairs.join("&");
} else {
return section;
}
});
return sections.join(":");
}
Each doesn't return a value. You had some semicolons missing I edited the code a little.
It's not production worthy but at least it returns the (partially) correct value.
You will have to figure out how to replace that value in the cookie. I think regex is the best approach or of course you can pass temp1 array between the function but you will have to re-factor your code quite a lot.
var cookieValue = 'id=1&state=normal&theme=purple:id=2&state=maximized&theme=pink:id=3&state=maximized&theme=black';
var setProperties = function (cookie, id, prop, prop_value) {
var windows = cookie.split(':');
var result = $.each(windows, function(index, value) {
var temp1 = [];
console.log('value' + value);
console.log('windows' + windows);
console.log(cookieValue);
if(value.indexOf(id) > -1) {
var temp2 = [];
var properties = value.split('&');
var windows = $.each(properties, function(index, value) {
if(value.indexOf(prop) > -1) {
temp3 = [];
temp3 = value.split('=');
temp3[1] = prop_value;
temp2.push(temp3.join('='));
}else {
temp2.push(value);
}
cookieValue = temp2.join('&');
});
temp1.push(temp2.join('&'));
cookieValue = temp1;
}
else{
temp1.push(value);
}
cookeValue = temp1;
})
console.log("new cookie" + cookieValue); // PRINTS new cookieid=2&state=maximized&theme=black
}
setProperties(cookieValue, '2', 'theme', 'black');

Categories

Resources