Ознакомьтесь с нашей политикой обработки персональных данных
  • ↓
  • ↑
  • ⇑
 
Записи с темой: javascript (список заголовков)
17:45 

All permuations of string with placeholders

Vi Veri Veniversum Vivus Vici
In my first post, betazold.diary.ru/p203783901.htm, I give you the function to generate all permutations of array.

So, I implemented all permuations of string '{Пожалуйста|Просто} сделайте так, чтобы это {удивительное|крутое|простое} тестовое предложение {изменялось {быстро|мгновенно} случайным образом|менялось каждый раз}.' with code above. I used parser from geektimes.ru/post/87754/#comment_2638276 comment, where author returns only first random variation of string, and modified it:

  1. function printTree(t, index, r, delim) {
  2. var out = [],
  3. prefix, res;
  4. r = r || '';
  5. delim = delim || ' ';
  6. index = index || 0;
  7. if (index < t.length) {
  8. t = t.map(function(el) {
  9. return el instanceof Array ? el : [el];
  10. });
  11. prefix = r ? r + delim : '';
  12. for (var i = 0; i < t[index].length; i++) {
  13. if (t[index][i] instanceof Array) {
  14. res = printTree(t[index][i], 0, r, delim);
  15. } else {
  16. res = [prefix + t[index][i]];
  17. }
  18. for (var j = 0; j < res.length; j++) {
  19. out = out.concat(printTree(t, index + 1, res[j], delim));
  20. }
  21. }
  22. } else {
  23. return [r];
  24. }
  25. return out;
  26. }
  27.  
  28. function Token(type, pos, value) {
  29. this.type = type;
  30. this.pos = pos;
  31. this.value = value;
  32. }
  33. Token.END_OF_LINE = 0;
  34. Token.OPERATOR = 1;
  35. Token.TEXT = 2;
  36.  
  37. function Parser(text) {
  38. this._text = text;
  39. this._pos = 0;
  40. this._len = text.length;
  41. }
  42. Parser.prototype = {
  43. operators: {
  44. '{': true,
  45. '}': true,
  46. '|': true
  47. },
  48. nextToken: function() {
  49. if (this._pos >= this._len) return new Token(Token.END_OF_LINE);
  50. if (this._text[this._pos] in this.operators) {
  51. return new Token(Token.OPERATOR, this._pos, this._text[this._pos++]);
  52. }
  53. var text = '',
  54. start = this._pos;
  55. while ((this._pos < this._len) && !(this._text[this._pos] in this.operators)) {
  56. text += this._text[this._pos];
  57. this._pos++;
  58. }
  59. return new Token(Token.TEXT, start, text);
  60. },
  61. getNextToken: function() {
  62. var pos = this._pos,
  63. result = this.nextToken();
  64. this._pos = pos;
  65. return result;
  66. }
  67. };
  68.  
  69. function Interpretter(text) {
  70. this._parser = new Parser(text);
  71. }
  72. Interpretter.prototype = {
  73. value: function() {
  74. var result = [],
  75. token = this._parser.getNextToken();
  76. while (token.type == Token.TEXT || (token.type == Token.OPERATOR && token.value == '{')) {
  77. token = this._parser.nextToken();
  78. if (token.type == Token.OPERATOR) {
  79. if (token.value == '{') {
  80. result.push(this.exprеssion());
  81. } else {
  82. throw 'Syntax error at pos ' + token.pos;
  83. }
  84. } else {
  85. result.push(token.value);
  86. }
  87. token = this._parser.getNextToken();
  88. }
  89. return result;
  90. },
  91. includeValue: function(variants, value) {
  92. var hasNested = false;
  93. for (var i = 0; i < value.length; i++) {
  94. if (value[i] instanceof Array) {
  95. hasNested = true;
  96. break;
  97. }
  98. }
  99. if (hasNested) {
  100. variants.push(value);
  101. } else {
  102. variants = variants.concat(value);
  103. }
  104. return variants;
  105. },
  106. expression: function() {
  107. var variants = [],
  108. value = this.value(),
  109. token = this._parser.nextToken();
  110. variants = this.includeValue(variants, value);
  111. while (token.value == '|') {
  112. value = this.value();
  113. variants = this.includeValue(variants, value);
  114. token = this._parser.nextToken();
  115. }
  116. if (!token.type == '}') throw 'Syntax error at pos ' + token.pos;
  117. return variants;
  118. }
  119. };
  120.  
  121. var text = '{Пожалуйста|Просто} сделайте так, чтобы это ' +
  122. '{удивительное|крутое|простое} тестовое предложение {изменялось {быстро|мгновенно}' +
  123. ' случайным образом|менялось каждый раз}.';
  124. var interpretter = new Interpretter(text);
  125. var v = interpretter.value();
  126. var r = printTree(v);
  127. r.sort();
  128. print(r.join('\n'));


You can to check it in action at: ideone.com/hxJP3F

@темы: JavaScript, permutaions

17:42 

All permuations of array of arrays (and even more nested arrays)

Vi Veri Veniversum Vivus Vici
We can to implement this in Javasсript like:



  1. function printTree(t, index, r, delim) {
  2. var out = [],
  3. prefix, res;
  4. r = r || '';
  5. delim = delim || ' ';
  6. index = index || 0;
  7. if (index < t.length) {
  8. t = t.map(function(el) {
  9. return el instanceof Array ? el : [el];
  10. });
  11. prefix = r ? r + delim : '';
  12. for (var i = 0; i < t[index].length; i++) {
  13. if (t[index][i] instanceof Array) {
  14. res = printTree(t[index][i], 0, r, delim);
  15. } else {
  16. res = [prefix + t[index][i]];
  17. }
  18. for (var j = 0; j < res.length; j++) {
  19. out = out.concat(printTree(t, index + 1, res[j], delim));
  20. }
  21. }
  22. } else {
  23. return [r];
  24. }
  25. return out;
  26. }
  27. var tests = [
  28. [1, 2, 3],
  29. [1, [2, 3]],
  30. [
  31. [1, 2], 3
  32. ],
  33. [
  34. [1, 2],
  35. [3, 4]
  36. ],
  37. [
  38. [1, 2],
  39. [3, [4, 5], 6]
  40. ],
  41. [1, [2, [3, [4, 5]]]],
  42. [
  43. [1, 2],
  44. [
  45. [3, [4, 5, 6]], 7
  46. ]
  47. ],
  48. [
  49. [1, 2],
  50. [
  51. [3, [4, 5, 6]], 7
  52. ], 8
  53. ],
  54. [
  55. 1,
  56. [
  57. 2,
  58. [
  59. 3,
  60. [
  61. 4,
  62. [5, 6]
  63. ],
  64. 7
  65. ],
  66. 8
  67. ],
  68. 9
  69. ],
  70. [
  71. 1,
  72. [
  73. 2,
  74. [
  75. 3,
  76. [
  77. [
  78. 4,
  79. [5, 6]
  80. ]
  81. ],
  82. 7
  83. ],
  84. 8
  85. ],
  86. 9
  87. ]
  88. ];
  89. for (var i = 0; i < tests.length; i++) {
  90. print(printTree(tests[i]).join('\n'));
  91. print('\n')
  92. }




As you can see, on each iteration we "increment" accumulator with string, and returns whole string when recursion is over.







You can check it in action at: ideone.com/tP5KTC

@темы: JavaScript, algorithms, permutations

00:00 

ExtJs Array series fill color

Vi Veri Veniversum Vivus Vici
  1. Ext.override(Ext.chart.series.Area, {
  2. drawSeries: function() {
  3. var result,
  4. style = this.colorArrayStyle,
  5. copy,
  6. idx = this.themeIdx,
  7. fill;
  8. if (this.style.fill) {
  9. copy = Ext.Array.clone(style);
  10. fill = Ext.isArray(this.style.fill) ? this.style.fill : [this.style.fill];
  11. Ext.each(fill, function(color, index) {
  12. style[idx + index] = color;
  13. });
  14. }
  15. result = this.callParent(arguments);
  16. this.colorArrayStyle = copy;
  17. return result;
  18. }
  19. });

@темы: ExtJS 4, JavaScript

12:29 

Wordwrap long words inside HTML with JavaScript

Vi Veri Veniversum Vivus Vici
  1. var wordwrap = function(value, width, separator) {
  2. width = width || 75;
  3. separator = separator || '<br>';
  4. if ((typeof(value) === 'string') && value) {
  5. var main = new RegExp('(\\s*)([^><]{' + width + ',})(<|$)', 'g');
  6. value = value.replace(main, function(full, before, v, after) {
  7. var regex = new RegExp('\\S{' + width + '}', 'g'),
  8. match,
  9. matches = [before],
  10. lastIndex = 0;
  11. while ((match = regex.exec(v)) != null) {
  12. if (lastIndex < match.index) {
  13. matches.push(v.substring(lastIndex, match.index));
  14. }
  15. matches.push(match[0] + separator);
  16. lastIndex = regex.lastIndex;
  17. }
  18. matches.push(v.substring(lastIndex));
  19. matches.push(after);
  20. return matches.join('');
  21. });
  22. }
  23. return value;
  24. };

@темы: JavaScript

23:26 

Задачка от Яндекса; Longest subarayy with equal count of 0 and 1

Vi Veri Veniversum Vivus Vici
Дан массив длины n из нулей и единиц. Найдите в нём подмассив макисмальной длины, в котором количество единиц равно количеству нулей. Ограничения: O(n) по времени и O(n) по дополнительной памяти.

  1. function getLongest(s) {
  2. var begin = 0,
  3. finish = 0,
  4. len = 0,
  5. b = {},
  6. sum = 0,
  7. i,
  8. n = s.length;
  9. prefix,
  10. padding = '',
  11. cursor;
  12. for (i = -n; i < n; i++) {
  13. b[i] = null;
  14. }
  15. b[0] = -1;
  16. for (i = 0; i < n; i++) {
  17. sum += (s[i] == 1 ? 1 : -1);
  18. if (b[sum] == null) {
  19. b[sum] = i;
  20. console.log('for sum = ' + sum + ' index = ' + i);
  21. } else {
  22. console.log('for sum = ' + sum + ' at index = ' + i + ' b = ' + b[sum]);
  23. if (len < i - b[sum]) {
  24. begin = b[sum] + 1;
  25. finish = i;
  26. len = i - b[sum];
  27. console.log('begin = ' + begin + ' finish = ' + finish + ' len = ' + len);
  28. }
  29. }
  30. }
  31. if (begin === finish) {
  32. console.log('No subarray');
  33. return;
  34. }
  35. prefix = '['+begin+':'+finish+'] = ';
  36. for (i = 0; i < prefix.length + s.length; i++) {
  37. cursor = i - prefix.length;
  38. padding += (cursor === begin || cursor === finish) ? '^' : ' ';
  39. }
  40. console.log(prefix + s);
  41. console.log(padding)
  42. console.log(padding.substr(0, prefix.length + begin) + s.substr(begin, finish - begin + 1));
  43. }
  44. (function(tests) {
  45. var i, j, s, len;
  46. for (i = 0; i < tests; i++) {
  47. len = Math.round(Math.random() * 10) + 1;
  48. s = '';
  49. for (j = 0; j < len; j++) {
  50. s += Math.round(Math.random());
  51. }
  52. console.log(s);
  53. getLongest(s);
  54. }
  55. })(3);

@темы: Algorithms, JavaScript, PHP

12:36 

JSLint Unexpected sync method in PHPStorm

Vi Veri Veniversum Vivus Vici
I have code like this:



So I got this error.

Explanation: jslinterrors.com/unexpected-sync-method-a/
Solution: go to PHPStorm settings, find JSLint and check "stupidity"

@темы: JavaScript, JSLint

02:03 

ExtJS 4.2.1 nested grids/panels/etc. in RowExpander issue

Vi Veri Veniversum Vivus Vici
As I see, in 4.2.1 all content of them does not recover after grid view refreshing (for example, after page navigation) - it only recovers text context of rowTpl. So I did following workaround:

  1. viewBodyExpandEventHandler: function (row, r) {
  2. if (!row.grid) {
  3. this.gridCreateRoutine(row, r.get('id'));
  4. }
  5. },
  6. viewRevreshEventHandler: function () {
  7. // Of course, in init method of my controller this.hashOfGrids = {};
  8. Ext4.Object.each(this.hashOfGrids, function(id, data) {
  9. this.createRowGrid(data.el, data.id);
  10. }, this);
  11. },
  12. gridCreateRoutine: function(row, id) {
  13. var l = 'renderdiv' + id,
  14. el = Ext.fly(layer);
  15. if (el) {
  16. el.setHTML('');
  17. Ext.create('Ext.grid.Panel', {
  18. renderTo : l,
  19. });
  20. this.hashOfGrids[id] = {
  21. el : row,
  22. id : id
  23. };
  24. }
  25. },
  26.  

@темы: долгая ебля с экстом, rowexpander, extjs 4.2.1, JavaScript, ExtJS 4

14:02 

Generate all combinations JavaScript

Vi Veri Veniversum Vivus Vici
  1. var a = [
  2. ['a', 'b', 'c'],
  3. ['e', 'f'],
  4. ['g', 'h', 'i', 'j'],
  5. ['k']
  6. ];
  7.  
  8. var f = function (data, i) {
  9. var result = [],
  10. tmp,
  11. j, k,
  12. variants;
  13. // start from 0 index of data at function launch if index wasn't passed
  14. i = i || 0;
  15. // in case i is greater then array bound, just return empty array
  16. if (i < data.length) {
  17. for (j = 0; j < data[i].length; j++) {
  18. variants = f(data, i + 1);
  19. // if there aren't variants, just create array of one element which is empty array itself
  20. if (!variants.length) {
  21. variants = [
  22. []
  23. ];
  24. }
  25. for (k = 0; k < variants.length; k++) {
  26. // concat variants and current iterable element
  27. tmp = [data[i][j]].concat(variants[k]);
  28. result.push(tmp);
  29. }
  30. }
  31. }
  32. return result;
  33. }
  34.  
  35. console.log(f(a));

@темы: JavaScript, algorithms, combinatoric

12:01 

Распределение чисел

Vi Veri Veniversum Vivus Vici
Пусть требуется распределить некую сумму по частям в массиве, притом каждая часть в массиве должна достаточно сильно отличаться от другой.
В примере части отличаются в 1,5 раза от предыдущей, помноженного на индекс элемента (без такого умножения разница межу соседями будет значительно меньшей)
Первая функция считает вес первого элемента, а вторая - проверяет корректность подсчетов

  1. function t(arr) {
  2. var d = 1,
  3. x = 1,
  4. i = 1,
  5. len = arr.length;
  6. for (; i < len; i++) {
  7. x *= 1.5;
  8. d += x * i;
  9. }
  10. d = len / d;
  11. return d;
  12. }
  13.  
  14. function test(d, arr, s) {
  15. var i = 0,
  16. x = 0,
  17. k,
  18. len = arr.length,
  19. w = s / arr.length,
  20. wp = 0;
  21. console.log('w = ' + w);
  22. for (; i < len; i++) {
  23. if (!i) {
  24. k = d;
  25. }
  26. else {
  27. k = i * Math.pow(1.5, i) * d;
  28. }
  29. console.log('k = ' + k);
  30. console.log('chunk for ' + i + ' is ' + k * w);
  31. wp += k * w;
  32. x += k;
  33. console.log('x = ' + x);
  34. }
  35. console.log('wp = ' + wp);
  36. return x;
  37. }
  38.  
  39. var sum = 6,
  40. a = [0, 1, 2],
  41. delta = t(a);
  42. console.log(delta);
  43. console.log(test(delta, a, sum));

@темы: JavaScript

11:22 

Custom overflowHandler in ExtJS 4 (Part 1)

Vi Veri Veniversum Vivus Vici
We need to implement overflowHandler for toolbar layout, which will add second toolbar and wraps components from first toolbar to second when them cannot be displayed because there isn't enough width of toolbar's container.
First, we need to override Ext.panel.Panel:
  1. Ext4.override(Ext4.panel.Panel, {
  2. bridgeToolbars : function () {
  3. var toolbar;
  4. this.callParent(arguments);
  5. if (this.tbar2) {
  6. if (Ext4.isArray(this.tbar2)) {
  7. toolbar = {
  8. xtype : 'toolbar',
  9. items : this.tbar2
  10. };
  11. }
  12. else if (!toolbar.xtype) {
  13. toolbar.xtype = 'toolbar';
  14. }
  15. toolbar.dock = 'top';
  16. toolbar.isTbar2 = true;
  17. this.dockedItems = this.dockedItems.concat(toolbar);
  18. this.tbar2 = null;
  19. }
  20. },
  21. onRender : function () {
  22. this.callParent(arguments);
  23. var topBars = this.getDockedItems('toolbar[dock="top"]'),
  24. i,
  25. len;
  26. for (i = 0, len = topBars.length; i < len; i++) {
  27. if (topBars[i].isTbar2) {
  28. this.tbar2 = topBars[i];
  29. break;
  30. }
  31. }
  32. },
  33. /**
  34.   * Creates, if not exists, and returns toolbar at passed position
  35.   * @param {Ext.panel.Panel} panel
  36.   * @param {String} position
  37.   * @return {Ext.toolbar.Toolbar}
  38.   */
  39. getDynamicTBar : function (position) {
  40. var panel = this,
  41. params,
  42. tb;
  43. position = position || 'top';
  44. if (position === 'tbar2') {
  45. tb = panel.tbar2;
  46. params = {
  47. dock : 'top',
  48. isTbar2 : true,
  49. layout : {
  50. overflowHandler : 'Scroller'
  51. }
  52. };
  53. }
  54. else {
  55. tb = panel.getDockedItems('toolbar[dock="' + position + '"]');
  56. params = {dock : position};
  57. if (tb.length > 0) {
  58. tb = tb[0];
  59. }
  60. }
  61. if (!tb) {
  62. tb = Ext4.create('Ext4.toolbar.Toolbar', params);
  63. panel.addDocked(tb);
  64. if (position === 'tbar2') {
  65. panel.tbar2 = tb;
  66. }
  67. }
  68. return tb;
  69. }
  70. });

@темы: ExtJS 4, JavaScript

11:22 

Custom overflowHandler in ExtJS 4 (Part 2)

Vi Veri Veniversum Vivus Vici
Next, we need to create class Ext4.layout.container.boxOverflow.TBar2 (it has so long name because ExtJS searches handleOverflow (which is instance of String) in hardcoded Ext4.layout.container.boxOverflow namespace).

читать дальше


@темы: ExtJS 4, JavaScript

15:20 

JavaScript static members of class

Vi Veri Veniversum Vivus Vici
This example shows how to share property between class instances and use static methods. We need to use 'for' loop instead of Array.prototype.concat because in case we'll use 'concat' method, we'll assign static array to instance of class, not to prototype of class constructor. So, we need to loop over an array and use 'push' method.

  1. function MyObject(title){
  2. this.title = title;
  3. this.test = function() {
  4. console.log('test from ' + this.title);
  5. console.log(this.staticItemsMember.join(' - '));
  6. }
  7. }
  8.  
  9.  
  10. MyObject.prototype = {
  11. staticItemsMember : [1, 2, 3],
  12. addItems : function(items) {
  13. var title = this.title || 'was called from constructor method',
  14. i = 0, l;
  15. console.log('add items in function of class instance (' + title + ')');
  16. if (!(items instanceof Array)) {
  17. items = [items];
  18. }
  19. for (l = items.length; i < l; i++) {
  20. this.staticItemsMember.push(items[i]);
  21. }
  22. }
  23. }
  24.  
  25.  
  26.  
  27. MyObject.addItems = function(items) {
  28. console.log('add items in function of class constructor');
  29. this.prototype.addItems(items);
  30. }
  31.  
  32.  
  33. var o = new MyObject('o');
  34. o.test();
  35. MyObject.addItems([5, 6]);
  36. o.test();
  37. o.addItems([8, 9, 10]);
  38. o.test();
  39. MyObject.addItems(11);
  40. o.test();
  41. var m = new MyObject('m');
  42. m.test();
  43. m.addItems([12, 13]);
  44. o.test();
  45. m.test();
  46. MyObject.addItems([14, 15, 16, 17]);
  47. m.test();
  48. o.test();
  49. o.addItems([18, 19, 20]);
  50. m.test();
  51. o.test();


This will output in browser's console text like:
  1.  
  2.  
  3. >>> function MyObject(title){ this.title = title...); o.addItems([18, 19, 20]); m.test(); o.test();
  4.  
  5. test from o
  6.  
  7. 1 - 2 - 3
  8.  
  9. add items in function of class constructor
  10.  
  11. add items in function of class instance (was called from constructor method)
  12.  
  13. test from o
  14.  
  15. 1 - 2 - 3 - 5 - 6
  16.  
  17. add items in function of class instance (o)
  18.  
  19. test from o
  20.  
  21. 1 - 2 - 3 - 5 - 6 - 8 - 9 - 10
  22.  
  23. add items in function of class constructor
  24.  
  25. add items in function of class instance (was called from constructor method)
  26.  
  27. test from o
  28.  
  29. 1 - 2 - 3 - 5 - 6 - 8 - 9 - 10 - 11
  30.  
  31. test from m
  32.  
  33. 1 - 2 - 3 - 5 - 6 - 8 - 9 - 10 - 11
  34.  
  35. add items in function of class instance (m)
  36.  
  37. test from o
  38.  
  39. 1 - 2 - 3 - 5 - 6 - 8 - 9 - 10 - 11 - 12 - 13
  40.  
  41. test from m
  42.  
  43. 1 - 2 - 3 - 5 - 6 - 8 - 9 - 10 - 11 - 12 - 13
  44.  
  45. add items in function of class constructor
  46.  
  47. add items in function of class instance (was called from constructor method)
  48.  
  49. test from m
  50.  
  51. 1 - 2 - 3 - 5 - 6 - 8 - 9 - 10 - 11 - 12 - 13 - 14 - 15 - 16 - 17
  52.  
  53. test from o
  54.  
  55. 1 - 2 - 3 - 5 - 6 - 8 - 9 - 10 - 11 - 12 - 13 - 14 - 15 - 16 - 17
  56.  
  57. add items in function of class instance (o)
  58.  
  59. test from m
  60.  
  61. 1 - 2 - 3 - 5 - 6 - 8 - 9 - 10 - 11 - 12 - 13 - 14 - 15 - 16 - 17 - 18 - 19 - 20
  62.  
  63. test from o
  64.  
  65. 1 - 2 - 3 - 5 - 6 - 8 - 9 - 10 - 11 - 12 - 13 - 14 - 15 - 16 - 17 - 18 - 19 - 20

@темы: JavaScript

15:41 

use strict within ExtJS 4.1

Vi Veri Veniversum Vivus Vici
I've created mixin to dynamically add 'use strict' literal to the start of functions in classes.
First, we need to create cache of keys which contains in second parameter of Ext.define:
  1. (function () {
  2. var old = Ext4.define,
  3. del = [
  4. 'extend', 'mixins', 'statics', 'strictMethods',
  5. 'constructor', 'init', 'notStrictMethods', 'initComponent'
  6. ],
  7. res;
  8. // save keys in cache and delete potentially unsafe keys
  9. window.StrictCache = {};
  10. Ext4.define = function (name, data) {
  11. res = Ext4.Object.getKeys(data);
  12. if (data.statics) {
  13. if (Ext4.isArray(data.statics.notStrictMethods)) {
  14. del = Ext4.Array.merge(del, data.statics.notStrictMethods);
  15. }
  16. res = Ext4.Array.merge(res, Ext4.Object.getKeys(data.statics));
  17. }
  18. res = Ext4.Array.unique(res);
  19. if (Ext4.isArray(data.notStrictMethods)) {
  20. del = Ext4.Array.merge(del, data.notStrictMethods);
  21. }
  22. Ext4.each(del, function (toDelete) {
  23. Ext4.Array.remove(res, toDelete);
  24. });
  25. StrictCache[name] = res;
  26. return old.apply(this, arguments);
  27. };
  28. })();

Next, we must to write mixin:
  1. /**
  2.  * @class Lib.StrictMixin
  3.  * Mixin class for 'use strict'
  4.  * @author guyfawkes
  5.  * @docauthor guyfawkes
  6.  */
  7. Ext4.define('Lib.StrictMixin', {
  8. onClassMixedIn : function (mixedClass) {
  9. var fn;
  10. // mixedClass can be both class prototype or constructor (in this case we need to get function from its prototype)
  11. // please note we don't break loop when strictMethods were found: it must be both in 'statics' and non-static of ExtJS 4's class
  12. Ext4.each([mixedClass, mixedClass.prototype], function (obj, index) {
  13. fn = function(method) {
  14. if (Ext4.isFunction(obj[method])) {
  15. console && console.info(
  16. Ext4.String.format(
  17. '{0} found in {1} of {2}',
  18. method, (index ? 'constructor prototype' : 'prototype'), obj.$className
  19. )
  20. );
  21. obj[method] = new Function("'use strict';nreturn " + obj[method].toString())();
  22. }
  23. };
  24. // if we need to loop over all methods, get keys from cache (or we'll get functions from parent classes and got an error
  25. if (Ext4.isString(obj.strictMethods) && (obj.strictMethods === 'ALL') && Ext4.isString(obj.$className)) {
  26. Ext4.each(StrictCache[obj.$className], fn);
  27. }
  28. else {
  29. // if strictMethods is an array, loop over it
  30. if (Ext4.isArray(obj.strictMethods)) {
  31. Ext4.each(obj.strictMethods, fn);
  32. }
  33. }
  34. });
  35. }
  36. });

@темы: ExtJS 4, JavaScript, use strict

17:11 

ExtJS add custom text to the fieldset label

Vi Veri Veniversum Vivus Vici
  1. var x = Ext.getCmp('ext-comp-1404').el;
  2. x.first().createChild({tag: 'span', html: ' (test message)'});

@темы: ExtJS, JavaScript

19:11 

CLI-like table in JavaScript and ExtJS

Vi Veri Veniversum Vivus Vici
  1. /**
  2.   * Returns ASCII-table in CLI-like style
  3.   * @param {Array} data array of rows like key=>value
  4.   * @param {Object} headers hash of table's headers like key=>title
  5.   * @return {String}
  6.   */
  7. cliTable = function (data, headers) {
  8. var cellLengths = {},
  9. result,
  10. cell,
  11. cellLength,
  12. bar = '+',
  13. header = '|',
  14. padRight = function (value, maxLen, character) {
  15. if (!Ext4.isString(value)) {
  16. value = value.toString();
  17. }
  18. while (value.length < maxLen) {
  19. value += character;
  20. }
  21. return value;
  22. };
  23. Ext4.each(data, function (row) {
  24. Ext4.Object.each(headers, function (key) {
  25. cellLength = row[key].toString().length;
  26. if (!cellLengths[key] || (cellLengths[key] < cellLength)) {
  27. cellLengths[key] = cellLength;
  28. }
  29. });
  30. });
  31. Ext4.Object.each(headers, function (key, value) {
  32. cellLength = cellLengths[key];
  33. bar += Ext4.String.repeat('-', cellLength + 2) + '+';
  34. if (value.length > cellLength) {
  35. value = value.substr(0, cellLength);
  36. }
  37. header += ' ' + padRight(value, cellLength, ' ') + ' |';
  38. });
  39. result = bar + 'n' + header + 'n' + bar + 'n';
  40. Ext4.each(data, function (row) {
  41. result += '|';
  42. Ext4.Object.each(row, function (key, value) {
  43. result += ' ' + padRight(value, cellLengths[key], ' ') + ' |';
  44. });
  45. result += 'n';
  46. });
  47. result += bar;
  48. return result;
  49. }

@темы: ExtJS 4, JavaScript

02:27 

JavaScript clasterise data

Vi Veri Veniversum Vivus Vici
  1. var s1 = Math.round(Math.random() * 10),
  2. s2 = 10 + Math.round(Math.random() * 10),
  3. n = Math.round(Math.random() * 5) + 2,
  4. i, clusters = {}, center, d = (s2 - s1) / n;
  5.  
  6. console.log('Clustering from ' + s1 + ' to ' + s2 + ' by ' + n + ' clusters');
  7. for (i = s1; i < s2; i++) {
  8. center = 'cluster_' + (s1 + Math.floor( (i - s1) / (s2 - s1) * n ) * d).toString();
  9. clusters[center] = (clusters[center] || []).concat(i);
  10. console.log( center + ' <- ' + i );
  11. }
  12.  
  13. console.log(clusters)

@темы: JavaScript

12:14 

HTMLInputElement set Array as value

Vi Veri Veniversum Vivus Vici
  1. var input = document.createElement('input');
  2. input.type = "text";
  3. document.getElementById('answer-5258595').appendChild(input);
  4. var a = ['1', 2222, {x:3}, [4,6,7], ['lol', 'hui']];
  5.  
  6. for (var i = 0, len = a.length; i < len; i++) {
  7. var fn = function(index) {
  8. input.value = a[index];
  9. };
  10. fn = fn.bind(window, i);
  11. setTimeout(fn, 100 + i * 5000);
  12. }


As you can see, objects convert into '[object Object]', and arrays convert into string which consists of their elements joined by ',' (without space).

@темы: JavaScript

11:47 

Динамически скрывать иконки в Ext.grid.column.Action

Vi Veri Veniversum Vivus Vici
Для этого пришлось разобраться с новой системой обращения к частям грида и воспользоваться непосредственно манипуляциями с DOM:

  1. Ext.create('Ext.data.Store', {
  2. storeId:'employeeStore',
  3. fields:['firstname', 'lastname', 'senority', 'dep', 'hired'],
  4. data:[
  5. {firstname:"Michael", lastname:"Scott"},
  6. {firstname:"Dwight", lastname:"Schrute"},
  7. {firstname:"Jim", lastname:"Halpert"},
  8. {firstname:"Kevin", lastname:"Malone"},
  9. {firstname:"Angela", lastname:"Martin"}
  10. ]
  11. });
  12.  
  13. var toggleIcons = function(grid, rowIndex, colIndex, firstAction) {
  14. var actions = { indexes: {show : 0, hide : 1}, acts: ['show', 'hide'] };
  15. var rec = grid.getStore().getAt(rowIndex);
  16. var col = grid.getHeaderCt().getHeaderAtIndex(colIndex);
  17. var el = grid.getCell(rec, col).child('div');
  18. var index = actions.indexes[firstAction];
  19. var a = actions.acts;
  20. el.child('img')[a[index]]().next('img')[a[1 - index]]();
  21. }
  22.  
  23. Ext.create('Ext.grid.Panel', {
  24. title: 'Action Column Demo',
  25. store: Ext.data.StoreManager.lookup('employeeStore'),
  26. columns: [
  27. {text: 'First Name', dataIndex:'firstname'},
  28. {text: 'Last Name', dataIndex:'lastname'},
  29. {
  30. xtype:'actioncolumn',
  31. width:50,
  32. items: [{
  33. icon: 'extjs/examples/shared/icons/fam/cog_edit.png', // Use a URL in the icon config
  34. tooltip: 'Edit',
  35. handler: function(grid, rowIndex, colIndex) {
  36. toggleIcons(grid, rowIndex, colIndex, 'hide');
  37. }
  38. },{
  39. icon: 'extjs/examples/restful/images/delete.png',
  40. tooltip: 'Delete',
  41. hidden: true,
  42. handler: function(grid, rowIndex, colIndex) {
  43. toggleIcons(grid, rowIndex, colIndex, 'show');
  44. }
  45. }]
  46. }
  47. ],
  48. width: 250,
  49. renderTo: Ext.getBody()
  50. });
  51.  


Это немного измененный пример из документации самого экста, куда я добавил свою функцию. Для полной визуальной корректности стоит задать для второй иконки класс iconCls, в котором для нее будет прописано что-то с visibility: hidden (именно так по умолчанию отрабатывает hide). Ну и да, чтобы не повторять аргументы в вызове toggleIcons, можно не описывать их в хендлере, делать [].slice.call(arguments, 0), добавлять в конец параметр действия и вызывать toggleIcons.apply(this, args);

@темы: ExtJS 4, JavaScript

12:02 

Максимальная сумма элементов подмассива (javascript)

Vi Veri Veniversum Vivus Vici
  1. var a = [];
  2.  
  3. for (var i = 0; i < 10; a[i] = Math.round(Math.random() * 10), i++);
  4.  
  5. console && console.log(a);
  6.  
  7. function find(arr) {
  8. var currMin = Infinity;
  9. var currMinIndex = null;
  10. var maxDiff = -Infinity;
  11. var best = {};
  12. for (var i in arr) {
  13. var v = a[i];
  14. if (v < currMin) {
  15. currMin = v;
  16. currMinIndex = i;
  17. }
  18. if (v - currMin > maxDiff) {
  19. maxDiff = v - currMin;
  20. console && console.log('Now max diff from ' + v + ' and ' + currMin + ' is ' + maxDiff);
  21. best = {start: currMinIndex, stop: i, startValue : a[currMinIndex], stopValue : v};
  22. }
  23. }
  24. return best;
  25. }
  26.  
  27. var res = find(a);
  28.  
  29. for (var i in res) {
  30. console && console.log(i + ': ' + res[i]);
  31. }

@темы: JavaScript, Алгоритмы

Small Coder Blog

главная